From d084acf2814279d741b412df9f6f425e89e65ba3 Mon Sep 17 00:00:00 2001 From: bc-travis-ci Date: Thu, 6 Jul 2023 07:08:18 +0000 Subject: [PATCH] chore(release): 1.398.2 [skip ci] --- CHANGELOG.md | 7 +++++++ dist/checkout-button.js | 2 +- dist/checkout-button.umd.js | 2 +- dist/checkout-sdk.js | 2 +- dist/checkout-sdk.js.map | 2 +- dist/checkout-sdk.umd.js | 2 +- dist/checkout-sdk.umd.js.map | 2 +- package-lock.json | 4 ++-- package.json | 2 +- 9 files changed, 16 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 620b667468..85434cbca2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. +### [1.398.2](https://github.com/bigcommerce/checkout-sdk-js/compare/v1.398.1...v1.398.2) (2023-07-06) + + +### Bug Fixes + +* **checkout:** PI-00 fix pending promise for bluesnapdirect APMs iframe ([9acdde7](https://github.com/bigcommerce/checkout-sdk-js/commit/9acdde7c9ce1bd11f3c81d07e87c72c7454de2eb)) + ### [1.398.1](https://github.com/bigcommerce/checkout-sdk-js/compare/v1.398.0...v1.398.1) (2023-07-05) ## [1.398.0](https://github.com/bigcommerce/checkout-sdk-js/compare/v1.397.0...v1.398.0) (2023-07-05) diff --git a/dist/checkout-button.js b/dist/checkout-button.js index 0f2474da82..701c411978 100644 --- a/dist/checkout-button.js +++ b/dist/checkout-button.js @@ -1,2 +1,2 @@ -(()=>{"use strict";var e={n:t=>{var n=t&&t.__esModule?()=>t.default:()=>t;return e.d(n,{a:n}),n},d:(t,n)=>{for(var r in n)e.o(n,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:n[r]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{createCheckoutButtonInitializer:()=>gs,createTimeout:()=>r.createTimeout});var n={};e.r(n),e.d(n,{createApplePayButtonStrategy:()=>Ta,createBoltButtonStrategy:()=>Fa,createPayPalCommerceAlternativeMethodsButtonStrategy:()=>ss,createPayPalCommerceButtonStrategy:()=>ts,createPayPalCommerceCreditButtonStrategy:()=>rs,createPayPalCommerceVenmoButtonStrategy:()=>os,createPaypalExpressButtonStrategy:()=>ms});const r=require("@bigcommerce/request-sender"),i=require("@bigcommerce/form-poster"),o=require("tslib"),a=require("@bigcommerce/data-store"),s=function(e){function t(t){var n,r,i=this.constructor,o=e.call(this,t||"An unexpected error has occurred.")||this;return o.name="StandardError",o.type="standard",n=o,r=i.prototype,Object.setPrototypeOf?Object.setPrototypeOf(n,r):n.__proto__=r,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(o,i):o.stack=new Error(o.message).stack,o}return(0,o.__extends)(t,e),t}(Error);var u={body:{},headers:{},status:0};const c=function(e){function t(t,n){var r=void 0===n?{}:n,i=r.message,o=r.errors,a=this,s=t||u,c=s.body,d=s.headers,p=s.status;return(a=e.call(this,i||"An unexpected error has occurred.")||this).name="RequestError",a.type="request",a.body=c,a.headers=d,a.status=p,a.errors=o||[],a}return(0,o.__extends)(t,e),t}(s),d=function(e){function t(t){var n=e.call(this,t,{message:"There is a problem processing your payment. Please try again later."})||this;return n.name="PaymentMethodInvalidError",n.type="payment_method_invalid",n}return(0,o.__extends)(t,e),t}(c);const p=function(e){function t(t){var n,r,i=this.constructor,o=e.call(this,t||"An unexpected error has occurred.")||this;return o.name="StandardError",o.type="standard",n=o,r=i.prototype,Object.setPrototypeOf?Object.setPrototypeOf(n,r):n.__proto__=r,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(o,i):o.stack=new Error(o.message).stack,o}return(0,o.__extends)(t,e),t}(Error);var l={body:{},headers:{},status:0};const h=function(e){function t(t,n){var r=void 0===n?{}:n,i=r.message,o=r.errors,a=this,s=t||l,u=s.body,c=s.headers,d=s.status;return(a=e.call(this,i||"An unexpected error has occurred.")||this).name="RequestError",a.type="request",a.body=u,a.headers=c,a.status=d,a.errors=o||[],a}return(0,o.__extends)(t,e),t}(p),f=function(e){function t(t,n){var r=e.call(this,t,{message:n||"An unexpected error has occurred. The checkout process cannot continue as a result."})||this;return r.name="UnrecoverableError",r.type="unrecoverable",r}return(0,o.__extends)(t,e),t}(h),m=require("lodash");function g(e){return e.reduce((function(e,t){return t?(0,o.__spreadArrays)(e,[t]):e}),[]).join(" ")}function y(e,t){var n=e.body.errors,r=void 0===n?[]:n;return new h(e,{message:_(r)||t,errors:r})}function _(e){if(Array.isArray(e))return e.reduce((function(e,t){return t&&t.message?(0,o.__spreadArrays)(e,[t.message]):e}),[]).join(" ")}const v=function(e){function t(t){var n=e.call(this,t,{message:"The request has timed out or aborted."})||this;return n.name="TimeoutError",n.type="timeout",n}return(0,o.__extends)(t,e),t}(h),C=function(){function e(){this._factoryMethods={},this.register("default",(function(e,t){return new h(e,{message:t})})),this.register("internal",(function(e,t){return function(e,t){var n=e.body,r=n.errors,i=void 0===r?[]:r;return new h(e,{message:g(i)||n.detail||n.title||t,errors:i.length?i.map((function(e){return{code:n.type,message:e}})):[{code:n.type,message:n.detail||n.title}]})}(e,t)})),this.register("storefront",(function(e,t){return function(e,t){var n=e.body;return new h(e,{message:t||n.detail||n.title,errors:[{code:n.code||n.type,message:n.detail||n.title}]})}(e,t)})),this.register("payment",(function(e,t){return y(e,t)})),this.register("timeout",(function(e){return new v(e)}))}return e.prototype.register=function(e,t){this._factoryMethods[e]=t},e.prototype.createError=function(e,t){return(this._factoryMethods[this._getType(e)]||this._factoryMethods.default)(e,t)},e.prototype._getType=function(e){if(0===e.status)return"timeout";if(this._isStorefrontErrorResponseBody(e.body))return"storefront";if(this._isInternalErrorResponseBody(e.body)){var t=(0,m.last)(e.body.type.split("/"));return t&&this._factoryMethods[t]?t:"internal"}var n=(0,m.last)(e.body&&e.body.errors);return n&&n.code&&this._factoryMethods[n.code]?n.code:"payment"},e.prototype._isStorefrontErrorResponseBody=function(e){var t=e;return!this._isInternalErrorResponseBody(e)&&"string"==typeof t.title&&"string"==typeof t.type&&"number"==typeof t.status&&"string"==typeof t.detail},e.prototype._isInternalErrorResponseBody=function(e){var t=e;return"object"==typeof t.errors&&"string"==typeof t.title&&"string"==typeof t.type&&"number"==typeof t.status},e}(),S=require("rxjs"),I=require("rxjs/operators");var E,w,A,b;function P(e,t){return Array.isArray(e)?e.map((function(e){return P(e,t)})):(0,m.isPlainObject)(e)?(0,m.transform)((0,m.omitBy)(e,t),(function(e,n,r){e[r]=P(n,t)}),{}):e}function O(e,t){return function(e){return e.type===w.ClearError}(t)?P(e,(function(e){return e===t.payload})):e}function T(e,t,n){return e===t||(e&&t&&"object"==typeof e&&"object"==typeof t?Array.isArray(e)&&Array.isArray(t)?function(e,t,n){if(e.length!==t.length)return!1;for(var r=0,i=e.length;r0}})),W=Tn(q,(function(e){return function(t){return!(!t||!t.nonce)||e()===Nn||e()===Ln}})),(0,An.memoizeOne)((function(e,t){return{getPaymentId:U({checkout:e,order:t}),getPaymentIdOrThrow:F({checkout:e,order:t}),getPaymentStatus:q({checkout:e,order:t}),getPaymentStatusOrThrow:B({checkout:e,order:t}),getPaymentToken:G({checkout:e,order:t}),getPaymentTokenOrThrow:x({checkout:e,order:t}),getPaymentRedirectUrl:Y({checkout:e,order:t}),getPaymentRedirectUrlOrThrow:H({checkout:e,order:t}),isPaymentDataRequired:j({checkout:e,order:t}),isPaymentDataSubmitted:W({checkout:e,order:t})}}))),Ae=function(){var e=Tn((function(e){return e.errors.applyError}),(function(e){return function(){return e}})),t=Tn((function(e){return!!e.statuses.isApplying}),(function(e){return function(){return e}}));return(0,An.memoizeOne)((function(n){return void 0===n&&(n=Fn),{getApplyError:e(n),isApplying:t(n)}}))}(),be=function(){var e=Tn((function(e){return e.errors.updateError}),(function(e){return function(){return e}})),t=Tn((function(e){return!!e.statuses.isUpdating}),(function(e){return function(){return e}}));return(0,An.memoizeOne)((function(n){return void 0===n&&(n=gn),{getUpdateError:e(n),isUpdating:t(n)}}))}(),Pe=(K=Tn((function(e){return e.data}),(function(e){return function(){return e}})),Q=Tn((function(e){return e.errors.sendError}),(function(e){return function(){return e}})),J=Tn((function(e){return!!e.statuses.isSending}),(function(e){return function(){return e}})),(0,An.memoizeOne)((function(e){return void 0===e&&(e=an),{getEmail:K(e),getSendError:Q(e),isSending:J(e)}}))),Te=function(){var e=Tn((function(e){return e.data}),(function(e){return function(){return e}})),t=Tn((function(e){return e.data}),(function(e){return function(t){return null==e?void 0:e.find((function(e){return e.region===t}))}})),n=Tn((function(e){return e.errors.loadError}),(function(e){return function(){return e}})),r=Tn((function(e){return e.statuses.isLoading}),(function(e){return function(){return!!e}}));return(0,An.memoizeOne)((function(i){return void 0===i&&(i=Ne),{getExtensions:e(i),getExtensionByRegion:t(i),getLoadError:n(i),isLoading:r(i)}}))}();return function(e,t){void 0===t&&(t={});var n,r=X(e.billingAddress),i=$(e.cart),o=ee(e.checkoutButton),a=ne(e.countries),s=re(e.coupons),u=ie(e.customer),c=ae(e.customerStrategies),d=Te(e.extensions),p=ce(e.formFields),l=se(e.giftCertificates),h=ue(e.instruments),f=Ee(e.orderBillingAddress),m=pe(e.paymentMethods),g=le(e.paymentStrategies),y=he(e.pickupOptions),_=fe(e.remoteCheckout),v=me(e.consignments),C=ye(e.shippingCountries),S=_e(e.shippingStrategies),I=be(e.subscriptions),E=Ae(e.storeCredit),w=Pe(e.signInEmail),A=ve(e.consignments,i),b=Ce(e.checkout,r,i,A,s,u,l),P=Se(e.order,f,s),O=we(b,P),T={billingAddress:r,cart:i,checkout:b,checkoutButton:o,config:te(e.config,e.formFields),consignments:A,countries:a,coupons:s,customer:u,customerStrategies:c,extensions:d,form:p,giftCertificates:l,instruments:h,order:P,orderBillingAddress:f,payment:O,paymentMethods:m,paymentStrategies:g,pickupOptions:y,remoteCheckout:_,shippingAddress:v,shippingCountries:C,shippingStrategies:S,signInEmail:w,subscriptions:I,storeCredit:E};return t.shouldWarnMutation?(n=T,Object.keys(n).reduce((function(e,t){return e[t]=Dn(n[t]),e}),{})):T}}function Bn(e,t){void 0===e&&(e={});var n,r,i=(n=new C,["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((function(e){n.register(e,(function(e,t){return new f(e,t)}))})),n.register("invalid_payment_provider",(function(e){return new d(e)})),n.register("payment_config_not_found",(function(e){return new d(e)})),r=n,function(e){return(0,S.from)(e).pipe((0,I.catchError)((function(e){if(e instanceof Error||e.payload instanceof Error)throw e;if((n=e.payload)&&"object"==typeof n&&["body","headers","status","statusText"].every((function(e){return Object.prototype.hasOwnProperty.call(n,e)}))){var t=e.payload.body&&e.payload.body.detail;throw(0,o.__assign)((0,o.__assign)({},e),{payload:r.createError(e.payload,t)})}var n;throw e})))}),s=qn();return(0,a.createDataStore)((0,a.combineReducers)({billingAddress:k,cart:H,checkout:Sn,checkoutButton:ee,config:ae,consignments:Nt,countries:je,coupons:pe,customer:Ee,customerStrategies:Te,extensions:Le,formFields:Ge,giftCertificates:ye,instruments:wt,orderBillingAddress:ot,order:Je,payment:st,paymentMethods:pt,paymentStrategies:_t,pickupOptions:xt,remoteCheckout:Rt,shippingCountries:Kt,shippingStrategies:en,signInEmail:sn,subscriptions:yn,storeCredit:ln}),e,(0,o.__assign)({actionTransformer:i,stateTransformer:function(e){return s(e)}},t))}function Gn(e,t,n){var r=new WeakMap;function i(e){var n=this;return function(){for(var i,a=[],s=0;s=400&&e.status<500)throw new or(e);throw e}))},e.prototype.updateCheckout=function(e,t,n){var r=void 0===n?{}:n,i=r.params,a=(void 0===i?{}:i).include,s=r.timeout,u="/api/storefront/checkout/"+e,c=(0,o.__assign)({Accept:Vn.JsonV1},jn);return this._requestSender.put(u,{params:{include:rr(ir,a)},body:t,headers:c,timeout:s})},e}(),sr=function(){function e(){}return e.prototype.isEqual=function(e,t){return(0,m.isEqual)(this._normalize(e),this._normalize(t))},e.prototype._normalize=function(e){return{cartAmount:e.cartAmount,currency:e.currency,id:e.id,lineItems:{digitalItems:e.lineItems.digitalItems.slice().sort((function(e,t){return(""+e.productId+e.variantId).localeCompare(""+t.productId+t.variantId)})).map((function(e){return{extendedSalePrice:e.extendedSalePrice,productId:e.productId,quantity:e.quantity,variantId:e.variantId}})),giftCertificates:e.lineItems.giftCertificates.slice().sort((function(e,t){return(""+e.id).localeCompare(""+t.id)})).map((function(e){return{amount:e.amount,recipient:e.recipient}})),physicalItems:e.lineItems.physicalItems.slice().sort((function(e,t){return(""+e.productId+e.variantId).localeCompare(""+t.productId+t.variantId)})).map((function(e){return{extendedSalePrice:e.extendedSalePrice,productId:e.productId,quantity:e.quantity,variantId:e.variantId,giftWrapping:e.giftWrapping}}))}}},e}(),ur=function(e){function t(t,n){var r=e.call(this,"An update to your shopping cart has been detected and your available shipping costs have been updated.")||this;return r.name="CartChangedError",r.type="cart_changed",r.data={previous:t,updated:n},r}return(0,o.__extends)(t,e),t}(p),cr=function(){function e(e){this._checkoutRequestSender=e}return e.prototype.validate=function(e,t){var n=this;if(!e)throw new Pn(bn.MissingCheckout);return this._checkoutRequestSender.loadCheckout(e.id,t).then((function(t){var r=new sr;if(!(e.outstandingBalance===t.body.outstandingBalance&&n._compareCoupons(e.coupons,t.body.coupons)&&n._compareGiftCertificates(e.giftCertificates,t.body.giftCertificates)&&r.isEqual(e.cart,t.body.cart)))throw new ur(n._getComparableCheckout(e),n._getComparableCheckout(t.body))}))},e.prototype._compareCoupons=function(e,t){return(0,m.isEqual)((0,m.map)(e,"code"),(0,m.map)(t,"code"))},e.prototype._compareGiftCertificates=function(e,t){return(0,m.isEqual)((0,m.map)(e,"code"),(0,m.map)(t,"code"))},e.prototype._getComparableCheckout=function(e){var t=e.cart,n=e.coupons,r=e.giftCertificates,i=e.outstandingBalance;return{cart:{cartAmount:t.cartAmount,currency:t.currency,lineItems:t.lineItems},coupons:n,giftCertificates:r,outstandingBalance:i}},e}(),dr=function(){function e(e){this._configRequestSender=e}return e.prototype.loadConfig=function(e){var t=this;return S.Observable.create((function(n){n.next((0,a.createAction)(Q.LoadConfigRequested)),t._configRequestSender.loadConfig(e).then((function(e){n.next((0,a.createAction)(Q.LoadConfigSucceeded,e.body)),n.complete()})).catch((function(e){n.error((0,a.createErrorAction)(Q.LoadConfigFailed,e))}))}))},(0,o.__decorate)([Gn],e.prototype,"loadConfig",null),e}(),pr=function(){function e(e){this._requestSender=e}return e.prototype.loadConfig=function(e){var t=void 0===e?{}:e,n=t.timeout,r=t.params;return this._requestSender.get("/api/storefront/checkout-settings",{timeout:n,headers:(0,o.__assign)({Accept:Vn.JsonV1,"X-API-INTERNAL":Hn},jn),params:r}).catch((function(e){if(e.status>=400&&e.status<500)throw new or(e);throw e}))},e}();function lr(e){var t=e;return"object"==typeof t&&"object"==typeof t.payload&&"string"==typeof t.payload.token}const hr=function(){function e(e,t,n){this._customerRequestSender=e,this._checkoutActionCreator=t,this._spamProtectionActionCreator=n}return e.prototype.createCustomer=function(e,t){var n=this;return function(r){var i=r.getState().config.getStoreConfigOrThrow().checkoutSettings.isStorefrontSpamProtectionEnabled,s=function(i){return(0,S.from)(n._customerRequestSender.createAccount((0,o.__assign)((0,o.__assign)({},e),{token:i}),t)).pipe((0,I.switchMap)((function(){return(0,S.concat)(n._checkoutActionCreator.loadCurrentCheckout(t)(r),(0,S.of)((0,a.createAction)(me.CreateCustomerSucceeded)))})))};return(0,S.concat)((0,S.of)((0,a.createAction)(me.CreateCustomerRequested)),i?(0,S.from)(n._spamProtectionActionCreator.execute()(r)).pipe((0,I.switchMap)((function(e){var t;return lr(e)?(0,S.concat)((0,S.of)(e),s(null===(t=e.payload)||void 0===t?void 0:t.token)):(0,S.of)(e)}))):s()).pipe((0,I.catchError)((function(e){return Qn(me.CreateCustomerFailed,e)})))}},e.prototype.createAddress=function(e,t){var n=this;return(0,S.concat)((0,S.of)((0,a.createAction)(me.CreateCustomerAddressRequested)),(0,S.defer)((function(){return(0,o.__awaiter)(n,void 0,void 0,(function(){var n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._customerRequestSender.createAddress(e,t)];case 1:return n=r.sent().body,[2,(0,a.createAction)(me.CreateCustomerAddressSucceeded,n)]}}))}))}))).pipe((0,I.catchError)((function(e){return Qn(me.CreateCustomerAddressFailed,e)})))},e.prototype.signInCustomer=function(e,t){var n=this;return function(r){return(0,S.concat)((0,S.of)((0,a.createAction)(me.SignInCustomerRequested)),(0,S.from)(n._customerRequestSender.signInCustomer(e,t)).pipe((0,I.switchMap)((function(e){var i=e.body;return(0,S.concat)(n._checkoutActionCreator.loadCurrentCheckout(t)(r),(0,S.of)((0,a.createAction)(me.SignInCustomerSucceeded,i.data)))})))).pipe((0,I.catchError)((function(e){return Qn(me.SignInCustomerFailed,e)})))}},e.prototype.signOutCustomer=function(e){var t=this;return function(n){return(0,S.concat)((0,S.of)((0,a.createAction)(me.SignOutCustomerRequested)),(0,S.from)(t._customerRequestSender.signOutCustomer(e)).pipe((0,I.switchMap)((function(r){var i=r.body;return(0,S.concat)(t._checkoutActionCreator.loadCurrentCheckout(e)(n),(0,S.of)((0,a.createAction)(me.SignOutCustomerSucceeded,i.data)))})))).pipe((0,I.catchError)((function(e){return Qn(me.SignOutCustomerFailed,e)})))}},e}(),fr=function(){function e(e){this._requestSender=e}return e.prototype.createAccount=function(e,t){var n=(void 0===t?{}:t).timeout;return this._requestSender.post("/api/storefront/customer",{timeout:n,headers:jn,body:e})},e.prototype.createAddress=function(e,t){var n=(void 0===t?{}:t).timeout;return this._requestSender.post("/api/storefront/customer-address",{timeout:n,headers:jn,body:e})},e.prototype.signInCustomer=function(e,t){var n=(void 0===t?{}:t).timeout;return this._requestSender.post("/internalapi/v1/checkout/customer",{timeout:n,headers:jn,body:e})},e.prototype.signOutCustomer=function(e){var t=(void 0===e?{}:e).timeout;return this._requestSender.delete("/internalapi/v1/checkout/customer",{timeout:t,headers:jn})},e}(),mr=function(){function e(e){this._formFieldsRequestSender=e}return e.prototype.loadFormFields=function(e){var t=this;return(0,S.concat)((0,S.of)((0,a.createAction)(ke.LoadFormFieldsRequested)),(0,S.defer)((function(){return(0,o.__awaiter)(t,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return[4,this._formFieldsRequestSender.loadFields(e)];case 1:return t=n.sent().body,[2,(0,a.createAction)(ke.LoadFormFieldsSucceeded,t)]}}))}))}))).pipe((0,I.catchError)((function(e){return Qn(ke.LoadFormFieldsFailed,e)})))},(0,o.__decorate)([Gn],e.prototype,"loadFormFields",null),e}(),gr=function(){function e(e){this._requestSender=e}return e.prototype.loadFields=function(e){var t=(void 0===e?{}:e).timeout;return this._requestSender.get("/api/storefront/form-fields",{timeout:t,headers:(0,o.__assign)({Accept:Vn.JsonV1,"X-API-INTERNAL":Hn},jn)})},e}(),yr=function(e){var t=this,n=new Promise((function(e,n){t.cancel=n}));this.promise=Promise.race([e,n])},_r=function(e){function t(t){var n=e.call(this,t||"Unable to proceed because the required element is unexpectedly detached from the page.")||this;return n.name="UnexpectedDetachmentError",n.type="unexpected_detachment",n}return(0,o.__extends)(t,e),t}(p),vr=function(){function e(e){this._mutationObserver=e}return e.prototype.ensurePresence=function(e,t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r,i,a;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:n=new yr(t),(r=this._mutationObserver.create((function(t){t.forEach((function(t){0!==Array.from(t.removedNodes).filter((function(t){return e.some((function(e){return t===e||t.contains(e)}))})).length&&n.cancel(new _r)}))}))).observe(document.body,{childList:!0,subtree:!0}),o.label=1;case 1:return o.trys.push([1,3,,4]),[4,n.promise];case 2:return i=o.sent(),r.disconnect(),[2,i];case 3:throw a=o.sent(),r.disconnect(),a;case 4:return[2]}}))}))},e}();var Cr=function(){function e(e){void 0===e&&(e=window),this._window=e}return e.prototype.create=function(e){return new this._window.MutationObserver(e)},e}();const Sr=function(e){function t(t){var n=e.call(this,t||"Invalid arguments have been provided.")||this;return n.name="InvalidArgumentError",n.type="invalid_argument",n}return(0,o.__extends)(t,e),t}(p);function Ir(e){if(!/^(https?:)?\/\//.test(e))throw new Sr("The provided URL must be absolute.");var t=document.createElement("a");t.href=e;var n=t.port&&-1!==e.indexOf(t.hostname+":"+t.port)?t.port:"";return{hash:t.hash,hostname:t.hostname,href:t.href,origin:t.protocol+"//"+t.hostname+(n?":"+n:""),pathname:t.pathname,port:n,protocol:t.protocol,search:t.search}}function Er(e,t){return e.type===t}const wr=function(){function e(e,t){this._targetWindow=t,this._targetOrigin="*"===e?"*":Ir(e).origin}return e.prototype.post=function(e,t){var n=this,r=this._targetWindow;if(window!==r){if(!r)throw new Error("Unable to post message because target window is not set.");var i=t&&(0,S.fromEvent)(window,"message").pipe((0,I.filter)((function(e){return e.origin===n._targetOrigin&&Er(e.data,e.data.type)&&-1!==[t.successType,t.errorType].indexOf(e.data.type)})),(0,I.map)((function(e){if(t.errorType===e.data.type)throw e.data;return e.data})),(0,I.take)(1)).toPromise();return r.postMessage(e,this._targetOrigin),i}},e.prototype.setTarget=function(e){this._targetWindow=e},e}(),Ar=function(e,t,n){return t&&n?br(0,t,n):function(e){var t=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return(0,o.__extends)(t,e),t}(e);return Object.getOwnPropertyNames(e.prototype).forEach((function(n){var r=Object.getOwnPropertyDescriptor(e.prototype,n);r&&"constructor"!==n&&Object.defineProperty(t.prototype,n,br(e.prototype,n,r))})),t}(e)};function br(e,t,n){if("function"!=typeof n.value)return n;var r=n.value;return{get:function(){var e=r.bind(this);return Object.defineProperty(this,t,(0,o.__assign)((0,o.__assign)({},n),{value:e})),e},set:function(e){r=e}}}const Pr=function(){function e(e){var t;this._sourceOrigins=[Ir(e).origin,(t=Ir(e),Ir(0===t.hostname.indexOf("www")?t.href:t.href.replace(t.hostname,"www."+t.hostname))).origin],this._isListening=!1,this._listeners={}}return e.prototype.listen=function(){this._isListening||(this._isListening=!0,window.addEventListener("message",this._handleMessage))},e.prototype.stopListen=function(){this._isListening&&(this._isListening=!1,window.removeEventListener("message",this._handleMessage))},e.prototype.addListener=function(e,t){var n=this._listeners[e];n||(this._listeners[e]=n=[]),-1===n.indexOf(t)&&n.push(t)},e.prototype.removeListener=function(e,t){var n=this._listeners[e];if(n){var r=n.indexOf(t);r>=0&&n.splice(r,1)}},e.prototype.trigger=function(e){var t=this._listeners[e.type];t&&t.forEach((function(t){return t(e)}))},e.prototype._handleMessage=function(e){-1!==this._sourceOrigins.indexOf(e.origin)&&Er(e.data,e.data.type)&&this.trigger(e.data)},(0,o.__decorate)([Ar],e.prototype,"_handleMessage",null),e}(),Or=function(e){function t(){var t=e.call(this,"You haven't complete our spam protection challenge. Please try again.")||this;return t.name="SpamProtectionChallengeNotCompletedError",t.type="spam_protection_challenge_not_completed",t}return(0,o.__extends)(t,e),t}(p),Tr=function(e){function t(){var t=e.call(this,"Please complete our human verification challenge and try again.")||this;return t.name="CardingProtectionChallengeNotCompletedError",t.type="carding_protection_challenge_not_completed",t}return(0,o.__extends)(t,e),t}(p),Rr=function(e){function t(){var t=e.call(this,"We were not able to verify that you are not a robot. Please try again.")||this;return t.name="CardingProtectionFailedError",t.type="carding_protection_failed",t}return(0,o.__extends)(t,e),t}(p),Mr=function(){function e(e){this._googleRecaptcha=e}return e.prototype.handle=function(e,t){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(n){return"string"==typeof e?[2,this.handleWithRecaptchaSitekey(e,t)]:[2,this.handleWithPaymentHumanVerificationRequestError(e)]}))}))},e.prototype.handleWithPaymentHumanVerificationRequestError=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(t){switch(t.label){case 0:if(!this._isPaymentHumanVerificationRequest(e))throw e;return[4,this._initialize(e.body.additional_action_required.data.key)];case 1:return t.sent(),[2,this._performRecaptcha()]}}))}))},e.prototype.handleWithRecaptchaSitekey=function(e,t){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if("recaptcha_v2"!==e)throw Error("Human verification method is not supported.");if(!t)throw Error("Recaptcha site key is missing.");return[4,this._initialize(t)];case 1:return n.sent(),[2,this._performRecaptcha()]}}))}))},e.prototype._performRecaptcha=function(){var e=this;return this._googleRecaptcha.execute().pipe((0,I.take)(1)).pipe((0,I.switchMap)((function(t){var n=t.error,r=t.token;return(0,o.__awaiter)(e,void 0,void 0,(function(){return(0,o.__generator)(this,(function(e){if(n instanceof Or)throw new Tr;if(n||!r)throw new Rr;return[2,{type:"recaptcha_v2_verification",data:{human_verification_token:r}}]}))}))}))).toPromise()},e.prototype._initialize=function(e){var t="cardingProtectionContainer",n=document.getElementById(t);return n&&n.parentNode&&n.parentNode.removeChild(n),(n=document.createElement("div")).setAttribute("id",t),document.body.appendChild(n),this._googleRecaptcha.load(t,e)},e.prototype._isPaymentHumanVerificationRequest=function(e){var t=e.body||{},n=t.additional_action_required;return"additional_action_required"===t.status&&n&&"recaptcha_v2_verification"===n.type},e}();var Dr;!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"}(Dr||(Dr={}));const kr=function(e){function t(t){var n=e.call(this,function(e){switch(e){case Dr.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case Dr.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case Dr.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case Dr.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."}}(t))||this;return n.subtype=t,n.name="NotInitializedError",n.type="not_initialized",n}return(0,o.__extends)(t,e),t}(p),Nr=function(e){function t(){var t=e.call(this,"We were not able to complete your spam protection verification. Please try again.")||this;return t.name="SpamProtectionFailedError",t.type="spam_protection_failed",t}return(0,o.__extends)(t,e),t}(p),Lr=function(e){function t(){var t=e.call(this,"Spam protection is not loaded. Please try again.")||this;return t.name="SpamProtectionNotLoadedError",t.type="spam_protection_failed",t}return(0,o.__extends)(t,e),t}(p),zr=function(){function e(e,t){var n=this;this.googleRecaptchaScriptLoader=e,this.mutationObserverFactory=t,this._memoized=(0,An.memoize)((function(e,t,r){var i=new S.Subject;if(!r)throw new Error;return n._widgetId=e.render(r.id,{sitekey:t,size:"invisible",callback:function(){i.next({token:e.getResponse(n._widgetId)}),e.reset(n._widgetId)},"error-callback":function(){i.next({error:new Nr})}}),i}),{isEqual:function(e,t){return e===t}})}return e.prototype.load=function(e,t){var n=this;return this.googleRecaptchaScriptLoader.load().then((function(r){r&&(n._event$=n._memoized(r,t,document.getElementById(e)),n._recaptcha=r)}))},e.prototype.execute=function(){var e=this;return(0,S.defer)((function(){var t=e._event$,n=e._recaptcha;if(!t||!n)throw new kr(Dr.SpamProtectionNotInitialized);return(0,S.defer)((function(){var e=document.querySelector('iframe[src*="bframe"]');return e?(0,S.of)(e):(0,S.throwError)(new Lr)})).pipe((0,I.retryWhen)((function(e){return e.pipe((0,I.delay)(250),(0,I.switchMap)((function(e,t){return t<28?(0,S.of)(e):(0,S.throwError)(e)})))})),(0,I.switchMap)((function(r){return e._watchRecaptchaChallengeWindow(t,r),n.execute(e._widgetId),t})),(0,I.catchError)((function(e){return(0,S.of)({error:e})})))}))},e.prototype._watchRecaptchaChallengeWindow=function(e,t){var n=t.parentElement;if(!n)throw new Lr;var r=n.parentElement;if(!r)throw new Lr;this.mutationObserverFactory.create((function(){"hidden"===r.style.visibility&&e.next({error:new Or})})).observe(r,{attributes:!0,attributeFilter:["style"]})},e}(),Ur=function(){function e(e,t){void 0===t&&(t=window),this._scriptLoader=e,this._window=t}return e.prototype.load=function(){return this._loadPromise||(this._loadPromise=this._loadScript()),this._loadPromise},e.prototype._loadScript=function(){var e=this,t="initRecaptcha",n=["onload="+t,"render=explicit"].join("&");return new Promise((function(r,i){e._window[t]=function(){return r(e._window.grecaptcha)},e._scriptLoader.loadScript("//www.google.com/recaptcha/api.js?"+n).catch((function(t){e._loadPromise=void 0,i(t)}))}))},e}();function Fr(e){return new zr(new Ur(e),new Cr)}const qr=function(e){function t(t){var n=e.call(this,t||"Unable to proceed due to invalid configuration provided for the hosted payment form.")||this;return n.name="InvalidHostedFormConfigError",n.type="invalid_hosted_form_config",n}return(0,o.__extends)(t,e),t}(p),Br=function(e){function t(t){var n=e.call(this,t||"Unable to proceed due to an unknown error with the hosted payment form.")||this;return n.name="InvalidHostedFormError",n.type="invalid_hosted_form",n}return(0,o.__extends)(t,e),t}(p),Gr=function(e){function t(t){var n=e.call(this,(0,o.__spreadArrays)(["Unable to proceed due to invalid user input values"],(0,m.flatMap)((0,m.values)(t),(function(e){return(0,m.map)(e,(function(e){return e.message}))}))).join(". "))||this;return n.errors=t,n.name="InvalidHostedFormValueError",n.type="invalid_hosted_form_value",n}return(0,o.__extends)(t,e),t}(p);var xr,Yr;!function(e){e.AttachRequested="HOSTED_FIELD:ATTACH_REQUESTED",e.SubmitRequested="HOSTED_FIELD:SUBMITTED_REQUESTED",e.ValidateRequested="HOSTED_FIELD:VALIDATE_REQUESTED"}(xr||(xr={})),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"}(Yr||(Yr={}));const Vr=function(){function e(e,t,n,r,i,o,a,s,u){this._type=e,this._containerId=t,this._placeholder=n,this._accessibilityLabel=r,this._styles=i,this._eventPoster=o,this._eventListener=a,this._detachmentObserver=s,this._cardInstrument=u,this._iframe=document.createElement("iframe"),this._iframe.src="/checkout/payment/hosted-field?version=1.398.1",this._iframe.style.border="none",this._iframe.style.height="100%",this._iframe.style.overflow="hidden",this._iframe.style.width="100%"}return e.prototype.getType=function(){return this._type},e.prototype.attach=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,t,n=this;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:if(!(e=document.getElementById(this._containerId)))throw new qr("Unable to proceed because the provided container ID is not valid.");return e.appendChild(this._iframe),this._eventListener.listen(),t=(0,S.fromEvent)(this._iframe,"load").pipe((0,I.switchMap)((function(e){var t=e.target;return(0,o.__awaiter)(n,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if(!(e=t&&t.contentWindow))throw new Error("The content window of the iframe cannot be accessed.");return this._eventPoster.setTarget(e),[4,this._eventPoster.post({type:xr.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:Yr.AttachSucceeded,errorType:Yr.AttachFailed})];case 1:return n.sent(),[2]}}))}))})),(0,I.take)(1)).toPromise(),[4,this._detachmentObserver.ensurePresence([this._iframe],t)];case 1:return r.sent(),[2]}}))}))},e.prototype.detach=function(){this._iframe.parentElement&&(this._iframe.parentElement.removeChild(this._iframe),this._eventListener.stopListen())},e.prototype.submitForm=function(e,t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),n=this._eventPoster.post({type:xr.SubmitRequested,payload:{fields:e,data:t}},{successType:Yr.SubmitSucceeded,errorType:Yr.SubmitFailed}),[4,this._detachmentObserver.ensurePresence([this._iframe],n)];case 1:return[2,i.sent()];case 2:if(r=i.sent(),this._isSubmitErrorEvent(r)){if("hosted_form_error"===r.payload.error.code)throw new Br(r.payload.error.message);if(r.payload.response)throw y(r.payload.response);throw new Error(r.payload.error.message)}throw r;case 3:return[2]}}))}))},e.prototype.validateForm=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return e=this._eventPoster.post({type:xr.ValidateRequested},{successType:Yr.Validated}),[4,this._detachmentObserver.ensurePresence([this._iframe],e)];case 1:if(!(t=n.sent().payload).isValid)throw new Gr(t.errors);return[2]}}))}))},e.prototype._getFontUrls=function(){var e=this,t="fonts.googleapis.com",n=document.querySelectorAll("link[href*='"+t+"'][rel='stylesheet']");return Array.prototype.slice.call(n).filter((function(e){return Ir(e.href).hostname===t})).filter((function(t){return(0,m.values)(e._styles).map((function(e){return e&&e.fontFamily})).filter((function(e){return"string"==typeof e})).some((function(e){return e.split(/,\s/).some((function(e){return-1!==t.href.indexOf(e.replace(" ","+"))}))}))})).map((function(e){return e.href}))},e.prototype._isSubmitErrorEvent=function(e){return e.type===Yr.SubmitFailed},e}(),Hr=function(){function e(e,t,n,r,i){var a=this;this._fields=e,this._eventListener=t,this._payloadTransformer=n,this._eventCallbacks=r,this._paymentHumanVerificationHandler=i,this._handleEnter=function(e){var t=e.payload;return(0,o.__awaiter)(a,void 0,void 0,(function(){var e,n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,this.validate()];case 1:return r.sent(),[3,3];case 2:if("InvalidHostedFormValueError"!==(e=r.sent()).name)throw e;return[3,3];case 3:return(void 0===(n=this._eventCallbacks.onEnter)?m.noop:n)(t),[2]}}))}))};var s=this._eventCallbacks,u=s.onBlur,c=void 0===u?m.noop:u,d=s.onCardTypeChange,p=void 0===d?m.noop:d,l=s.onFocus,h=void 0===l?m.noop:l,f=s.onValidate,g=void 0===f?m.noop:f;this._eventListener.addListener(Yr.Blurred,(function(e){var t=e.payload;return c(t)})),this._eventListener.addListener(Yr.CardTypeChanged,(function(e){var t=e.payload;return p(t)})),this._eventListener.addListener(Yr.Focused,(function(e){var t=e.payload;return h(t)})),this._eventListener.addListener(Yr.Validated,(function(e){var t=e.payload;return g(t)})),this._eventListener.addListener(Yr.Entered,this._handleEnter),this._eventListener.addListener(Yr.CardTypeChanged,(function(e){var t=e.payload;return a._cardType=t.cardType})),this._eventListener.addListener(Yr.BinChanged,(function(e){var t=e.payload;return a._bin=t.bin}))}return e.prototype.getBin=function(){return this._bin},e.prototype.getCardType=function(){return this._cardType},e.prototype.attach=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return this._eventListener.listen(),e=this._getFirstField(),t=(0,m.without)(this._fields,e),[4,e.attach()];case 1:return n.sent(),[4,Promise.all(t.map((function(e){return e.attach()})))];case 2:return n.sent(),[2]}}))}))},e.prototype.detach=function(){this._eventListener.stopListen(),this._fields.forEach((function(e){e.detach()}))},e.prototype.submit=function(e,t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,5]),[4,this._getFirstField().submitForm(this._fields.map((function(e){return e.getType()})),this._payloadTransformer.transform(e,t))];case 1:case 4:return[2,i.sent()];case 2:return n=i.sent(),[4,this._paymentHumanVerificationHandler.handle(n)];case 3:return r=i.sent(),[4,this._getFirstField().submitForm(this._fields.map((function(e){return e.getType()})),this._payloadTransformer.transform(e,r))];case 5:return[2]}}))}))},e.prototype.validate=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(e){return[2,this._getFirstField().validateForm()]}))}))},e.prototype._getFirstField=function(){var e=this._fields[0];if(!e)throw new qr("Unable to proceed because the payment form has no field defined.");return e},e}();function jr(e){return Boolean(e.instrumentId)}const Wr=function(){function e(e){this._store=e}return e.prototype.transform=function(e,t){var n=this._store.getState(),r=n.checkout.getCheckout(),i=n.config.getConfig(),o=n.instruments.getInstrumentsMeta(),a=n.order.getOrder(),s=n.order.getOrderMeta(),u=(0,m.omit)(e.paymentData,"ccExpiry","ccName","ccNumber","ccCvv"),c=n.paymentMethods.getPaymentMethod(e.methodId,e.gatewayId),d=n.paymentMethods.getPaymentMethodsMeta(),p=o&&u&&jr(u)?n.payment.getPaymentToken()+", "+o.vaultAccessToken:n.payment.getPaymentToken();if(!p)throw new Pn(bn.MissingPaymentToken);return{additionalAction:t,authToken:p,checkout:r,config:i,order:a,orderMeta:s,payment:u,paymentMethod:c,paymentMethodMeta:d}},e}(),Kr=function(){function e(e){this._store=e}return e.prototype.create=function(e,t){var n=this,r=Object.keys(t.fields).reduce((function(r,i){var a=t.fields[i];return a?(0,o.__spreadArrays)(r,[new Vr(i,a.containerId,a.placeholder||"",a.accessibilityLabel||"",t.styles||{},new wr(e),new Pr(e),new vr(new Cr),"instrumentId"in a?n._getCardInstrument(a.instrumentId):void 0)]):r}),[]);return new Hr(r,new Pr(e),new Wr(this._store),(0,m.pick)(t,"onBlur","onEnter","onFocus","onCardTypeChange","onValidate"),new Mr(Fr((0,Kn.createScriptLoader)())))},e.prototype._getCardInstrument=function(e){var t=(0,this._store.getState().instruments.getCardInstrument)(e);if(!t)throw new Pn(bn.MissingPaymentInstrument);return t},e}(),Qr=function(e){function t(){var t=e.call(this,"You haven't complete our spam check. Please try again.")||this;return t.name="SpamProtectionNotCompletedError",t.type="spam_protection_not_completed",t}return(0,o.__extends)(t,e),t}(p),Zr=function(){function e(e,t){this._orderRequestSender=e,this._checkoutValidator=t}return e.prototype.loadOrder=function(e,t){var n=this;return new S.Observable((function(r){r.next((0,a.createAction)(ie.LoadOrderRequested)),n._orderRequestSender.loadOrder(e,t).then((function(e){r.next((0,a.createAction)(ie.LoadOrderSucceeded,e.body)),r.complete()})).catch((function(e){r.error((0,a.createErrorAction)(ie.LoadOrderFailed,e))}))}))},e.prototype.loadOrderPayments=function(e,t){var n=this;return new S.Observable((function(r){r.next((0,a.createAction)(ie.LoadOrderPaymentsRequested)),n._orderRequestSender.loadOrder(e,t).then((function(e){r.next((0,a.createAction)(ie.LoadOrderPaymentsSucceeded,e.body)),r.complete()})).catch((function(e){r.error((0,a.createErrorAction)(ie.LoadOrderPaymentsFailed,e))}))}))},e.prototype.loadCurrentOrder=function(e){var t=this;return function(n){return(0,S.defer)((function(){var r=t._getCurrentOrderId(n.getState());if(!r)throw new Pn(bn.MissingOrderId);return t.loadOrder(r,e)}))}},e.prototype.submitOrder=function(e,t){var n=this;return function(r){return(0,S.concat)((0,S.of)((0,a.createAction)(ie.SubmitOrderRequested)),(0,S.defer)((function(){var i=r.getState(),s=i.config.getExternalSource(),u=i.config.getVariantIdentificationToken(),c=i.checkout.getCheckout();if(!c)throw new Pn(bn.MissingCheckout);if(c.shouldExecuteSpamCheck)throw new Qr;return(0,S.from)(n._checkoutValidator.validate(c,t).then((function(){return n._orderRequestSender.submitOrder(n._mapToOrderRequestBody(null!=e?e:{},c.id,c.customerMessage,s),(0,o.__assign)((0,o.__assign)({},t),{headers:{checkoutVariant:u}}))}))).pipe((0,I.switchMap)((function(e){return(0,S.concat)(n.loadOrder(e.body.data.order.orderId,t),(0,S.of)((0,a.createAction)(ie.SubmitOrderSucceeded,e.body.data,(0,o.__assign)((0,o.__assign)({},e.body.meta),{token:e.headers.token}))))})))})).pipe((0,I.catchError)((function(e){return Qn(ie.SubmitOrderFailed,e)}))))}},e.prototype.finalizeOrder=function(e,t){var n=this;return(0,S.concat)((0,S.of)((0,a.createAction)(ie.FinalizeOrderRequested)),(0,S.from)(this._orderRequestSender.finalizeOrder(e,t)).pipe((0,I.switchMap)((function(r){return(0,S.concat)(n.loadOrder(e,t),(0,S.of)((0,a.createAction)(ie.FinalizeOrderSucceeded,r.body.data)))})))).pipe((0,I.catchError)((function(e){return Qn(ie.FinalizeOrderFailed,e)})))},e.prototype._getCurrentOrderId=function(e){var t=e.order.getOrder(),n=e.checkout.getCheckout();return t&&t.orderId||n&&n.orderId},e.prototype._mapToOrderRequestBody=function(e,t,n,r){var i=e.payment,a=(0,o.__rest)(e,["payment"]);return i?(0,o.__assign)((0,o.__assign)({},a),{cartId:t,customerMessage:n,externalSource:r,payment:{paymentData:i.paymentData,name:i.methodId,gateway:i.gatewayId}}):(0,o.__assign)((0,o.__assign)({},a),{cartId:t,customerMessage:n,externalSource:r})},e}(),Jr=function(e){function t(t){var n=e.call(this,t||"Your checkout could not be processed because some details have changed. Please review your order and try again.")||this;return n.name="CartConsistencyError",n.type="cart_consistency",n}return(0,o.__extends)(t,e),t}(p),Xr=function(e){function t(t){var n=e.call(this,t||"The tax provider is unavailable.")||this;return n.name="OrderTaxProviderUnavailableError",n.type="tax_provider_unavailable",n}return(0,o.__extends)(t,e),t}(p),$r=function(){function e(e){this._requestSender=e}return e.prototype.loadOrder=function(e,t){var n=(void 0===t?{}:t).timeout,r="/api/storefront/orders/"+e,i=(0,o.__assign)({Accept:Vn.JsonV1},jn);return this._requestSender.get(r,{params:{include:nr(["payments","lineItems.physicalItems.socialMedia","lineItems.physicalItems.options","lineItems.physicalItems.categories","lineItems.digitalItems.socialMedia","lineItems.digitalItems.options","lineItems.digitalItems.categories"])},headers:i,timeout:n})},e.prototype.submitOrder=function(e,t){var n=void 0===t?{}:t,r=n.headers,i=n.timeout;return this._requestSender.post("/internalapi/v1/checkout/order",{body:e,headers:(0,m.omitBy)((0,o.__assign)({"X-Checkout-Variant":r&&r.checkoutVariant},jn),m.isNil),timeout:i}).catch((function(e){if("tax_provider_unavailable"===e.body.type)throw new Xr;if("cart_has_changed"===e.body.type)throw new Jr;throw e}))},e.prototype.finalizeOrder=function(e,t){var n=(void 0===t?{}:t).timeout,r="/internalapi/v1/checkout/order/"+e;return this._requestSender.post(r,{timeout:n,headers:jn})},e}(),ei=function(){function e(e,t,n,r){var i=this;this._paymentRequestSender=e,this._orderActionCreator=t,this._paymentRequestTransformer=n,this._paymentHumanVerificationHandler=r,this.initializeOffsitePayment=function(e){var t=e.methodId,n=e.gatewayId,r=e.instrumentId,o=e.target,s=e.promise,u=e.shouldSaveInstrument,c=e.shouldSetAsDefaultInstrument;return function(e){var d;r?d={formattedPayload:{bigpay_token:r}}:u&&(d={formattedPayload:{vault_payment_instrument:u,set_as_default_stored_instrument:c||null}});var p=i._paymentRequestTransformer.transform({gatewayId:n,methodId:t,paymentData:d},e.getState());return(0,S.concat)((0,S.of)((0,a.createAction)(nt.InitializeOffsitePaymentRequested)),Promise.race([i._paymentRequestSender.initializeOffsitePayment(p,o),s].filter(Boolean)).then((function(){return(0,a.createAction)(nt.InitializeOffsitePaymentSucceeded)}))).pipe((0,I.catchError)((function(e){return Qn(nt.InitializeOffsitePaymentFailed,e)})))}}}return e.prototype.submitPayment=function(e){var t=this;return function(n){return(0,S.concat)((0,S.of)((0,a.createAction)(nt.SubmitPaymentRequested)),(0,S.defer)((function(){return(0,o.__awaiter)(t,void 0,void 0,(function(){var t,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,5]),[4,this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform(e,n.getState()))];case 1:case 4:return[2,i.sent()];case 2:return t=i.sent(),[4,this._paymentHumanVerificationHandler.handle(t)];case 3:return r=i.sent(),[4,this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform((0,o.__assign)((0,o.__assign)({},e),{additionalAction:r}),n.getState()))];case 5:return[2]}}))}))})).pipe((0,I.switchMap)((function(e){var r=e.body;return(0,S.concat)(t._orderActionCreator.loadCurrentOrder()(n),(0,S.of)((0,a.createAction)(nt.SubmitPaymentSucceeded,r)))})))).pipe((0,I.catchError)((function(e){return Qn(nt.SubmitPaymentFailed,e)})))}},e}(),ti=function(){function e(e){this._client=e}return e.prototype.submitPayment=function(e){var t=this;return new Promise((function(n,r){t._client.submitPayment(e,(function(e,i){e?r(t._transformResponse(e)):n(t._transformResponse(i))}))}))},e.prototype.initializeOffsitePayment=function(e,t){var n=this;return new Promise((function(){n._client.initializeOffsitePayment(e,null,t)}))},e.prototype._transformResponse=function(e){return{headers:e.headers,body:e.data,status:e.status,statusText:e.statusText}},e}(),ni=require("@bigcommerce/bigpay-client");function ri(e,t){var n;return function(e){return void 0!==e.id}(e)?n=e.id:t&&t.length&&(n=t[0].id),{id:n,firstName:e.firstName,lastName:e.lastName,company:e.company,addressLine1:e.address1,addressLine2:e.address2,city:e.city,province:e.stateOrProvince,provinceCode:e.stateOrProvinceCode,postCode:e.postalCode,country:e.country,countryCode:e.countryCode,phone:e.phone,customFields:e.customFields}}const ii=function(){function e(e){this._decimalPlaces=e}return e.prototype.toInteger=function(e){return Math.round(e*Math.pow(10,this._decimalPlaces))},e}();var oi,ai=["per_item_discount","percentage_discount","per_total_discount","shipping_discount","free_shipping"];function si(e){return{code:e.code,discount:e.displayName,discountType:ai.indexOf(e.couponType)}}function ui(e){return{code:e.code,discountedAmount:e.used,remainingBalance:e.remaining,giftCertificate:{balance:e.balance,code:e.code,purchaseDate:e.purchaseDate}}}function ci(e,t,n){return void 0===n&&(n="id"),Object.keys(e).reduce((function(r,i){return(0,o.__spreadArrays)(r,e[i].map((function(e){return"giftCertificates"===i?function(e,t){var n=new ii(t);return{id:e.id,imageUrl:"",name:e.name,amount:e.amount,amountAfterDiscount:e.amount,discount:0,integerAmount:n.toInteger(e.amount),integerAmountAfterDiscount:n.toInteger(e.amount),integerUnitPrice:n.toInteger(e.amount),integerUnitPriceAfterDiscount:n.toInteger(e.amount),integerDiscount:0,quantity:1,sender:e.sender,recipient:e.recipient,type:"ItemGiftCertificateEntity",attributes:[],variantId:null}}(e,t):function(e,t,n,r){void 0===r&&(r="id");var i=new ii(n);return{id:e[r],imageUrl:e.imageUrl,amount:e.extendedListPrice,amountAfterDiscount:e.extendedSalePrice,discount:e.discountAmount,integerAmount:i.toInteger(e.extendedListPrice),integerAmountAfterDiscount:i.toInteger(e.extendedSalePrice),integerDiscount:i.toInteger(e.discountAmount),integerUnitPrice:i.toInteger(e.listPrice),integerUnitPriceAfterDiscount:i.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((function(e){return{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""}}(i),t,n)})))}),[])}function di(e){var t,n,r=e.cart.currency.decimalPlaces,i=new ii(r);return{id:e.cart.id,items:ci(e.cart.lineItems,r),currency:e.cart.currency.code,coupon:{discountedAmount:(0,m.reduce)(e.cart.coupons,(function(e,t){return e+t.discountedAmount}),0),coupons:e.cart.coupons.map(si)},discount:{amount:e.cart.discountAmount,integerAmount:i.toInteger(e.cart.discountAmount)},discountNotifications:(t=e.promotions,n=[],(t||[]).forEach((function(e){(e.banners||[]).forEach((function(e){n.push({placeholders:[],discountType:null,message:"",messageHtml:e.text})}))})),n),giftCertificate:{totalDiscountedAmount:(0,m.reduce)(e.giftCertificates,(function(e,t){return e+t.used}),0),appliedGiftCertificates:(0,m.keyBy)(e.giftCertificates.map(ui),"code")},shipping:{amount:e.shippingCostTotal,integerAmount:i.toInteger(e.shippingCostTotal),amountBeforeDiscount:e.shippingCostBeforeDiscount,integerAmountBeforeDiscount:i.toInteger(e.shippingCostBeforeDiscount),required:(0,m.some)(e.cart.lineItems.physicalItems,(function(e){return 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)}}}!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.MASTERPASS="masterpass",e.PAYPALEXPRESS="paypalexpress"}(oi||(oi={}));const pi=oi;function li(e,t){var n=e.firstName||t.firstName||"",r=e.lastName||t.lastName||"";return{addresses:(e.addresses||[]).map((function(e){return ri(e)})),customerId:e.id,isGuest:e.isGuest,storeCredit:e.storeCredit,email:e.email||t.email||"",firstName:n,lastName:r,name:e.fullName||[n,r].join(" "),customerGroupName:e.customerGroup&&e.customerGroup.name}}const hi=function(){function e(){}return e.prototype.format=function(e){var t=e.split(new RegExp("\\s*/\\s*")),n=t[0],r=void 0===n?"":n,i=t[1],o=void 0===i?"":i,a=r.slice(0,2),s=4===o.length?o.slice(-2):o?o.slice(0,2):r.slice(2);return e.length<2?r:e.length>3&&!s?a:a+" / "+s},e.prototype.toObject=function(e){var t=e.split(new RegExp("\\s*/\\s*")),n=t[0],r=void 0===n?"":n,i=t[1],o=void 0===i?"":i;return/^\d+$/.test(r)&&/^\d+$/.test(o)?{month:1===r.length?"0"+r:r.slice(0,2),year:2===o.length?"20"+o:o.slice(0,4)}:{month:"",year:""}},e}(),fi=require("card-validator"),mi=function(){function e(){}return e.prototype.format=function(e){var t=(0,fi.number)(e).card;if(!t)return e;var n=(0,m.max)((0,fi.creditCardType)(e).map((function(e){return(0,m.max)(e.lengths)}))),r=this.unformat(e).slice(0,n);return t.gaps.filter((function(e){return r.length>e})).reduce((function(e,t,n){return[e.slice(0,t+n),e.slice(t+n)].join(" ")}),r)},e.prototype.unformat=function(e){return(0,fi.number)(e).card?e.replace(new RegExp(" ","g"),""):e},e}();function gi(e,t){void 0===t&&(t={});var n,r,i=e.currency.decimalPlaces,o=new ii(i);return{id:e.orderId,items:ci(e.lineItems,e.currency.decimalPlaces,"productId"),orderId:e.orderId,currency:e.currency.code,customerCanBeCreated:e.customerCanBeCreated,payment:_i(e.payments,t.payment),subtotal:{amount:e.baseAmount,integerAmount:o.toInteger(e.baseAmount)},coupon:{discountedAmount:(0,m.reduce)(e.coupons,(function(e,t){return e+t.discountedAmount}),0),coupons:e.coupons.map(si)},discount:{amount:e.discountAmount,integerAmount:o.toInteger(e.discountAmount)},token:t.orderToken,callbackUrl:t.callbackUrl,discountNotifications:[],giftCertificate:(n=e.payments,r=(0,m.filter)(n,{providerId:"giftcertificate"}),{totalDiscountedAmount:(0,m.reduce)(r,(function(e,t){return t.amount+e}),0),appliedGiftCertificates:(0,m.keyBy)(r.map((function(e){return{code:e.detail.code,discountedAmount:e.amount,remainingBalance:e.detail.remaining,giftCertificate:{balance:e.amount+e.detail.remaining,code:e.detail.code,purchaseDate:""}}})),"code")}),socialData:Ci(e),status:e.status,hasDigitalItems:e.hasDigitalItems,isDownloadable:e.isDownloadable,isComplete:e.isComplete,shipping:{amount:e.shippingCostTotal,integerAmount:o.toInteger(e.shippingCostTotal),amountBeforeDiscount:e.shippingCostBeforeDiscount,integerAmountBeforeDiscount:o.toInteger(e.shippingCostBeforeDiscount)},storeCredit:{amount:yi(e.payments)},taxes:e.taxes,taxTotal:{amount:e.taxTotal,integerAmount:o.toInteger(e.taxTotal)},handling:{amount:e.handlingCostTotal,integerAmount:o.toInteger(e.handlingCostTotal)},grandTotal:{amount:e.orderAmount,integerAmount:e.orderAmountAsInteger}}}function yi(e){var t=(0,m.find)(e,{providerId:"storecredit"});return t?t.amount:0}function _i(e,t){void 0===t&&(t={});var n,r=(0,m.find)(e,vi);return r?{id:r.providerId,status:(n=r.detail.step,"PAYMENT_STATUS_"+n),helpText:r.detail.instructions,returnUrl:t.returnUrl}:{}}function vi(e){return"giftcertificate"!==e.providerId&&"storecredit"!==e.providerId}function Ci(e){var t={};return(0,o.__spreadArrays)(e.lineItems.physicalItems,e.lineItems.digitalItems).forEach((function(e){var n;t[e.id]=(n=e,["fb","tw","gp"].reduce((function(e,t){var r=n.socialMedia&&(0,m.find)(n.socialMedia,(function(e){return e.code===t}));return r?(e[t]={name:n.name,description:n.name,image:n.imageUrl,url:r.link,shareText:r.text,sharingLink:r.link,channelName:r.channel,channelCode:r.code},e):e}),{}))})),t}function Si(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}}const Ii=function(){function e(){this._cardExpiryFormatter=new hi,this._cardNumberFormatter=new mi}return e.prototype.transform=function(e,t){var n,r=t.billingAddress.getBillingAddress(),i=t.checkout.getCheckout(),a=t.customer.getCustomer(),s=t.order.getOrder(),u=t.paymentMethods.getPaymentMethod(e.methodId,e.gatewayId),c=this._mapShippingAddress(t,u),d=t.consignments.getConsignments(),p=t.consignments.getShippingOption(),l=t.config.getStoreConfig(),h=t.config.getContextConfig(),f=t.instruments.getInstrumentsMeta(),g=t.paymentMethods.getPaymentMethodsMeta(),y=t.order.getOrderMeta(),_=a&&r&&li(a,r),v=f&&e.paymentData&&(jr(e.paymentData)||(n=e.paymentData.formattedPayload)&&("string"==typeof n.bigpay_token||Boolean(n.bigpay_token&&n.bigpay_token.token)))?t.payment.getPaymentToken()+", "+f.vaultAccessToken:t.payment.getPaymentToken();if(!v)throw new Pn(bn.MissingPaymentToken);return{additionalAction:e.additionalAction,authToken:v,customer:_,billingAddress:r&&ri(r),shippingAddress:c&&ri(c,d),shippingOption:p&&Si(p,!0),cart:i&&di(i),order:s&&gi(s,y),orderMeta:y,payment:e.paymentData,paymentMethod:u&&this._transformPaymentMethod(u),quoteMeta:{request:(0,o.__assign)((0,o.__assign)({},g),{geoCountryCode:h&&h.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:(0,m.pick)(l&&l.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}},e.prototype.transformWithHostedFormData=function(e,t,n){var r=t.additionalAction,i=t.authToken,a=t.checkout,s=t.config,u=t.order,c=t.orderMeta,d=t.payment,p=void 0===d?{}:d,l=t.paymentMethod,h=t.paymentMethodMeta,f=a&&a.consignments[0],g=f&&f.shippingAddress,y=f&&f.selectedShippingOption;return{additionalAction:r,authToken:i,paymentMethod:l&&this._transformPaymentMethod(l),customer:u&&u.billingAddress&&a&&li(a.customer,u.billingAddress),billingAddress:u&&u.billingAddress&&ri(u.billingAddress),shippingAddress:g&&a&&ri(g,a.consignments),shippingOption:y&&Si(y,!0),cart:a&&di(a),order:u&&gi(u,c),orderMeta:c,payment:this._transformHostedInputValues(e,p,n),quoteMeta:{request:(0,o.__assign)((0,o.__assign)({},h),{geoCountryCode:s&&s.context.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:s&&(0,m.pick)(s.storeConfig.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}},e.prototype._transformPaymentMethod=function(e){return"multi-option"!==e.method||e.gateway?e.initializationData&&e.initializationData.gateway?(0,o.__assign)((0,o.__assign)({},e),{id:e.initializationData.gateway}):e.id===pi.BRAINTREE_VENMO?(0,o.__assign)((0,o.__assign)({},e),{id:pi.BRAINTREE_PAYPAL}):e:(0,o.__assign)((0,o.__assign)({},e),{gateway:e.id})},e.prototype._transformHostedInputValues=function(e,t,n){return"instrumentId"in t?(0,o.__assign)((0,o.__assign)({},t),{ccCvv:e.cardCodeVerification,ccNumber:e.cardNumberVerification&&this._cardNumberFormatter.unformat(e.cardNumberVerification),hostedFormNonce:n}):(0,o.__assign)((0,o.__assign)({},t),{ccCvv:e.cardCode,ccExpiry:this._cardExpiryFormatter.toObject(e.cardExpiry||""),ccName:e.cardName||"",ccNumber:this._cardNumberFormatter.unformat(e.cardNumber||""),hostedFormNonce:n})},e.prototype._mapShippingAddress=function(e,t){var n,r,i,o;if(t){var a=null===(r=null===(n=t.initializationData)||void 0===n?void 0:n.bopis)||void 0===r?void 0:r.enabled,s=null===(o=null===(i=t.initializationData)||void 0===i?void 0:i.bopis)||void 0===o?void 0:o.requiredAddress,u=e.consignments.getConsignments(),c=null==u?void 0:u.every((function(e){return e.selectedPickupOption}));if(a&&c&&"none"===s)return}return e.shippingAddress.getShippingAddress()},e}();var Ei;!function(e){e.AvailableShippingOptions="consignments.availableShippingOptions",e.PhysicalItemsCategoryNames="cart.lineItems.physicalItems.categoryNames",e.DigitalItemsCategoryNames="cart.lineItems.digitalItems.categoryNames"}(Ei||(Ei={}));const wi=function(){function e(e,t){this._consignmentRequestSender=e,this._checkoutRequestSender=t}return e.prototype.unassignItemsByAddress=function(e,t){var n=this;return function(r){var i=r.getState();if(!i.checkout.getCheckout())throw new Pn(bn.MissingCheckout);var o=n._consignmentHasAddress(e)?e.address:e.shippingAddress,a=i.consignments.getConsignmentByAddress(o);if(!a)throw new Sr("No consignment found for the specified address");var s=n._removeLineItems(e.lineItems,a,i.cart.getCart());return s.length?n.updateConsignment({id:a.id,address:o,lineItems:s},t)(r):n.deleteConsignment(a.id,t)(r)}},e.prototype.assignItemsByAddress=function(e,t){var n=this;return function(r){var i=r.getState(),o=n._consignmentHasAddress(e)?e.address:e.shippingAddress,a=i.consignments.getConsignmentByAddress(o);return n._createOrUpdateConsignment({id:a&&a.id,address:o,lineItems:n._addLineItems(e.lineItems,a,i.cart.getCart())},t)(r)}},e.prototype.selectShippingOption=function(e,t){var n=this;return function(r){return S.Observable.create((function(i){var o=r.getState(),s=o.checkout.getCheckout(),u=o.consignments.getConsignments();if(!s)throw new Pn(bn.MissingCheckout);if(!u||!u.length)throw new Pn(bn.MissingConsignments);var c={id:u[0].id,shippingOptionId:e},d={id:u[0].id};i.next((0,a.createAction)(x.UpdateShippingOptionRequested,void 0,d)),n._consignmentRequestSender.updateConsignment(s.id,c,t).then((function(e){var t=e.body;i.next((0,a.createAction)(x.UpdateShippingOptionSucceeded,t,d)),i.complete()})).catch((function(e){i.error((0,a.createErrorAction)(x.UpdateShippingOptionFailed,e,d))}))}))}},e.prototype.loadShippingOptions=function(e){var t=this;return function(n){return S.Observable.create((function(r){var i=n.getState().checkout.getCheckout();if(!i)throw new Pn(bn.MissingCheckout);r.next((0,a.createAction)(x.LoadShippingOptionsRequested)),t._checkoutRequestSender.loadCheckout(i.id,(0,o.__assign)((0,o.__assign)({},e),{params:{include:[Ei.AvailableShippingOptions]}})).then((function(e){var t=e.body;r.next((0,a.createAction)(x.LoadShippingOptionsSucceeded,t)),r.complete()})).catch((function(e){r.error((0,a.createErrorAction)(x.LoadShippingOptionsFailed,e))}))}))}},e.prototype.updateAddress=function(e,t){var n=this;return function(r){var i=n._getUpdateAddressRequestBody(e,r),o=r.getState().consignments.getConsignments();return o&&o.length&&(i.id=o[0].id),n._createOrUpdateConsignment(i,t)(r)}},e.prototype.createConsignments=function(e,t){var n=this;return function(r){return S.Observable.create((function(i){var o=r.getState().checkout.getCheckout();if(!o||!o.id)throw new Pn(bn.MissingCheckout);i.next((0,a.createAction)(x.CreateConsignmentsRequested)),n._consignmentRequestSender.createConsignments(o.id,e,t).then((function(e){var t=e.body;i.next((0,a.createAction)(x.CreateConsignmentsSucceeded,t)),i.complete()})).catch((function(e){i.error((0,a.createErrorAction)(x.CreateConsignmentsFailed,e))}))}))}},e.prototype.updateConsignment=function(e,t){var n=this;return function(r){return S.Observable.create((function(i){var o=r.getState().checkout.getCheckout();if(!o||!o.id)throw new Pn(bn.MissingCheckout);var s={id:e.id};i.next((0,a.createAction)(x.UpdateConsignmentRequested,void 0,s)),n._consignmentRequestSender.updateConsignment(o.id,e,t).then((function(e){var t=e.body;i.next((0,a.createAction)(x.UpdateConsignmentSucceeded,t,s)),i.complete()})).catch((function(e){i.error((0,a.createErrorAction)(x.UpdateConsignmentFailed,e,s))}))}))}},e.prototype.deleteConsignment=function(e,t){var n=this;return function(r){return S.Observable.create((function(i){var o=r.getState().checkout.getCheckout(),s={id:e};if(!o||!o.id)throw new Pn(bn.MissingCheckout);i.next((0,a.createAction)(x.DeleteConsignmentRequested,void 0,s)),n._consignmentRequestSender.deleteConsignment(o.id,e,t).then((function(e){var t=e.body;i.next((0,a.createAction)(x.DeleteConsignmentSucceeded,t,s)),i.complete()})).catch((function(e){i.error((0,a.createErrorAction)(x.DeleteConsignmentFailed,e,s))}))}))}},e.prototype.updateShippingOption=function(e,t){var n=this;return function(r){return S.Observable.create((function(i){var o=r.getState().checkout.getCheckout();if(!o||!o.id)throw new Pn(bn.MissingCheckout);var s={id:e.id};i.next((0,a.createAction)(x.UpdateShippingOptionRequested,void 0,s)),n._consignmentRequestSender.updateConsignment(o.id,e,t).then((function(e){var t=e.body;i.next((0,a.createAction)(x.UpdateShippingOptionSucceeded,t,s)),i.complete()})).catch((function(e){i.error((0,a.createErrorAction)(x.UpdateShippingOptionFailed,e,s))}))}))}},e.prototype._createOrUpdateConsignment=function(e,t){var n=this;return function(r){var i=r.getState().checkout.getCheckout();if(!i||!i.id)throw new Pn(bn.MissingCheckout);return n._isUpdateConsignmentRequest(e)?n.updateConsignment(e,t)(r):n.createConsignments([e],t)(r)}},e.prototype._getUpdateAddressRequestBody=function(e,t){var n=t.getState().cart.getCart();if(!n)throw new Pn(bn.MissingCart);var r=n.lineItems,i=r.physicalItems,a=r.customItems,s=void 0===a?[]:a;return{address:e,lineItems:(0,o.__spreadArrays)(i,s).map((function(e){return{itemId:e.id,quantity:e.quantity}}))}},e.prototype._removeLineItems=function(e,t,n){if(!n)throw new Pn(bn.MissingCart);return this._hydrateLineItems(t.lineItemIds,n).map((function(t){var n=(0,m.find)(e,(function(e){return e.itemId===t.itemId}));return(0,o.__assign)((0,o.__assign)({},t),{quantity:n?t.quantity-n.quantity:t.quantity})})).filter((function(e){return e.quantity>0}))},e.prototype._addLineItems=function(e,t,n){if(!t)return e;if(!n)throw new Pn(bn.MissingCart);return e.concat(this._hydrateLineItems(t.lineItemIds,n)).filter((function(e){return e.quantity>0}))},e.prototype._hydrateLineItems=function(e,t){return e.map((function(e){var n=(0,m.find)(t.lineItems.physicalItems,(function(t){return t.id===e}));return{itemId:e,quantity:n?n.quantity:0}}))},e.prototype._isUpdateConsignmentRequest=function(e){return!!e.id},e.prototype._consignmentHasAddress=function(e){return"object"==typeof e&&"address"in e},e}();var Ai=["consignments.availableShippingOptions","cart.lineItems.physicalItems.options","cart.lineItems.digitalItems.options","customer","promotions.banners"];const bi=function(){function e(e){this._requestSender=e}return e.prototype.createConsignments=function(e,t,n){var r=void 0===n?{}:n,i=r.timeout,a=r.params,s=(void 0===a?{}:a).include,u="/api/storefront/checkouts/"+e+"/consignments",c=(0,o.__assign)({Accept:Vn.JsonV1},jn);return this._requestSender.post(u,{body:t,params:{include:rr(Ai,s)},headers:c,timeout:i})},e.prototype.updateConsignment=function(e,t,n){var r=void 0===n?{}:n,i=r.timeout,a=r.params,s=(void 0===a?{}:a).include,u=t.id,c=(0,o.__rest)(t,["id"]),d="/api/storefront/checkouts/"+e+"/consignments/"+u,p=(0,o.__assign)({Accept:Vn.JsonV1},jn);return this._requestSender.put(d,{body:c,params:{include:rr(Ai,s)},headers:p,timeout:i})},e.prototype.deleteConsignment=function(e,t,n){var r=(void 0===n?{}:n).timeout,i="/api/storefront/checkouts/"+e+"/consignments/"+t,a=(0,o.__assign)({Accept:Vn.JsonV1},jn),s=nr(Ai);return this._requestSender.delete(i,{params:{include:s},headers:a,timeout:r})},e}(),Pi=function(){function e(e,t){this._googleRecaptcha=e,this._requestSender=t}return e.prototype.initialize=function(e){var t=this;return function(n){return(0,S.concat)((0,S.of)((0,a.createAction)(mn.InitializeRequested,void 0)),(0,S.defer)((function(){return(0,o.__awaiter)(t,void 0,void 0,(function(){var t,r,i,s,u;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:return t=e?e.containerId:"spamProtectionContainer",e||document.getElementById(t)||((r=document.createElement("div")).setAttribute("id",t),document.body.appendChild(r)),i=n.getState(),s=i.config.getStoreConfigOrThrow(),u=s.checkoutSettings.googleRecaptchaSitekey,[4,this._googleRecaptcha.load(t,u)];case 1:return o.sent(),[2,(0,a.createAction)(mn.InitializeSucceeded)]}}))}))}))).pipe((0,I.catchError)((function(e){return Qn(mn.InitializeFailed,e)})))}},e.prototype.verifyCheckoutSpamProtection=function(){var e=this;return function(t){return(0,S.defer)((function(){var n=t.getState().checkout.getCheckout();if(!n)throw new Pn(bn.MissingCheckout);return(0,S.concat)((0,S.of)((0,a.createAction)(mn.VerifyCheckoutRequested)),(0,S.from)(e.execute()(t)).pipe((0,I.switchMap)((function(t){return lr(t)&&t.payload?(0,S.from)(e._requestSender.validate(n.id,t.payload.token)).pipe((0,I.switchMap)((function(e){var n=e.body;return(0,S.concat)((0,S.of)(t),(0,S.of)((0,a.createAction)(mn.VerifyCheckoutSucceeded,n)))}))):(0,S.of)(t)})))).pipe((0,I.catchError)((function(e){return Qn(mn.VerifyCheckoutFailed,e)})))}))}},e.prototype.execute=function(){var e=this;return function(t){return(0,S.concat)((0,S.of)((0,a.createAction)(mn.ExecuteRequested)),e.initialize()(t),e._googleRecaptcha.execute().pipe((0,I.take)(1)).pipe((0,I.switchMap)((function(t){var n=t.error,r=t.token;return(0,o.__awaiter)(e,void 0,void 0,(function(){return(0,o.__generator)(this,(function(e){if(n instanceof Or)throw n;if(n||!r)throw new Nr;return[2,(0,a.createAction)(mn.ExecuteSucceeded,{token:r})]}))}))})))).pipe((0,I.catchError)((function(e){return Qn(mn.ExecuteFailed,e)})))}},e}(),Oi=function(){function e(e){this._requestSender=e}return e.prototype.validate=function(e,t,n){var r=(void 0===n?{}:n).timeout,i="/api/storefront/checkouts/"+e+"/spam-protection",a=(0,o.__assign)({Accept:Vn.JsonV1},jn);return this._requestSender.post(i,{body:{token:t},headers:a,timeout:r})},e}(),Ti=function(){function e(e){this._storeCreditRequestSender=e}return e.prototype.applyStoreCredit=function(e,t){var n=this;return function(r){return(0,S.concat)((0,S.of)((0,a.createAction)(on.ApplyStoreCreditRequested)),(0,S.defer)((function(){return(0,o.__awaiter)(n,void 0,void 0,(function(){var n,i,s;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(n=r.getState(),!(i=n.checkout.getCheckout()))throw new Pn(bn.MissingCheckout);return[4,e?this._storeCreditRequestSender.applyStoreCredit(i.id,t):this._storeCreditRequestSender.removeStoreCredit(i.id,t)];case 1:return s=o.sent().body,[2,(0,a.createAction)(on.ApplyStoreCreditSucceeded,s)]}}))}))}))).pipe((0,I.catchError)((function(e){return Qn(on.ApplyStoreCreditFailed,e)})))}},e}(),Ri=function(){function e(e){this._requestSender=e}return e.prototype.applyStoreCredit=function(e,t){var n=(void 0===t?{}:t).timeout,r="/api/storefront/checkouts/"+e+"/store-credit",i=(0,o.__assign)({Accept:Vn.JsonV1},jn);return this._requestSender.post(r,{headers:i,timeout:n,params:{include:nr(ir)}})},e.prototype.removeStoreCredit=function(e,t){var n=(void 0===t?{}:t).timeout,r="/api/storefront/checkouts/"+e+"/store-credit",i=(0,o.__assign)({Accept:Vn.JsonV1},jn);return this._requestSender.delete(r,{headers:i,timeout:n,params:{include:nr(ir)}})},e}(),Mi=function(e){function t(t){var n=e.call(this,t)||this;return n.name="UpdateSubscriptionsError",n.type="update_subscriptions",n}return(0,o.__extends)(t,e),t}(h),Di=function(){function e(e){this._subscriptionsRequestSender=e}return e.prototype.updateSubscriptions=function(e,t){var n=this;return(0,S.concat)((0,S.of)((0,a.createAction)(A.UpdateSubscriptionsRequested)),(0,S.defer)((function(){return(0,o.__awaiter)(n,void 0,void 0,(function(){var n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._subscriptionsRequestSender.updateSubscriptions(e,t)];case 1:return n=r.sent().body,[2,(0,a.createAction)(A.UpdateSubscriptionsSucceeded,n)]}}))}))}))).pipe((0,I.catchError)((function(e){return Qn(A.UpdateSubscriptionsFailed,new Mi(e))})))},e}(),ki=function(){function e(e){this._requestSender=e}return e.prototype.updateSubscriptions=function(e,t){var n=(void 0===t?{}:t).timeout,r=(0,o.__assign)({Accept:Vn.JsonV1},jn);return this._requestSender.post("/api/storefront/subscriptions",{body:e,headers:r,timeout:n})},e}();var Ni=(0,m.memoize)((function(e){return Array.isArray(e)?e.map((function(e){return Li(e)})):U(e)?Object.keys(e).reduce((function(t,n){var r;return(0,o.__assign)((0,o.__assign)({},t),((r={})[n]=Li(e[n]),r))}),{}):e}));Ni.cache=new WeakMap;var Li=function(e){return"object"==typeof e&&null!==e?Ni(e):e};function zi(e){return function(){for(var t=[],n=0;n55?55:e<25?25:e}function Qo(e){var t=e.billingAddress,n=e.email,r=e.firstName,i=e.lastName,o=e.phone,a=e.shippingAddress,s=t||a;return{email:n,first_name:r,last_name:i,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 Zo(e){var t=e.email,n=e.phone,r=e.shippingAddress,i=((null==r?void 0:r.recipientName)||"").split(" ");return{email:t,first_name:i[0]||"",last_name:i[1]||"",phone_number:n,address_line_1:null==r?void 0:r.line1,address_line_2:null==r?void 0:r.line2,city:null==r?void 0:r.city,state:null==r?void 0:r.state,country_code:null==r?void 0:r.countryCode,postal_code:null==r?void 0:r.postalCode}}const Jo=function(){function e(e,t,n,r,i,o){this._store=e,this._checkoutActionCreator=t,this._cartRequestSender=n,this._braintreeSDKCreator=r,this._formPoster=i,this._window=o}return e.prototype.initialize=function(e){var t,n;return(0,o.__awaiter)(this,void 0,void 0,(function(){var r,i,a,s,u,c,d,p,l,h,f,m,g=this;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(r=e.braintreepaypal,i=e.containerId,a=e.methodId,u=(s=r||{}).messagingContainerId,c=s.onError,!a)throw new Sr('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new Sr('Unable to initialize payment because "options.containerId" argument is not provided.');if(!r)throw new Sr('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');if(!r.buyNowInitializeOptions)return[3,1];if(d=this._store.getState(),p=d.paymentMethods.getPaymentMethodOrThrow(a),!r.currencyCode)throw new Sr('Unable to initialize payment because "options.braintreepaypal.currencyCode" argument is not provided.');return l=r.currencyCode,[3,3];case 1:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 2:d=o.sent(),p=d.paymentMethods.getPaymentMethodOrThrow(a),l=d.cart.getCartOrThrow().currency.code,o.label=3;case 3:if(!p.clientToken)throw new Pn(bn.MissingPaymentMethod);return h={currency:l,intent:null===(t=p.initializationData)||void 0===t?void 0:t.intent,isCreditEnabled:null===(n=p.initializationData)||void 0===n?void 0:n.isCreditEnabled},f=function(e){g._renderPayPalComponents(e,r,i,a,Boolean(p.config.testMode))},m=function(e){return g._handleError(e,i,u,c)},this._braintreeSDKCreator.initialize(p.clientToken),[4,this._braintreeSDKCreator.getPaypalCheckout(h,f,m)];case 4:return o.sent(),[2]}}))}))},e.prototype.deinitialize=function(){return this._braintreeSDKCreator.teardown(),Promise.resolve()},e.prototype._renderPayPalComponents=function(e,t,n,r,i){var o=t.messagingContainerId;this._renderPayPalMessages(o),this._renderPayPalButton(e,t,n,r,i)},e.prototype._renderPayPalButton=function(e,t,n,r,i){var o=this,a=t.style,s=t.shouldProcessPayment,u=t.onAuthorizeError,c=this._window.paypal,d=null==c?void 0:c.FUNDING.PAYPAL;if(c&&d){var p=a?Wo(a):{},l=c.Buttons({env:i?"sandbox":"production",commit:!1,fundingSource:d,style:p,createOrder:function(){return o._setupPayment(e,t,r)},onApprove:function(t){return o._tokenizePayment(t,e,r,s,u)}});l.isEligible()&&l.render("#"+n)}else this._removeElement(n)},e.prototype._renderPayPalMessages=function(e){var t=e&&Boolean(document.getElementById(e)),n=this._window.paypal;if(n&&t){var r=this._store.getState().cart.getCartOrThrow();n.Messages({amount:r.cartAmount,placement:"cart"}).render("#"+e)}else this._removeElement(e)},e.prototype._setupPayment=function(e,t,n){var r,i;return(0,o.__awaiter)(this,void 0,void 0,(function(){var a,s,u,c,d,p,l,h,f,m,g,y;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:a=t.buyNowInitializeOptions,s=t.shippingAddress,u=t.onPaymentError,o.label=1;case 1:return o.trys.push([1,7,,8]),d=this,[4,this._createBuyNowCart({buyNowInitializeOptions:a})];case 2:return d._buyNowCart=o.sent(),this._buyNowCart?(c=this._store.getState(),[3,5]):[3,3];case 3:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 4:c=o.sent(),o.label=5;case 5:return p=c.customer.getCustomer(),l=c.paymentMethods.getPaymentMethodOrThrow(n),h=this._buyNowCart?this._buyNowCart.cartAmount:c.checkout.getCheckoutOrThrow().outstandingBalance,f=null!==(r=t.currencyCode)&&void 0!==r?r:c.config.getStoreConfigOrThrow().currency.code,m=s||(null==p?void 0:p.addresses[0]),g=m?jo(m):void 0,[4,e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:g,amount:h,currency:f,offerCredit:!1,intent:null===(i=l.initializationData)||void 0===i?void 0:i.intent})];case 6:return[2,o.sent()];case 7:throw y=o.sent(),u&&u(y),y;case 8:return[2]}}))}))},e.prototype._createBuyNowCart=function(e){var t=e.buyNowInitializeOptions;return(0,o.__awaiter)(this,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if("function"!=typeof(null==t?void 0:t.getBuyNowCartRequestBody))return[3,4];if(!(e=t.getBuyNowCartRequestBody()))throw new Pn(bn.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._cartRequestSender.createBuyNowCart(e)];case 2:return[2,n.sent().body];case 3:throw n.sent(),new Go;case 4:return[2]}}))}))},e.prototype._tokenizePayment=function(e,t,n,r,i){var a;return(0,o.__awaiter)(this,void 0,void 0,(function(){var s,u,c,d,p,l;return(0,o.__generator)(this,(function(h){switch(h.label){case 0:return h.trys.push([0,3,,4]),[4,this._braintreeSDKCreator.getDataCollector({paypal:!0})];case 1:return s=h.sent().deviceData,[4,t.tokenizePayment(e)];case 2:return u=h.sent(),c=u.details,d=u.nonce,p=null===(a=this._buyNowCart)||void 0===a?void 0:a.id,this._formPoster.postForm("/checkout.php",(0,o.__assign)({payment_type:"paypal",provider:n,action:r?"process_payment":"set_external_checkout",nonce:d,device_data:s,billing_address:JSON.stringify(Qo(c)),shipping_address:JSON.stringify(Zo(c))},p&&{cart_id:p})),[2,u];case 3:throw l=h.sent(),i&&i(l),l;case 4:return[2]}}))}))},e.prototype._handleError=function(e,t,n,r){this._removeElement(t),this._removeElement(n),r&&r(e)},e.prototype._removeElement=function(e){var t=e&&document.getElementById(e);t&&t.remove()},e}();var Xo,$o,ea,ta,na;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(Xo||(Xo={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}($o||($o={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black"}(ea||(ea={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(ta||(ta={})),function(e){e.PILL="pill",e.RECT="rect"}(na||(na={}));const ra=function(){function e(e,t,n,r,i,o){this._store=e,this._checkoutActionCreator=t,this._cartRequestSender=n,this._braintreeSDKCreator=r,this._formPoster=i,this._window=o}return e.prototype.initialize=function(e){var t,n;return(0,o.__awaiter)(this,void 0,void 0,(function(){var r,i,a,s,u,c,d,p,l,h=this;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(r=e.braintreepaypalcredit,i=e.containerId,!(a=e.methodId))throw new Sr('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new Sr('Unable to initialize payment because "options.containerId" argument is not provided.');if(!r)throw new Sr('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');if(!r.buyNowInitializeOptions)return[3,1];if(s=this._store.getState(),u=s.paymentMethods.getPaymentMethodOrThrow(a),!r.currencyCode)throw new Sr('Unable to initialize payment because "options.braintreepaypalcredit.currencyCode" argument is not provided.');return c=r.currencyCode,[3,3];case 1:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 2:s=o.sent(),u=s.paymentMethods.getPaymentMethodOrThrow(a),c=s.cart.getCartOrThrow().currency.code,o.label=3;case 3:if(!u.clientToken)throw new Pn(bn.MissingPaymentMethod);return d={currency:c,intent:null===(t=u.initializationData)||void 0===t?void 0:t.intent,isCreditEnabled:null===(n=u.initializationData)||void 0===n?void 0:n.isCreditEnabled},p=function(e){return h._renderPayPalButton(e,r,i,a,Boolean(u.config.testMode))},l=function(e){return h._handleError(e,i,r.onError)},this._braintreeSDKCreator.initialize(u.clientToken),[4,this._braintreeSDKCreator.getPaypalCheckout(d,p,l)];case 4:return o.sent(),[2]}}))}))},e.prototype.deinitialize=function(){return this._braintreeSDKCreator.teardown(),Promise.resolve()},e.prototype._renderPayPalButton=function(e,t,n,r,i){var a=this,s=t.style,u=t.shouldProcessPayment,c=t.onAuthorizeError,d=this._window.paypal,p=!1;if(d){var l=[d.FUNDING.PAYLATER,d.FUNDING.CREDIT],h=s?Wo(s):{};l.forEach((function(s){var l=s===d.FUNDING.CREDIT?(0,o.__assign)({label:ta.CREDIT},h):h;if(!p){var f=d.Buttons({env:i?"sandbox":"production",commit:!1,fundingSource:s,style:l,createOrder:function(){return a._setupPayment(e,t,r)},onApprove:function(t){return a._tokenizePayment(t,e,r,u,c)}});f.isEligible()&&(f.render("#"+n),p=!0)}}))}d&&p||this._removeElement(n)},e.prototype._setupPayment=function(e,t,n){var r,i;return(0,o.__awaiter)(this,void 0,void 0,(function(){var a,s,u,c,d,p,l,h,f,m,g,y;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:a=t.onPaymentError,s=t.shippingAddress,u=t.buyNowInitializeOptions,o.label=1;case 1:return o.trys.push([1,7,,8]),d=this,[4,this._createBuyNowCart({buyNowInitializeOptions:u})];case 2:return d._buyNowCart=o.sent(),this._buyNowCart?(c=this._store.getState(),[3,5]):[3,3];case 3:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 4:c=o.sent(),o.label=5;case 5:return p=c.customer.getCustomer(),l=c.paymentMethods.getPaymentMethodOrThrow(n),h=this._buyNowCart?this._buyNowCart.cartAmount:c.checkout.getCheckoutOrThrow().outstandingBalance,f=null!==(r=t.currencyCode)&&void 0!==r?r:c.config.getStoreConfigOrThrow().currency.code,m=s||(null==p?void 0:p.addresses[0]),g=m?jo(m):void 0,[4,e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:g,amount:h,currency:f,offerCredit:!0,intent:null===(i=l.initializationData)||void 0===i?void 0:i.intent})];case 6:return[2,o.sent()];case 7:throw y=o.sent(),a&&a(y),y;case 8:return[2]}}))}))},e.prototype._createBuyNowCart=function(e){var t=e.buyNowInitializeOptions;return(0,o.__awaiter)(this,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if("function"!=typeof(null==t?void 0:t.getBuyNowCartRequestBody))return[3,4];if(!(e=t.getBuyNowCartRequestBody()))throw new Pn(bn.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._cartRequestSender.createBuyNowCart(e)];case 2:return[2,n.sent().body];case 3:throw n.sent(),new Go;case 4:return[2]}}))}))},e.prototype._tokenizePayment=function(e,t,n,r,i){var a;return(0,o.__awaiter)(this,void 0,void 0,(function(){var s,u,c,d,p,l;return(0,o.__generator)(this,(function(h){switch(h.label){case 0:return h.trys.push([0,3,,4]),[4,this._braintreeSDKCreator.getDataCollector({paypal:!0})];case 1:return s=h.sent().deviceData,[4,t.tokenizePayment(e)];case 2:return u=h.sent(),c=u.details,d=u.nonce,p=null===(a=this._buyNowCart)||void 0===a?void 0:a.id,this._formPoster.postForm("/checkout.php",(0,o.__assign)({payment_type:"paypal",provider:n,action:r?"process_payment":"set_external_checkout",nonce:d,device_data:s,billing_address:JSON.stringify(Qo(c)),shipping_address:JSON.stringify(Zo(c))},p&&{cart_id:p})),[2,u];case 3:throw l=h.sent(),i&&i(l),l;case 4:return[2]}}))}))},e.prototype._handleError=function(e,t,n){this._removeElement(t),n&&n(e)},e.prototype._removeElement=function(e){var t=e&&document.getElementById(e);t&&t.remove()},e}();var ia={backgroundColor:"#3D95CE",backgroundPosition:"50% 50%",backgroundSize:"80px auto",backgroundImage:'url("/app/assets/img/payment-providers/venmo-logo-white.svg")',backgroundRepeat:"no-repeat",borderRadius:"4px",cursor:"pointer",transition:"0.2s ease",minHeight:"40px",minWidth:"150px",height:"100%",width:"100%"};const oa=function(){function e(e,t,n,r,i){this._store=e,this._paymentMethodActionCreator=t,this._cartRequestSender=n,this._braintreeSDKCreator=r,this._formPoster=i,this._onError=m.noop}return e.prototype.initialize=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,a,s=this;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(t=e.braintreevenmo,n=e.containerId,!(r=e.methodId))throw new Sr('Unable to initialize payment because "options.methodId" argument is not provided.');return[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(r))];case 1:if(i=o.sent(),!(a=i.paymentMethods.getPaymentMethodOrThrow(r)).clientToken)throw new Pn(bn.MissingPaymentMethod);if(!n)throw new Sr('Unable to initialize payment because "options.containerId" argument is not provided.');return this._onError=(null==t?void 0:t.onError)||this._handleError,this._braintreeSDKCreator.initialize(a.clientToken),[4,this._braintreeSDKCreator.getVenmoCheckout((function(e){return s._handleInitializationVenmoSuccess(e,n,null==t?void 0:t.buyNowInitializeOptions)}),(function(e){return s._handleInitializationVenmoError(e,n)}))];case 2:return o.sent(),[2]}}))}))},e.prototype.deinitialize=function(){return this._braintreeSDKCreator.teardown(),Promise.resolve()},e.prototype._handleError=function(e){throw new Error(e.message)},e.prototype._handleInitializationVenmoSuccess=function(e,t,n){return this._renderVenmoButton(e,t,n)},e.prototype._handleInitializationVenmoError=function(e,t){return this._removeVenmoContainer(t),this._onError(e)},e.prototype._removeVenmoContainer=function(e){var t=document.getElementById(e);t&&t.remove()},e.prototype._renderVenmoButton=function(e,t,n){var r=this,i=document.getElementById(t);if(!i)throw new Sr("Unable to create wallet button without valid container ID.");i.setAttribute("aria-label","Venmo"),Object.assign(i.style,ia),i.addEventListener("click",(function(){return(0,o.__awaiter)(r,void 0,void 0,(function(){var t,r=this;return(0,o.__generator)(this,(function(a){switch(a.label){case 0:return i.setAttribute("disabled","true"),[4,this._createBuyNowCart(n)];case 1:return t=a.sent(),e.tokenize&&e.tokenize((function(e,n){return(0,o.__awaiter)(r,void 0,void 0,(function(){return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return i.removeAttribute("disabled"),e?[2,this._onError(e)]:[4,this._handlePostForm(n,null==t?void 0:t.id)];case 1:return r.sent(),[2]}}))}))})),[2]}}))}))})),i.addEventListener("mouseenter",(function(){i.style.backgroundColor="#0a7fc2"})),i.addEventListener("mouseleave",(function(){i.style.backgroundColor=ia.backgroundColor}))},e.prototype._createBuyNowCart=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if("function"!=typeof(null==e?void 0:e.getBuyNowCartRequestBody))return[3,4];if(!(t=e.getBuyNowCartRequestBody()))throw new Pn(bn.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._cartRequestSender.createBuyNowCart(t)];case 2:return[2,n.sent().body];case 3:throw n.sent(),new Go;case 4:return[2]}}))}))},e.prototype._handlePostForm=function(e,t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r,i;return(0,o.__generator)(this,(function(a){switch(a.label){case 0:return[4,this._braintreeSDKCreator.getDataCollector()];case 1:return n=a.sent().deviceData,r=e.nonce,i=e.details,this._formPoster.postForm("/checkout.php",(0,o.__assign)({nonce:r,provider:pi.BRAINTREE_VENMO,payment_type:"paypal",device_data:n,action:"set_external_checkout",billing_address:JSON.stringify(Qo(i)),shipping_address:JSON.stringify(Zo(i))},t&&{cart_id:t})),[2]}}))}))},e}();const aa=function(e){function t(t){var n=e.call(this,t||"Invalid arguments have been provided.")||this;return n.name="InvalidArgumentError",n.type="invalid_argument",n}return(0,o.__extends)(t,e),t}(s);var sa;!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"}(sa||(sa={}));const ua=function(e){function t(t){var n=e.call(this,function(e){switch(e){case sa.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case sa.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case sa.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case sa.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."}}(t))||this;return n.subtype=t,n.name="NotInitializedError",n.type="not_initialized",n}return(0,o.__extends)(t,e),t}(s);var ca;!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"}(ca||(ca={}));const da=function(e){function t(t){var n=e.call(this,function(e){switch(e){case ca.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case ca.MissingCart:return"Unable to proceed because cart data is unavailable.";case ca.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case ca.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case ca.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case ca.MissingCheckoutConfig:case ca.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case ca.MissingOrder:return"Unable to proceed because order data is unavailable.";case ca.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case ca.MissingPayment:return"Unable to proceed because payment data is unavailable.";case ca.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case ca.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case ca.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(t))||this;return n.subtype=t,n.name="MissingDataError",n.type="missing_data",n}return(0,o.__extends)(t,e),t}(s),pa=function(){function e(e,t,n,r,i){this._store=e,this._formPoster=t,this._checkoutActionCreator=n,this._googlePayPaymentProcessor=r,this._cartRequestSender=i}return e.prototype.initialize=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,a,s,u,c,d;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(t=e.containerId,n=e.methodId,r=e.currencyCode,i=this._getGooglePayOptions(e),a=i.buyNowInitializeOptions,!t||!n)throw new aa('Unable to proceed because "containerId" argument is not provided.');if(s=this._store.getState(),u=s.paymentMethods.getPaymentMethod(n),c=((null==u?void 0:u.config)||{}).testMode,this._methodId=n,this._isBuyNowFlow=!!a,!this._isBuyNowFlow)return[3,2];if(!r)throw new aa('Unable to initialize payment because "options.currencyCode" argument is not provided.');return d=i.buyNowInitializeOptions,this._googlePayPaymentProcessor.updateBuyNowFlowFlag(this._isBuyNowFlow),[4,this._googlePayPaymentProcessor.initialize(this._getMethodId(),this._getGooglePayClientOptions(r,c,d))];case 1:return o.sent(),[3,5];case 2:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 3:return o.sent(),[4,this._googlePayPaymentProcessor.initialize(this._getMethodId())];case 4:o.sent(),o.label=5;case 5:return this._walletButton=this._createSignInButton(t,i,r),[2]}}))}))},e.prototype.deinitialize=function(){return this._walletButton&&this._walletButton.parentNode&&(this._walletButton.parentNode.removeChild(this._walletButton),this._walletButton=void 0),this._googlePayPaymentProcessor.deinitialize()},e.prototype._getGooglePayClientOptions=function(e,t,n){var r=this;return{environment:t?"TEST":"PRODUCTION",paymentDataCallbacks:{onPaymentDataChanged:function(t){var i=t.callbackTrigger;return(0,o.__awaiter)(r,void 0,void 0,(function(){var t,r,a,s,u;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(i!==go.INITIALIZE)return[2];o.label=1;case 1:return o.trys.push([1,5,,6]),t=this,[4,this._createBuyNowCart(n)];case 2:return t._buyNowCart=o.sent(),this._buyNowCart?(r=this._buyNowCart,a=r.id,s=r.cartAmount,[4,this._store.dispatch(this._checkoutActionCreator.loadCheckout(a))]):[3,4];case 3:return o.sent(),[2,{newTransactionInfo:{currencyCode:e,totalPrice:String(s),totalPriceStatus:yo.FINAL}}];case 4:return[3,6];case 5:throw u=o.sent(),new Go(u);case 6:return[2]}}))}))}}}},e.prototype._createSignInButton=function(e,t,n){var r=this,i=document.getElementById(e),o=t.buttonType,a=t.buttonColor;if(!i)throw new aa("Unable to create sign-in button without valid container ID.");var s=this._googlePayPaymentProcessor.createButton((function(e){return r._handleWalletButtonClick(e,n)}),o,a);return i.appendChild(s),s},e.prototype._getMethodId=function(){if(!this._methodId)throw new ua(sa.PaymentNotInitialized);return this._methodId},e.prototype._getGooglePayOptions=function(e){if(e.methodId===pi.GOOGLEPAY_ADYENV2&&e.googlepayadyenv2)return e.googlepayadyenv2;if(e.methodId===pi.GOOGLEPAY_ADYENV3&&e.googlepayadyenv3)return e.googlepayadyenv3;if(e.methodId===pi.GOOGLEPAY_AUTHORIZENET&&e.googlepayauthorizenet)return e.googlepayauthorizenet;if(e.methodId===pi.GOOGLEPAY_BNZ&&e.googlepaybnz)return e.googlepaybnz;if(e.methodId===pi.GOOGLEPAY_BRAINTREE&&e.googlepaybraintree)return e.googlepaybraintree;if(e.methodId===pi.GOOGLEPAY_CHECKOUTCOM&&e.googlepaycheckoutcom)return e.googlepaycheckoutcom;if(e.methodId===pi.GOOGLEPAY_CYBERSOURCEV2&&e.googlepaycybersourcev2)return e.googlepaycybersourcev2;if(e.methodId===pi.GOOGLEPAY_ORBITAL&&e.googlepayorbital)return e.googlepayorbital;if(e.methodId===pi.GOOGLEPAY_STRIPE&&e.googlepaystripe)return e.googlepaystripe;if(e.methodId===pi.GOOGLEPAY_STRIPEUPE&&e.googlepaystripeupe)return e.googlepaystripeupe;if(e.methodId===pi.GOOGLEPAY_WORLDPAYACCESS&&e.googlepayworldpayaccess)return e.googlepayworldpayaccess;throw new aa},e.prototype._createBuyNowCart=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if("function"!=typeof(null==e?void 0:e.getBuyNowCartRequestBody))return[3,4];if(!(t=e.getBuyNowCartRequestBody()))throw new da(ca.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._cartRequestSender.createBuyNowCart(t)];case 2:return[2,n.sent().body];case 3:throw n.sent(),new Go;case 4:return[2]}}))}))},e.prototype._handleWalletButtonClick=function(e,t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:e.preventDefault(),i.label=1;case 1:return i.trys.push([1,7,,8]),this._isBuyNowFlow&&t&&this._googlePayPaymentProcessor.updatePaymentDataRequest({transactionInfo:{currencyCode:t,totalPrice:"0",totalPriceStatus:yo.ESTIMATED},callbackIntents:[_o.OFFER]}),[4,this._googlePayPaymentProcessor.displayWallet()];case 2:return n=i.sent(),[4,this._googlePayPaymentProcessor.handleSuccess(n)];case 3:return i.sent(),Xi(this._store.getState().cart.getCartOrThrow())>0&&n.shippingAddress?[4,this._googlePayPaymentProcessor.updateShippingAddress(n.shippingAddress)]:[3,5];case 4:i.sent(),i.label=5;case 5:return[4,this._onPaymentSelectComplete()];case 6:return i.sent(),[3,8];case 7:if((r=i.sent())&&"CANCELED"!==r.message)throw r;return[3,8];case 8:return[2]}}))}))},e.prototype._onPaymentSelectComplete=function(){var e,t=null===(e=this._buyNowCart)||void 0===e?void 0:e.id;this._formPoster.postForm("/checkout.php",(0,o.__assign)({headers:(0,o.__assign)({Accept:"text/html","Content-Type":"application/x-www-form-urlencoded"},jn)},t&&{action:"set_external_checkout",provider:this._methodId,cart_id:t}))},(0,o.__decorate)([Ar],e.prototype,"_handleWalletButtonClick",null),e}();var la={es:["es_es","es_mx","es_pe","es_co","es_ar","es_cl"],en:["en_us","en_gb","en_ca","en_es","en_fr","en_ie","en_sg","en_au","en_nz","en_my","en_hk","en_th","en_ae","en_sa","en_qa","en_kw","en_za"],pt:["pt_br"],zu:["zu_za"],ar:["ar_sa","ar_ae","ar_qa","ar_kw"],zh:["zh_sg","zh_hk"],ms:["ms_my"],uk:["uk_ua"],sv:["sv_se"],hr:["hr_hr"],pl:["pl_pl"],nl:["nl_be"],it:["it_it"],de:["de_de"],fr:["fr_fr","fr_ca"]};function ha(e){var t=e.replace("-","_").toLowerCase().split("_"),n=t[0],r=n+"_"+t[1],i=la[n];return i?i.indexOf(r)>-1?r:i[0]:"en_us"}const fa=function(){function e(e,t,n,r){this._store=e,this._checkoutActionCreator=t,this._masterpassScriptLoader=n,this._locale=r}return e.prototype.initialize=function(e){var t=this,n=e.containerId,r=e.methodId;if(!n||!r)throw new Sr('Unable to proceed because "containerId" argument is not provided.');return this._methodId=r,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()).then((function(e){var n=e.paymentMethods.getPaymentMethod(r);if(!n||!n.initializationData.checkoutId)throw new Pn(bn.MissingPaymentMethod);var i={useMasterpassSrc:n.initializationData.isMasterpassSrcEnabled,language:ha(t._locale),testMode:n.config.testMode,checkoutId:n.initializationData.checkoutId};return t._masterpassScriptLoader.load(i)})).then((function(e){t._masterpassClient=e,t._signInButton=t._createSignInButton(n)}))},e.prototype.deinitialize=function(){return this._signInButton&&this._signInButton.parentNode&&(this._signInButton.removeEventListener("click",this._handleWalletButtonClick),this._signInButton.parentNode.removeChild(this._signInButton),this._signInButton=void 0),Promise.resolve()},e.prototype._createSignInButton=function(e){var t=document.getElementById(e),n=this._store.getState(),r=this._methodId?n.paymentMethods.getPaymentMethod(this._methodId):null,i=n.config.getStoreConfig();if(!t)throw new Error("Need a container to place the button");if(!r)throw new Pn(bn.MissingPaymentMethod);if(!i)throw new Sr("Unable to retrieve store configuration");var o=document.createElement("input");if(o.type="image",r.initializationData.isMasterpassSrcEnabled){var a=r.config.testMode?"sandbox.":"",s=r.initializationData.checkoutId,u=["locale="+ha(this._locale),"paymentmethod=master,visa,amex,discover","checkoutid="+s];o.src=["https://"+a+"src.mastercard.com/assets/img/btn/src_chk_btn_126x030px.svg",u.join("&")].join("?")}else o.src="https://static.masterpass.com/dyn/img/btn/global/mp_chk_btn_160x037px.svg";return t.appendChild(o),o.addEventListener("click",this._handleWalletButtonClick),o},e.prototype._createMasterpassPayload=function(){var e=this._store.getState(),t=e.checkout.getCheckout(),n=this._methodId?e.paymentMethods.getPaymentMethod(this._methodId):null;if(!t)throw new Pn(bn.MissingCheckout);if(!n)throw new Pn(bn.MissingPaymentMethod);return{checkoutId:n.initializationData.checkoutId,allowedCardTypes:n.initializationData.allowedCardTypes,amount:t.cart.cartAmount.toString(),currency:t.cart.currency.code,cartId:t.cart.id,callbackUrl:("cart",window.location.origin+"/checkout.php?action=set_external_checkout&provider=masterpass&gateway=stripe&origin=cart")}},e.prototype._handleWalletButtonClick=function(){if(!this._masterpassClient)throw new kr(Dr.CheckoutButtonNotInitialized);this._masterpassClient.checkout(this._createMasterpassPayload())},(0,o.__decorate)([Ar],e.prototype,"_handleWalletButtonClick",null),e}(),ma=function(){function e(e,t,n,r,i){void 0===i&&(i=""),this._store=e,this._checkoutActionCreator=t,this._paypalScriptLoader=n,this._formPoster=r,this._host=i}return e.prototype.initialize=function(e){var t=this,n=e.paypal,r=this._store.getState(),i=this._paymentMethod=r.paymentMethods.getPaymentMethod(e.methodId);if(!n)throw new Sr;if(!i)throw new Pn(bn.MissingPaymentMethod);return this._paypalScriptLoader.loadPaypal(i.config.merchantId).then((function(r){var a,s,u;if(!i||!i.config.merchantId)throw new Pn(bn.MissingPaymentMethod);var c=i.config.merchantId,d=i.config.testMode?"sandbox":"production",p=((a={})[d]=n.clientId,a),l=r.FUNDING.CREDIT||"credit",h=n.allowCredit?[l]:[],f=n.allowCredit?[]:[l];return r.Button.render({env:d,client:p,commit:n.shouldProcessPayment,funding:{allowed:h,disallowed:f},style:(0,o.__assign)((0,o.__assign)({shape:na.RECT},(0,m.pick)(n.style,"layout","color","label","shape","tagline","fundingicons")),{size:"paypalexpress"===i.id&&"small"===(null===(s=n.style)||void 0===s?void 0:s.size)?$o.RESPONSIVE:null===(u=n.style)||void 0===u?void 0:u.size}),payment:function(e,r){return t._setupPayment(c,r,n.onPaymentError)},onAuthorize:function(e,r){return t._tokenizePayment(e,r,n.shouldProcessPayment,n.onAuthorizeError)}},e.containerId)}))},e.prototype.deinitialize=function(){return this._paymentMethod=void 0,Promise.resolve()},e.prototype._setupPayment=function(e,t,n){var r=this;if(!t)throw new kr(Dr.CheckoutButtonNotInitialized);return this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()).then((function(n){var i=n.cart.getCart(),a=i?i.id:"";return t.request.post(r._host+"/api/storefront/payment/paypalexpress",{merchantId:e,cartId:a},{headers:(0,o.__assign)({"X-API-INTERNAL":Hn},jn)})})).then((function(e){return e.id})).catch((function(e){throw n&&n(e),e}))},e.prototype._tokenizePayment=function(e,t,n,r){var i=this;if(!this._paymentMethod)throw new kr(Dr.CheckoutButtonNotInitialized);if(!t)throw new kr(Dr.CheckoutButtonNotInitialized);if(!e.paymentID||!e.payerID)throw new Pn(bn.MissingPayment);var o=this._paymentMethod.id;return t.payment.get(e.paymentID).then((function(t){i._formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:o,action:n?"process_payment":"set_external_checkout",paymentId:e.paymentID,payerId:e.payerID,payerInfo:JSON.stringify(t.payer.payer_info)})}))},e}();function ga(){try{return process.env.NODE_ENV||0}catch(e){return"development"}}const ya=function(){function e(e){this._console=e}return e.prototype.log=function(){for(var e=[],t=0;t0}));a.length>1&&a[0].matches===a[1].matches&&"development"===ga()&&Ca.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.");var s=a[0];if(s&&s.token)return s.token;if(this._useFallback){var u=null===(n=o.find((function(e){return e.default})))||void 0===n?void 0:n.token;if(u)return u}throw new Error("Unable to resolve to a registered token with the provided token.")},e}();function Ia(e,t){return Object.assign(e,{resolveIds:t})}const Ea=function(e){function t(t){var n=e.call(this,t||"Payment process was cancelled.")||this;return n.name="PaymentMethodCancelledError",n.type="payment_cancelled",n}return(0,o.__extends)(t,e),t}(s);const wa=function(e){function t(t){var n=e.call(this,t||"An unexpected error has occurred during buy now cart creation process. Please try again later.")||this;return n.name="BuyNowCartCreationError",n.type="buy_now_cart_creation_error",n}return(0,o.__extends)(t,e),t}(s);function Aa(e){if(!function(e){return"ApplePaySession"in e}(e))throw new Error("Apple pay is not supported")}const ba=function(){function e(){}return e.prototype.create=function(e){return Aa(window),new ApplePaySession(1,e)},e}();var Pa;!function(e){e.Subtotal="Subtotal",e.Shipping="Shipping"}(Pa||(Pa={}));const Oa=function(){function e(e,t,n){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=n,this._onAuthorizeCallback=m.noop,this._subTotalLabel=Pa.Subtotal,this._shippingLabel=Pa.Shipping}return e.prototype.initialize=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,a,s,u,c;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(t=e.methodId,n=e.containerId,r=e.applepay,Aa(window),!t||!r)throw new da(ca.MissingPaymentMethod);return i=r.buttonClassName,a=r.onPaymentAuthorize,s=r.buyNowInitializeOptions,u=r.requiresShipping,this._requiresShipping=u,this._buyNowInitializeOptions=s,this._onAuthorizeCallback=a,s?[3,2]:[4,this._paymentIntegrationService.loadDefaultCheckout()];case 1:o.sent(),o.label=2;case 2:return[4,this._paymentIntegrationService.loadPaymentMethod(t)];case 3:return o.sent(),c=this._paymentIntegrationService.getState(),this._paymentMethod=c.getPaymentMethodOrThrow(t),[4,this._paymentIntegrationService.verifyCheckoutSpamProtection()];case 4:return o.sent(),this._applePayButton=this._createButton(n,i),this._applePayButton.addEventListener("click",this._handleWalletButtonClick.bind(this)),[2,Promise.resolve()]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype._createButton=function(e,t){void 0===t&&(t="apple-pay-checkout-button");var n=document.getElementById(e);if(!n)throw new aa("Unable to create wallet button without valid container ID.");document.body.classList.add("apple-pay-supported");var r=document.createElement("div");return r.setAttribute("class",t),r.setAttribute("role","button"),r.setAttribute("aria-label","Apple Pay button"),n.appendChild(r),r},e.prototype._handleWalletButtonClick=function(e){var t;return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r,i,a,s,u,c,d,p,l,h,f;return(0,o.__generator)(this,(function(o){if(e.preventDefault(),!this._paymentMethod||!this._paymentMethod.initializationData)throw new da(ca.MissingPaymentMethod);return this._buyNowInitializeOptions&&"function"==typeof this._buyNowInitializeOptions.getBuyNowCartRequestBody?(n=this._paymentMethod.initializationData,r=n.countryCode,i=n.currencyCode,a=n.merchantCapabilities,s=n.supportedNetworks,u=n.storeName,h=this._getRequestWithEmptyTotal(r,i,s,a),this._requiresShipping&&(null===(t=h.requiredShippingContactFields)||void 0===t||t.push("postalAddress")),f=this._sessionFactory.create(h),this._handleApplePayEvents(f,this._paymentMethod,u),f.begin()):(c=this._paymentIntegrationService.getState(),d=c.getCartOrThrow(),p=c.getStoreConfigOrThrow(),l=c.getCheckoutOrThrow(),h=this._getBaseRequest(d,l,p,this._paymentMethod),f=this._sessionFactory.create(h),this._handleApplePayEvents(f,this._paymentMethod,p.storeProfile.storeName),f.begin()),[2]}))}))},e.prototype._getRequestWithEmptyTotal=function(e,t,n,r){return{countryCode:e,currencyCode:t,supportedNetworks:n,merchantCapabilities:r,total:{label:"",amount:"0",type:"pending"},requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"]}},e.prototype._getBaseRequest=function(e,t,n,r){var i,o=n.storeProfile,a=o.storeCountryCode,s=o.storeName,u=e.currency,c=u.code,d=u.decimalPlaces,p=r.initializationData,l=p.merchantCapabilities,h=p.supportedNetworks,f=e.lineItems.physicalItems.length>0,m={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:a,currencyCode:c,merchantCapabilities:l,supportedNetworks:h,lineItems:[],total:f?{label:s,amount:""+t.grandTotal.toFixed(d),type:"pending"}:{label:s,amount:""+t.grandTotal.toFixed(d),type:"final"}};if(f)null===(i=m.requiredShippingContactFields)||void 0===i||i.push("postalAddress");else{var g=[{label:this._subTotalLabel,amount:""+t.subtotal.toFixed(d)}];t.taxes.forEach((function(e){return g.push({label:e.name,amount:""+e.amount.toFixed(d)})})),m.lineItems=g}return m},e.prototype._handleApplePayEvents=function(e,t,n){var r=this;e.onvalidatemerchant=function(n){return(0,o.__awaiter)(r,void 0,void 0,(function(){var r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this._onValidateMerchant(t,n)];case 1:return r=i.sent().body,e.completeMerchantValidation(r),[3,3];case 2:throw i.sent(),new Error("Merchant validation failed");case 3:return[2]}}))}))},this._buyNowInitializeOptions&&!this._requiresShipping&&(e.onpaymentmethodselected=function(){return(0,o.__awaiter)(r,void 0,void 0,(function(){return(0,o.__generator)(this,(function(t){switch(t.label){case 0:return[4,this._createBuyNowCart()];case 1:return t.sent(),this._handlePaymentMethodSelected(e),[2]}}))}))}),e.onshippingcontactselected=function(t){return(0,o.__awaiter)(r,void 0,void 0,(function(){return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return this._buyNowInitializeOptions&&this._requiresShipping?[4,this._createBuyNowCart()]:[3,2];case 1:r.sent(),r.label=2;case 2:return[4,this._handleShippingContactSelected(e,n,t)];case 3:return r.sent(),[2]}}))}))},e.onshippingmethodselected=function(t){return(0,o.__awaiter)(r,void 0,void 0,(function(){return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._handleShippingMethodSelected(e,n,t)];case 1:return r.sent(),[2]}}))}))},e.oncancel=function(){return(0,o.__awaiter)(r,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return n.trys.push([0,3,,4]),e="/remote-checkout/"+t.id+"/signout",[4,this._requestSender.get(e)];case 1:return n.sent(),[4,this._paymentIntegrationService.loadCheckout()];case 2:return[2,n.sent()];case 3:throw n.sent(),new Ea;case 4:return[2]}}))}))},e.onpaymentauthorized=function(n){return(0,o.__awaiter)(r,void 0,void 0,(function(){return(0,o.__generator)(this,(function(r){return[2,this._onPaymentAuthorized(n,e,t)]}))}))}},e.prototype._createBuyNowCart=function(){var e,t;return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:if(i.trys.push([0,3,,4]),!(n=null===(t=null===(e=this._buyNowInitializeOptions)||void 0===e?void 0:e.getBuyNowCartRequestBody)||void 0===t?void 0:t.call(e)))throw new da(ca.MissingCart);return[4,this._paymentIntegrationService.createBuyNowCart(n)];case 1:return r=i.sent(),[4,this._paymentIntegrationService.loadCheckout(r.id)];case 2:return i.sent(),[3,4];case 3:throw i.sent(),new wa;case 4:return[2]}}))}))},e.prototype._handlePaymentMethodSelected=function(e){var t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow(),r=t.getStoreConfigOrThrow(),i=t.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new da(ca.MissingPaymentMethod);var o=this._getBaseRequest(n,i,r,this._paymentMethod);delete o.total.type,e.completePaymentMethodSelection({newTotal:o.total,newLineItems:o.lineItems})},e.prototype._handleShippingContactSelected=function(e,t,n){var r;return(0,o.__awaiter)(this,void 0,void 0,(function(){var i,a,s,u,c,d,p,l,h,f,m,g;return(0,o.__generator)(this,(function(y){switch(y.label){case 0:i=this._transformContactToAddress(n.shippingContact),y.label=1;case 1:return y.trys.push([1,3,,4]),[4,this._paymentIntegrationService.updateShippingAddress(i)];case 2:return y.sent(),[3,4];case 3:throw y.sent(),e.abort(),new Error("Shipping address update failed");case 4:if(a=this._paymentIntegrationService.getState(),s=a.getCartOrThrow().currency.decimalPlaces,u=a.getCheckoutOrThrow(),c=null===(r=u.consignments[0].selectedShippingOption)||void 0===r?void 0:r.id,d=u.consignments[0].availableShippingOptions,p=null==d?void 0:d.find((function(e){return e.id===c})),l=null==d?void 0:d.filter((function(e){return e.id!==c})),h=p?[{label:p.description,amount:""+p.cost.toFixed(s),detail:p.additionalDescription,identifier:p.id}]:[],l&&(0,o.__spreadArrays)(l.filter((function(e){return e.isRecommended})),l.filter((function(e){return!e.isRecommended}))).forEach((function(e){return h.push({label:e.description,amount:""+e.cost.toFixed(s),detail:e.additionalDescription,identifier:e.id})})),!(d instanceof Array))throw new Error("Shipping options not available.");if(0===d.length)return e.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:t,amount:""+u.grandTotal.toFixed(s)},[]),[2];f=d.find((function(e){return e.isRecommended})),m=f?f.id:d[0].id,g=p?p.id:m,y.label=5;case 5:return y.trys.push([5,7,,8]),[4,this._updateShippingOption(g)];case 6:return y.sent(),[3,8];case 7:throw y.sent(),new Error("Shipping options update failed");case 8:return a=this._paymentIntegrationService.getState(),u=a.getCheckoutOrThrow(),e.completeShippingContactSelection({newShippingMethods:h,newTotal:{type:"final",label:t,amount:""+u.grandTotal.toFixed(s)},newLineItems:this._getUpdatedLineItems(u,s)}),[2]}}))}))},e.prototype._handleShippingMethodSelected=function(e,t,n){return(0,o.__awaiter)(this,void 0,void 0,(function(){var r,i,a,s;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:r=n.shippingMethod.identifier,o.label=1;case 1:return o.trys.push([1,3,,4]),[4,this._updateShippingOption(r)];case 2:return o.sent(),[3,4];case 3:throw o.sent(),e.abort(),new Error("Shipping option selection update failed.");case 4:return i=this._paymentIntegrationService.getState(),a=i.getCartOrThrow().currency.decimalPlaces,s=i.getCheckoutOrThrow(),e.completeShippingMethodSelection({newTotal:{type:"final",label:t,amount:""+s.grandTotal.toFixed(a)},newLineItems:this._getUpdatedLineItems(s,a)}),[2]}}))}))},e.prototype._getUpdatedLineItems=function(e,t){var n=[{label:this._subTotalLabel,amount:""+e.subtotal.toFixed(t)}];return e.taxes.forEach((function(e){return n.push({label:e.name,amount:""+e.amount.toFixed(t)})})),n.push({label:this._shippingLabel,amount:""+e.shippingCostTotal.toFixed(t)}),n},e.prototype._updateShippingOption=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(t){return[2,this._paymentIntegrationService.selectShippingOption(e)]}))}))},e.prototype._onValidateMerchant=function(e,t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n;return(0,o.__generator)(this,(function(r){return n=["validationUrl="+t.validationURL,"merchantIdentifier="+e.initializationData.merchantId,"displayName="+e.initializationData.storeName,"domainName="+window.location.hostname].join("&"),[2,this._requestSender.post((i=e.initializationData.paymentsUrl,i+"/api/public/v1/payments/applepay/validate_merchant"),{credentials:!1,headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","X-XSRF-TOKEN":null},body:n})];var i}))}))},e.prototype._onPaymentAuthorized=function(e,t,n){return(0,o.__awaiter)(this,void 0,void 0,(function(){var r,i,a,s,u,c,d,p,l,h,f,m;return(0,o.__generator)(this,(function(g){switch(g.label){case 0:r=e.payment,i=r.token,a=r.billingContact,s=r.shippingContact,u=this._paymentIntegrationService.getState(),c=u.getCartOrThrow(),d=c.lineItems.physicalItems.length>0,p={methodId:n.id,paymentData:{formattedPayload:{apple_pay_token:{payment_data:i.paymentData,payment_method:i.paymentMethod,transaction_id:i.transactionIdentifier}}}},l=this._transformContactToAddress(a),h=this._transformContactToAddress(s),f=null==s?void 0:s.emailAddress,m=(null==s?void 0:s.phoneNumber)||"",g.label=1;case 1:return g.trys.push([1,7,,8]),[4,this._paymentIntegrationService.updateBillingAddress((0,o.__assign)((0,o.__assign)({},l),{email:f,phone:m}))];case 2:return g.sent(),d?[4,this._paymentIntegrationService.updateShippingAddress(h)]:[3,4];case 3:g.sent(),g.label=4;case 4:return[4,this._paymentIntegrationService.submitOrder({useStoreCredit:!1})];case 5:return g.sent(),[4,this._paymentIntegrationService.submitPayment(p)];case 6:return g.sent(),t.completePayment(ApplePaySession.STATUS_SUCCESS),[2,this._onAuthorizeCallback()];case 7:throw g.sent(),t.completePayment(ApplePaySession.STATUS_FAILURE),new Error("Payment cannot complete");case 8:return[2]}}))}))},e.prototype._transformContactToAddress=function(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:[]}},e}(),Ta=Ia((function(e){var t=e.getState().getHost;return new Oa((0,r.createRequestSender)({host:t()}),e,new ba)}),[{id:"applepay"}]),Ra=require("query-string"),Ma=function(e){function t(t){var n=e.call(this,t||"Not implemented.")||this;return n.name="NotImplementedError",n.type="not_implemented",n}return(0,o.__extends)(t,e),t}(s);var Da,ka,Na;!function(e){e.SandboxMode="bolt_sandbox",e.StagingMode="bolt_staging",e.DevelopmentMode="bolt_development"}(Da||(Da={})),function(e){e.Small="small",e.Medium="medium",e.Large="large"}(ka||(ka={})),function(e){e.Pill="pill",e.Rect="rect"}(Na||(Na={}));const La=function(){function e(e,t,n){void 0===n&&(n=window),this.paymentIntegrationService=e,this.boltScriptLoader=t,this.boltHostWindow=n}return e.prototype.initialize=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,a,s,u,c,d,p,l,h,f;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(t=e.bolt,n=e.containerId,r=e.methodId,a=(i=t||{}).buyNowInitializeOptions,s=i.style,!r)throw new aa('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new aa('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new aa('Unable to initialize payment because "options.bolt" argument is not provided.');if(!Boolean(a))throw new Ma("Only buy now flow is implemented for Bolt button");if(!(null==a?void 0:a.storefrontApiToken)||"string"!=typeof a.storefrontApiToken)throw new aa('Unable to initialize payment because "options.storefrontApiToken" argument is not provided.');return u=this.paymentIntegrationService.getState(),c=u.getPaymentMethodOrThrow(r),d=c.initializationData,p=c.config,h=(l=d||{}).publishableKey,f=l.developerConfig,[4,this.boltScriptLoader.loadBoltClient(h,p.testMode,f,"BigCommerce",a.storefrontApiToken)];case 1:return o.sent(),this.renderButton(n,c,s),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.renderButton=function(e,t,n){var r;"function"==typeof(null===(r=this.boltHostWindow.BoltConnect)||void 0===r?void 0:r.setupProductPageCheckout)&&(this.addButtonContainer(e,t,n),this.boltHostWindow.BoltConnect.setupProductPageCheckout())},e.prototype.addButtonContainer=function(e,t,n){var r=document.getElementById(e);if(r){var i=document.createElement("div"),o=document.createElement("object");i.setAttribute("id","product-page-checkout-wrapper"),i.setAttribute("class","bolt-button-wrapper"),i.setAttribute("style","display:none"),i.setAttribute("data-tid","product-page-checkout-wrapper"),o.setAttribute("data",this.getBoltObjectData(t,n)),o.setAttribute("class","bolt-product-checkout-button"),i.append(o),r.innerHTML="",r.append(i)}},e.prototype.getBoltObjectData=function(e,t){var n=e.initializationData,r=e.config,i=n||{},o=i.publishableKey,a=i.developerConfig,s=this.boltScriptLoader.getDomainURL(!!r.testMode,a),u=this.getButtonHeight(null==t?void 0:t.size),c=this.getButtonBorderRadius(null==t?void 0:t.shape,u);return(0,Ra.stringifyUrl)({url:"https://"+s+"/v1/checkout_button",query:{publishable_key:o,variant:"ppc",height:u,border_radius:c}})},e.prototype.getButtonHeight=function(e){if(e)switch(e){case ka.Small:return 25;case ka.Large:return 45;case ka.Medium:default:return 40}},e.prototype.getButtonBorderRadius=function(e,t){if(e)switch(e){case Na.Pill:return t?Math.round(t/2):void 0;case Na.Rect:default:return 4}},e}();const za=function(e){function t(t){var n=e.call(this,t||"Unable to proceed because the client library of a payment method is not loaded or ready to be used.")||this;return n.name="PaymentMethodClientUnavailableError",n.type="payment_method_client_unavailable",n}return(0,o.__extends)(t,e),t}(s),Ua=function(){function e(e,t){void 0===t&&(t=window),this.scriptLoader=e,this.boltHostWindow=t}return e.prototype.loadBoltClient=function(e,t,n,r,i){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(this.boltHostWindow.BoltCheckout)return[2,this.boltHostWindow.BoltCheckout];if(!e)throw new aa('Unable to initialize payment because "publishableKey" argument is not provided.');return[4,this.scriptLoader.loadScript("//"+this.getDomainURL(!!t,n)+"/connect-bigcommerce.js",this.getScriptOptions("bolt-connect",e,r,i))];case 1:return o.sent(),[4,this.scriptLoader.loadScript("//"+this.getDomainURL(!!t,n)+"/track.js",this.getScriptOptions("bolt-track",e))];case 2:if(o.sent(),!this.boltHostWindow.BoltCheckout)throw new za;return[2,this.boltHostWindow.BoltCheckout]}}))}))},e.prototype.loadBoltEmbedded=function(e,t,n){return(0,o.__awaiter)(this,void 0,void 0,(function(){var r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:return r={async:!0,attributes:{id:"bolt-embedded"}},[4,this.scriptLoader.loadScript("//"+this.getDomainURL(!!t,n)+"/embed.js",r)];case 1:if(i.sent(),!this.boltHostWindow.Bolt)throw new za;return[2,this.boltHostWindow.Bolt(e)]}}))}))},e.prototype.getDomainURL=function(e,t){if(!e)return"connect.bolt.com";if(t)switch(t.developerMode){case Da.StagingMode:return"connect-staging.bolt.com";case Da.DevelopmentMode:return"connect."+t.developerDomain}return"connect-sandbox.bolt.com"},e.prototype.getScriptOptions=function(e,t,n,r){return{async:!0,attributes:(0,o.__assign)((0,o.__assign)({id:e,"data-publishable-key":t},n&&{"data-shopping-cart-id":n}),r&&{"data-storefront-api-token":r})}},e}(),Fa=Ia((function(e){return new La(e,new Ua((0,Kn.getScriptLoader)()))}),[{id:"bolt"}]);var qa,Ba,Ga,xa,Ya,Va,Ha;!function(e){e.BuyNow="BUY_NOW"}(qa||(qa={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(Ba||(Ba={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(Ga||(Ga={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(xa||(xa={})),function(e){e.pill="pill",e.rect="rect"}(Ya||(Ya={})),function(e){e.OXXO="oxxo"}(Va||(Va={})),function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED"}(Ha||(Ha={}));const ja=function(){function e(e,t,n,r){this.formPoster=e,this.paymentIntegrationService=t,this.paypalCommerceRequestSender=n,this.paypalCommerceScriptLoader=r}return e.prototype.loadPayPalSdk=function(e,t,n){return(0,o.__awaiter)(this,void 0,void 0,(function(){var r,i,a,s;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:return r=this.paymentIntegrationService.getState(),i=t||r.getCartOrThrow().currency.code,a=r.getPaymentMethodOrThrow(e),s=this,[4,this.paypalCommerceScriptLoader.getPayPalSDK(a,i,n)];case 1:return s.paypalSdk=o.sent(),[2,this.paypalSdk]}}))}))},e.prototype.getPayPalSdkOrThrow=function(){if(!this.paypalSdk)throw new za;return this.paypalSdk},e.prototype.createBuyNowCartOrThrow=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if(!(t=e.getBuyNowCartRequestBody()))throw new da(ca.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.paymentIntegrationService.createBuyNowCart(t)];case 2:return[2,n.sent()];case 3:throw n.sent(),new wa;case 4:return[2]}}))}))},e.prototype.createOrder=function(e,t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return n=this.paymentIntegrationService.getState().getCartOrThrow().id,[4,this.paypalCommerceRequestSender.createOrder(e,(0,o.__assign)({cartId:n},t))];case 1:return[2,r.sent().orderId]}}))}))},e.prototype.updateOrder=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,t,n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getConsignmentsOrThrow()[0],r.label=1;case 1:return r.trys.push([1,3,,4]),[4,this.paypalCommerceRequestSender.updateOrder({availableShippingOptions:n.availableShippingOptions,cartId:t.id,selectedShippingOption:n.selectedShippingOption})];case 2:return r.sent(),[3,4];case 3:throw r.sent(),new c;case 4:return[2]}}))}))},e.prototype.getOrderStatus=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,this.paypalCommerceRequestSender.getOrderStatus()];case 1:return[2,e.sent().status];case 2:throw e.sent(),new c;case 3:return[2]}}))}))},e.prototype.tokenizePayment=function(e,t){var n=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new da(ca.MissingOrderId);return this.formPoster.postForm("/checkout.php",(0,o.__assign)({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},n.source===qa.BuyNow&&{cart_id:n.id}))},e.prototype.submitPayment=function(e,t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return n={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:e,paypal_account:{order_id:t}}},[4,this.paymentIntegrationService.submitPayment({methodId:e,paymentData:n})];case 1:return r.sent(),[2]}}))}))},e.prototype.getShippingOptionOrThrow=function(e){var t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],n=t.availableShippingOptions||[],r=n.find((function(e){return e.isRecommended})),i=(e?n.find((function(t){return t.id===e})):n.find((function(e){var n;return e.id===(null===(n=t.selectedShippingOption)||void 0===n?void 0:n.id)})))||r||n[0];if(!i)throw new Error("Your order can't be shipped to this address");return i},e.prototype.getAddress=function(e){return{firstName:(null==e?void 0:e.firstName)||"",lastName:(null==e?void 0:e.lastName)||"",email:(null==e?void 0:e.email)||"",phone:"",company:"",address1:(null==e?void 0:e.address1)||"",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:[]}},e.prototype.getBillingAddressFromOrderDetails=function(e){var t=e.payer;return this.getAddress({firstName:t.name.given_name,lastName:t.name.surname,email:t.email_address,address1:t.address.address_line_1,city:t.address.admin_area_2,countryCode:t.address.country_code,postalCode:t.address.postal_code,stateOrProvinceCode:t.address.admin_area_1})},e.prototype.getShippingAddressFromOrderDetails=function(e){var t,n,r=e.payer,i=(null===(n=null===(t=e.purchase_units[0])||void 0===t?void 0:t.shipping)||void 0===n?void 0:n.address)||{};return this.getAddress({firstName:r.name.given_name,lastName:r.name.surname,email:r.email_address,address1:i.address_line_1,city:i.admin_area_2,countryCode:i.country_code,postalCode:i.postal_code,stateOrProvinceCode:i.admin_area_1})},e.prototype.getValidButtonStyle=function(e){var t=e||{},n=t.color,r=t.height,i=t.label,o=t.shape,a={color:n&&xa[n]?n:void 0,height:this.getValidHeight(r),label:i&&Ga[i]?i:void 0,shape:o&&Ya[o]?o:void 0};return(0,m.omitBy)(a,m.isNil)},e.prototype.getValidHeight=function(e){return e&&"number"==typeof e?e>55?55:e<25?25:e:40},e.prototype.removeElement=function(e){var t=e&&document.getElementById(e);t&&t.remove()},e}();var Wa,Ka="This API endpoint is for internal use only and may change in the future";!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(Wa||(Wa={}));const Qa=Wa;var Za={"X-Checkout-SDK-Version":"1.398.1"};const Ja=function(){function e(e){this.requestSender=e}return e.prototype.createOrder=function(e,t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r,i;return(0,o.__generator)(this,(function(a){switch(a.label){case 0:return n="/api/storefront/payment/"+e,r=t,i=(0,o.__assign)({"X-API-INTERNAL":Ka,"Content-Type":Qa.Json},Za),[4,this.requestSender.post(n,{headers:i,body:r})];case 1:return[2,a.sent().body]}}))}))},e.prototype.updateOrder=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return t=e,n=(0,o.__assign)({"X-API-INTERNAL":Ka,"Content-Type":Qa.Json},Za),[4,this.requestSender.put("/api/storefront/initialization/paypalcommerce",{headers:n,body:t})];case 1:return[2,r.sent().body]}}))}))},e.prototype.getOrderStatus=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(t){switch(t.label){case 0:return e=(0,o.__assign)({"X-API-INTERNAL":Ka,"Content-Type":Qa.Json},Za),[4,this.requestSender.get("/api/storefront/initialization/paypalcommerce",{headers:e})];case 1:return[2,t.sent().body]}}))}))},e}(),Xa=function(){function e(e){this.scriptLoader=e,this.window=window}return e.prototype.getPayPalSDK=function(e,t,n){return(0,o.__awaiter)(this,void 0,void 0,(function(){var r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:return this.paypalSdk?[3,2]:(r=this,[4,this.loadPayPalSDK(this.getPayPalSdkScriptConfigOrThrow(e,t,n))]);case 1:r.paypalSdk=i.sent(),i.label=2;case 2:return[2,this.paypalSdk]}}))}))},e.prototype.loadPayPalSDK=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(t){switch(t.label){case 0:return this.window.paypalLoadScript?[3,2]:[4,this.scriptLoader.loadScript("https://unpkg.com/@paypal/paypal-js@5.0.5/dist/iife/paypal-js.min.js",{async:!0,attributes:{}})];case 1:if(t.sent(),!this.window.paypalLoadScript)throw new za;t.label=2;case 2:return[4,this.window.paypalLoadScript(e)];case 3:if(t.sent(),!this.window.paypal)throw new za;return[2,this.window.paypal]}}))}))},e.prototype.getPayPalSdkScriptConfigOrThrow=function(e,t,n){void 0===n&&(n=!0);var r=e.id,i=e.clientToken,a=e.initializationData;if(!(null==a?void 0:a.clientId))throw new da(ca.MissingPaymentMethod);var s=a.intent,u=a.clientId,c=a.merchantId,d=a.buyerCountry,p=a.attributionId,l=a.isVenmoEnabled,h=a.isHostedCheckoutEnabled,f=a.isPayPalCreditAvailable,m=a.isDeveloperModeApplicable,g=a.availableAlternativePaymentMethods,y=void 0===g?[]:g,_=a.enabledAlternativePaymentMethods,v=void 0===_?[]:_,C=h||n,S="paypalcommercecreditcards"===r,I=S?["card"]:[],E=S?[]:["card"],w=f?["credit","paylater"]:[],A=f?[]:["credit","paylater"],b=n||!C,P=b&&l?["venmo"]:[],O=b&&l?[]:["venmo"],T=b?v:[],R=b?y.filter((function(e){return!v.includes(e)})):y,M=(0,o.__spreadArrays)(E,A,O,R),D=(0,o.__spreadArrays)(I,w,P,T);return(0,o.__assign)({"client-id":u,"data-partner-attribution-id":p,"data-client-token":i,"merchant-id":c,"enable-funding":D.length>0?D:void 0,"disable-funding":M.length>0?M:void 0,commit:C,components:["buttons","hosted-fields","messages","payment-fields"],currency:t,intent:s},m&&{"buyer-country":d})},e}(),$a=function(e){var t=e.getState().getHost;return new ja((0,i.createFormPoster)(),e,new Ja((0,r.createRequestSender)({host:t()})),new Xa((0,Kn.getScriptLoader)()))},es=function(){function e(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}return e.prototype.initialize=function(e){var t;return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r,i,a,s;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(n=e.paypalcommerce,r=e.containerId,i=e.methodId,a=Boolean(null==n?void 0:n.buyNowInitializeOptions),!i)throw new aa('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new aa('Unable to initialize payment because "options.containerId" argument is not provided.');if(!n)throw new aa('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');if(a&&!n.currencyCode)throw new aa('Unable to initialize payment because "options.paypalcommerce.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null===(t=n.buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody))throw new aa('Unable to initialize payment because "options.paypalcommerce.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');return a?[3,2]:[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:o.sent(),o.label=2;case 2:return s=a?n.currencyCode:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,[4,this.paypalCommerceIntegrationService.loadPayPalSdk(i,s,!1)];case 3:return o.sent(),this.renderButton(r,i,n),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.renderButton=function(e,t,n){var r=this,i=n.buyNowInitializeOptions,a=n.style,s=n.onComplete,u=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),c=(this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t).initializationData||{}).isHostedCheckoutEnabled,d={createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommerce")},onApprove:function(e){var n=e.orderID;return r.paypalCommerceIntegrationService.tokenizePayment(t,n)}},p={onClick:function(){return r.handleClick(i)},onCancel:function(){return r.paymentIntegrationService.loadDefaultCheckout()}},l={onShippingAddressChange:function(e){return r.onShippingAddressChange(e)},onShippingOptionsChange:function(e){return r.onShippingOptionsChange(e)},onApprove:function(e,n){return r.onHostedCheckoutApprove(e,n,t,s)}},h=(0,o.__assign)((0,o.__assign)((0,o.__assign)({fundingSource:u.FUNDING.PAYPAL,style:this.paypalCommerceIntegrationService.getValidButtonStyle(a)},d),i&&p),c&&l),f=u.Buttons(h);f.isEligible()?f.render("#"+e):this.paypalCommerceIntegrationService.removeElement(e)},e.prototype.handleClick=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return e?[4,this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e)]:[3,3];case 1:return t=n.sent(),[4,this.paymentIntegrationService.loadCheckout(t.id)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},e.prototype.onHostedCheckoutApprove=function(e,t,n,r){return(0,o.__awaiter)(this,void 0,void 0,(function(){var i,a,s,u,c,d;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(!e.orderID)throw new da(ca.MissingOrderId);return i=this.paymentIntegrationService.getState(),a=i.getCartOrThrow(),[4,t.order.get()];case 1:s=o.sent(),o.label=2;case 2:return o.trys.push([2,9,,10]),u=this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(s),[4,this.paymentIntegrationService.updateBillingAddress(u)];case 3:return o.sent(),a.lineItems.physicalItems.length>0?(c=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(s),[4,this.paymentIntegrationService.updateShippingAddress(c)]):[3,6];case 4:return o.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:o.sent(),o.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return o.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,e.orderID)];case 8:return o.sent(),r&&"function"==typeof r&&r(),[2,!0];case 9:throw d=o.sent(),new Error(d);case 10:return[2]}}))}))},e.prototype.onShippingAddressChange=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:t=this.paypalCommerceIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.country_code,postalCode:e.shippingAddress.postal_code,stateOrProvinceCode:e.shippingAddress.state}),i.label=1;case 1:return i.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(t)];case 2:return i.sent(),[4,this.paymentIntegrationService.updateShippingAddress(t)];case 3:return i.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return i.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return i.sent(),[3,7];case 6:throw r=i.sent(),new Error(r);case 7:return[2]}}))}))},e.prototype.onShippingOptionsChange=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:t=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(t.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:throw n=r.sent(),new Error(n);case 5:return[2]}}))}))},e}(),ts=Ia((function(e){return new es(e,$a(e))}),[{id:"paypalcommerce"}]),ns=function(){function e(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}return e.prototype.initialize=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,a,s,u,c,d;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(t=e.paypalcommercecredit,n=e.containerId,r=e.methodId,a=(i=t||{}).buyNowInitializeOptions,s=i.currencyCode,u=i.messagingContainerId,c=!!a,!r)throw new aa('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new aa('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new aa('Unable to initialize payment because "options.paypalcommercecredit" argument is not provided.');if(c&&!s)throw new aa('Unable to initialize payment because "options.paypalcommercecredit.currencyCode" argument is not provided.');if(c&&"function"!=typeof(null==a?void 0:a.getBuyNowCartRequestBody))throw new aa('Unable to initialize payment because "options.paypalcommercecredit.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');return c?[3,2]:[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:o.sent(),o.label=2;case 2:return d=c?s:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,[4,this.paypalCommerceIntegrationService.loadPayPalSdk(r,d,!1)];case 3:return o.sent(),this.renderButton(n,r,t),this.renderMessages(u),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.renderButton=function(e,t,n){var r=this,i=n.buyNowInitializeOptions,a=n.style,s=n.onComplete,u=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),c=(this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t).initializationData||{}).isHostedCheckoutEnabled,d={createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommercecredit")},onApprove:function(e){var n=e.orderID;return r.paypalCommerceIntegrationService.tokenizePayment(t,n)}},p={onClick:function(){return r.handleClick(i)},onCancel:function(){return r.paymentIntegrationService.loadDefaultCheckout()}},l={onShippingAddressChange:function(e){return r.onShippingAddressChange(e)},onShippingOptionsChange:function(e){return r.onShippingOptionsChange(e)},onApprove:function(e,n){return r.onHostedCheckoutApprove(e,n,t,s)}},h=[u.FUNDING.PAYLATER,u.FUNDING.CREDIT],f=!1;h.forEach((function(t){if(!f){var n=(0,o.__assign)((0,o.__assign)((0,o.__assign)({fundingSource:t,style:r.paypalCommerceIntegrationService.getValidButtonStyle(a)},d),i&&p),c&&l),s=u.Buttons(n);s.isEligible()&&(s.render("#"+e),f=!0)}})),f||this.paypalCommerceIntegrationService.removeElement(e)},e.prototype.handleClick=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return e?[4,this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e)]:[3,3];case 1:return t=n.sent(),[4,this.paymentIntegrationService.loadCheckout(t.id)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},e.prototype.onHostedCheckoutApprove=function(e,t,n,r){return(0,o.__awaiter)(this,void 0,void 0,(function(){var i,a,s,u,c,d;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(!e.orderID)throw new da(ca.MissingOrderId);return i=this.paymentIntegrationService.getState(),a=i.getCartOrThrow(),[4,t.order.get()];case 1:s=o.sent(),o.label=2;case 2:return o.trys.push([2,9,,10]),u=this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(s),[4,this.paymentIntegrationService.updateBillingAddress(u)];case 3:return o.sent(),a.lineItems.physicalItems.length>0?(c=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(s),[4,this.paymentIntegrationService.updateShippingAddress(c)]):[3,6];case 4:return o.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:o.sent(),o.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return o.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,e.orderID)];case 8:return o.sent(),r&&"function"==typeof r&&r(),[2,!0];case 9:throw d=o.sent(),new Error(d);case 10:return[2]}}))}))},e.prototype.onShippingAddressChange=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:t=this.paypalCommerceIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.country_code,postalCode:e.shippingAddress.postal_code,stateOrProvinceCode:e.shippingAddress.state}),i.label=1;case 1:return i.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(t)];case 2:return i.sent(),[4,this.paymentIntegrationService.updateShippingAddress(t)];case 3:return i.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return i.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return i.sent(),[3,7];case 6:throw r=i.sent(),new Error(r);case 7:return[2]}}))}))},e.prototype.onShippingOptionsChange=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:t=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(t.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:throw n=r.sent(),new Error(n);case 5:return[2]}}))}))},e.prototype.renderMessages=function(e){var t=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();if(e&&document.getElementById(e)){var n={amount:this.paymentIntegrationService.getState().getCartOrThrow().cartAmount,placement:"cart",style:{layout:"text"}};t.Messages(n).render("#"+e)}},e}(),rs=Ia((function(e){return new ns(e,$a(e))}),[{id:"paypalcommercecredit"}]),is=function(){function e(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}return e.prototype.initialize=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,a,s,u,c;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(t=e.paypalcommercevenmo,n=e.containerId,r=e.methodId,a=(i=t||{}).buyNowInitializeOptions,s=i.currencyCode,u=!!a,!r)throw new aa('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new aa('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new aa('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');if(u&&!s)throw new aa('Unable to initialize payment because "options.paypalcommercevenmo.currencyCode" argument is not provided.');if(u&&"function"!=typeof(null==a?void 0:a.getBuyNowCartRequestBody))throw new aa('Unable to initialize payment because "options.paypalcommercevenmo.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');return u?[3,2]:[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:o.sent(),o.label=2;case 2:return c=u?s:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,[4,this.paypalCommerceIntegrationService.loadPayPalSdk(r,c,!1)];case 3:return o.sent(),this.renderButton(n,r,t),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.renderButton=function(e,t,n){var r=this,i=n.buyNowInitializeOptions,a=n.style,s=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),u=s.FUNDING.VENMO,c={createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommercevenmo")},onApprove:function(e){var n=e.orderID;return r.paypalCommerceIntegrationService.tokenizePayment(t,n)}},d={onClick:function(){return r.handleClick(i)},onCancel:function(){return r.paymentIntegrationService.loadDefaultCheckout()}},p=(0,o.__assign)((0,o.__assign)({fundingSource:u,style:this.getValidVenmoButtonStyles(a)},c),i&&d),l=s.Buttons(p);l.isEligible()?l.render("#"+e):this.paypalCommerceIntegrationService.removeElement(e)},e.prototype.getValidVenmoButtonStyles=function(e){var t=this.paypalCommerceIntegrationService.getValidButtonStyle(e);return t.color===xa.gold?(0,o.__assign)((0,o.__assign)({},t),{color:void 0}):t},e.prototype.handleClick=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return e?[4,this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e)]:[3,3];case 1:return t=n.sent(),[4,this.paymentIntegrationService.loadCheckout(t.id)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},e}(),os=Ia((function(e){return new is(e,$a(e))}),[{id:"paypalcommercevenmo"}]),as=function(){function e(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}return e.prototype.initialize=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,a,s,u,c,d;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(t=e.paypalcommercealternativemethods,n=e.containerId,r=e.methodId,a=(i=t||{}).apm,s=i.buyNowInitializeOptions,u=i.currencyCode,c=!!s,!r)throw new aa('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new aa('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new aa('Unable to initialize payment because "options.paypalcommercealternativemethods" argument is not provided.');if(!a)throw new aa('Unable to initialize payment because "options.paypalcommercealternativemethods.apm" argument is not provided.');if(c&&!u)throw new aa('Unable to initialize payment because "options.paypalcommercealternativemethods.currencyCode" argument is not provided.');if(c&&"function"!=typeof(null==s?void 0:s.getBuyNowCartRequestBody))throw new aa('Unable to initialize payment because "options.paypalcommercealternativemethods.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');return c?[3,2]:[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:o.sent(),o.label=2;case 2:return d=c?u:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,[4,this.paypalCommerceIntegrationService.loadPayPalSdk(r,d,!1)];case 3:return o.sent(),this.renderButton(n,r,t),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.renderButton=function(e,t,n){var r=this,i=n.apm,a=n.buyNowInitializeOptions,s=n.style,u=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();if(!Object.values(u.FUNDING).includes(i))throw new aa('Unable to initialize PayPal button because "options.paypalcommercealternativemethods.apm" argument is not valid funding source.');var c={createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommercealternativemethod")},onApprove:function(e){var n=e.orderID;return r.paypalCommerceIntegrationService.tokenizePayment(t,n)}},d={onClick:function(){return r.handleClick(a)},onCancel:function(){return r.paymentIntegrationService.loadDefaultCheckout()}},p=(0,o.__assign)((0,o.__assign)({fundingSource:i,style:this.paypalCommerceIntegrationService.getValidButtonStyle(s)},c),a&&d),l=u.Buttons(p);l.isEligible()?l.render("#"+e):this.paypalCommerceIntegrationService.removeElement(e)},e.prototype.handleClick=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return e?[4,this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e)]:[3,3];case 1:return t=n.sent(),[4,this.paymentIntegrationService.loadCheckout(t.id)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},e}(),ss=Ia((function(e){return new as(e,$a(e))}),[{id:"paypalcommercealternativemethods"}]);var us,cs,ds,ps,ls;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(us||(us={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(cs||(cs={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black"}(ds||(ds={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(ps||(ps={})),function(e){e.PILL="pill",e.RECT="rect"}(ls||(ls={}));const hs=function(){function e(e,t,n){this.paymentIntegrationService=e,this.paypalExpressScriptLoader=t,this.formPoster=n}return e.prototype.initialize=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:if(t=this.paymentIntegrationService.getState(),n=t.getPaymentMethodOrThrow(e.methodId),!e.paypal)throw new aa;if(!n.config.merchantId)throw new da(ca.MissingPaymentMethod);return[4,this.paypalExpressScriptLoader.loadPaypalSDK(n.config.merchantId)];case 1:return r=i.sent(),this.renderButton(e,r),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.renderButton=function(e,t){var n,r=this,i=e.containerId,o=e.methodId,a=e.paypal,s=a.allowCredit,u=a.clientId,c=a.onPaymentError,d=a.shouldProcessPayment,p=a.style,l=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId);if(!l.config.merchantId)throw new da(ca.MissingPaymentMethod);var h=l.config.merchantId,f=l.config.testMode?"sandbox":"production",m=((n={})[f]=u,n),g=t.FUNDING.CREDIT||"credit",y=s?[g]:[],_=s?[]:[g];return t.Button.render({env:f,client:m,commit:d,funding:{allowed:y,disallowed:_},style:this.getStyle(p),payment:function(e,t){return r.setupPayment(h,t,c)},onAuthorize:function(e,t){return r.tokenizePayment(e,o,t,d)}},i)},e.prototype.getStyle=function(e){var t=e||{},n=t.color,r=t.fundingicons,i=t.label,o=t.layout,a=t.shape,s=t.size,u=t.tagline;return{color:n,fundingicons:r,label:i,layout:o,shape:a||ls.RECT,size:"small"===s?cs.RESPONSIVE:s,tagline:u}},e.prototype.setupPayment=function(e,t,n){return(0,o.__awaiter)(this,void 0,void 0,(function(){var r,i,a,s;return(0,o.__generator)(this,(function(u){switch(u.label){case 0:if(!t)throw new ua(sa.CheckoutButtonNotInitialized);u.label=1;case 1:return u.trys.push([1,4,,5]),[4,this.paymentIntegrationService.loadDefaultCheckout()];case 2:return r=u.sent(),i=r.getCartOrThrow().id,a=r.getHost()||"",[4,t.request.post(a+"/api/storefront/payment/paypalexpress",{merchantId:e,cartId:i},{headers:(0,o.__assign)({"X-API-INTERNAL":Ka},Za)})];case 3:return[2,u.sent().id];case 4:throw s=u.sent(),n&&n(s),s;case 5:return[2]}}))}))},e.prototype.tokenizePayment=function(e,t,n,r){return(0,o.__awaiter)(this,void 0,void 0,(function(){var i,a,s;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(!n)throw new ua(sa.CheckoutButtonNotInitialized);if(!e.paymentID||!e.payerID)throw new da(ca.MissingPayment);return i=this.paymentIntegrationService.getState(),a=i.getPaymentMethodOrThrow(t),[4,n.payment.get(e.paymentID)];case 1:return s=o.sent(),[2,this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:a.id,action:r?"process_payment":"set_external_checkout",paymentId:e.paymentID,payerId:e.payerID,payerInfo:JSON.stringify(s.payer.payer_info)})]}}))}))},e}();const fs=function(){function e(e){this.scriptLoader=e,this.window=window}return e.prototype.loadPaypalSDK=function(e){return void 0===e&&(e=""),(0,o.__awaiter)(this,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return t=(0,o.__assign)({async:!0,attributes:{"data-merchant-id":e}},e&&{attributes:{"data-merchant-id":e}}),[4,this.scriptLoader.loadScript("//www.paypalobjects.com/api/checkout.min.js",t)];case 1:if(n.sent(),!this.window.paypal)throw new za;return[2,this.window.paypal]}}))}))},e}(),ms=Ia((function(e){return new hs(e,new fs((0,Kn.getScriptLoader)()),(0,i.createFormPoster)())}),[{id:"paypalexpress"}]);function gs(e){var t=null!=e?e:{},o=t.host,a=t.locale,s=void 0===a?"en":a,u=Bn(),c=(0,r.createRequestSender)({host:o}),d=(0,i.createFormPoster)({host:o}),p=function(e,t){void 0===t&&(t=n);for(var r=new Sa,i=function(t){if(!function(e){return"resolveIds"in e}(t))return"continue";for(var n=0,i=t.resolveIds;n{"use strict";var e={n:t=>{var n=t&&t.__esModule?()=>t.default:()=>t;return e.d(n,{a:n}),n},d:(t,n)=>{for(var r in n)e.o(n,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:n[r]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{createCheckoutButtonInitializer:()=>gs,createTimeout:()=>r.createTimeout});var n={};e.r(n),e.d(n,{createApplePayButtonStrategy:()=>Ta,createBoltButtonStrategy:()=>Fa,createPayPalCommerceAlternativeMethodsButtonStrategy:()=>ss,createPayPalCommerceButtonStrategy:()=>ts,createPayPalCommerceCreditButtonStrategy:()=>rs,createPayPalCommerceVenmoButtonStrategy:()=>os,createPaypalExpressButtonStrategy:()=>ms});const r=require("@bigcommerce/request-sender"),i=require("@bigcommerce/form-poster"),o=require("tslib"),a=require("@bigcommerce/data-store"),s=function(e){function t(t){var n,r,i=this.constructor,o=e.call(this,t||"An unexpected error has occurred.")||this;return o.name="StandardError",o.type="standard",n=o,r=i.prototype,Object.setPrototypeOf?Object.setPrototypeOf(n,r):n.__proto__=r,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(o,i):o.stack=new Error(o.message).stack,o}return(0,o.__extends)(t,e),t}(Error);var u={body:{},headers:{},status:0};const c=function(e){function t(t,n){var r=void 0===n?{}:n,i=r.message,o=r.errors,a=this,s=t||u,c=s.body,d=s.headers,p=s.status;return(a=e.call(this,i||"An unexpected error has occurred.")||this).name="RequestError",a.type="request",a.body=c,a.headers=d,a.status=p,a.errors=o||[],a}return(0,o.__extends)(t,e),t}(s),d=function(e){function t(t){var n=e.call(this,t,{message:"There is a problem processing your payment. Please try again later."})||this;return n.name="PaymentMethodInvalidError",n.type="payment_method_invalid",n}return(0,o.__extends)(t,e),t}(c);const p=function(e){function t(t){var n,r,i=this.constructor,o=e.call(this,t||"An unexpected error has occurred.")||this;return o.name="StandardError",o.type="standard",n=o,r=i.prototype,Object.setPrototypeOf?Object.setPrototypeOf(n,r):n.__proto__=r,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(o,i):o.stack=new Error(o.message).stack,o}return(0,o.__extends)(t,e),t}(Error);var l={body:{},headers:{},status:0};const h=function(e){function t(t,n){var r=void 0===n?{}:n,i=r.message,o=r.errors,a=this,s=t||l,u=s.body,c=s.headers,d=s.status;return(a=e.call(this,i||"An unexpected error has occurred.")||this).name="RequestError",a.type="request",a.body=u,a.headers=c,a.status=d,a.errors=o||[],a}return(0,o.__extends)(t,e),t}(p),f=function(e){function t(t,n){var r=e.call(this,t,{message:n||"An unexpected error has occurred. The checkout process cannot continue as a result."})||this;return r.name="UnrecoverableError",r.type="unrecoverable",r}return(0,o.__extends)(t,e),t}(h),m=require("lodash");function g(e){return e.reduce((function(e,t){return t?(0,o.__spreadArrays)(e,[t]):e}),[]).join(" ")}function y(e,t){var n=e.body.errors,r=void 0===n?[]:n;return new h(e,{message:_(r)||t,errors:r})}function _(e){if(Array.isArray(e))return e.reduce((function(e,t){return t&&t.message?(0,o.__spreadArrays)(e,[t.message]):e}),[]).join(" ")}const v=function(e){function t(t){var n=e.call(this,t,{message:"The request has timed out or aborted."})||this;return n.name="TimeoutError",n.type="timeout",n}return(0,o.__extends)(t,e),t}(h),C=function(){function e(){this._factoryMethods={},this.register("default",(function(e,t){return new h(e,{message:t})})),this.register("internal",(function(e,t){return function(e,t){var n=e.body,r=n.errors,i=void 0===r?[]:r;return new h(e,{message:g(i)||n.detail||n.title||t,errors:i.length?i.map((function(e){return{code:n.type,message:e}})):[{code:n.type,message:n.detail||n.title}]})}(e,t)})),this.register("storefront",(function(e,t){return function(e,t){var n=e.body;return new h(e,{message:t||n.detail||n.title,errors:[{code:n.code||n.type,message:n.detail||n.title}]})}(e,t)})),this.register("payment",(function(e,t){return y(e,t)})),this.register("timeout",(function(e){return new v(e)}))}return e.prototype.register=function(e,t){this._factoryMethods[e]=t},e.prototype.createError=function(e,t){return(this._factoryMethods[this._getType(e)]||this._factoryMethods.default)(e,t)},e.prototype._getType=function(e){if(0===e.status)return"timeout";if(this._isStorefrontErrorResponseBody(e.body))return"storefront";if(this._isInternalErrorResponseBody(e.body)){var t=(0,m.last)(e.body.type.split("/"));return t&&this._factoryMethods[t]?t:"internal"}var n=(0,m.last)(e.body&&e.body.errors);return n&&n.code&&this._factoryMethods[n.code]?n.code:"payment"},e.prototype._isStorefrontErrorResponseBody=function(e){var t=e;return!this._isInternalErrorResponseBody(e)&&"string"==typeof t.title&&"string"==typeof t.type&&"number"==typeof t.status&&"string"==typeof t.detail},e.prototype._isInternalErrorResponseBody=function(e){var t=e;return"object"==typeof t.errors&&"string"==typeof t.title&&"string"==typeof t.type&&"number"==typeof t.status},e}(),S=require("rxjs"),I=require("rxjs/operators");var E,w,A,b;function P(e,t){return Array.isArray(e)?e.map((function(e){return P(e,t)})):(0,m.isPlainObject)(e)?(0,m.transform)((0,m.omitBy)(e,t),(function(e,n,r){e[r]=P(n,t)}),{}):e}function O(e,t){return function(e){return e.type===w.ClearError}(t)?P(e,(function(e){return e===t.payload})):e}function T(e,t,n){return e===t||(e&&t&&"object"==typeof e&&"object"==typeof t?Array.isArray(e)&&Array.isArray(t)?function(e,t,n){if(e.length!==t.length)return!1;for(var r=0,i=e.length;r0}})),W=Tn(q,(function(e){return function(t){return!(!t||!t.nonce)||e()===Nn||e()===Ln}})),(0,An.memoizeOne)((function(e,t){return{getPaymentId:U({checkout:e,order:t}),getPaymentIdOrThrow:F({checkout:e,order:t}),getPaymentStatus:q({checkout:e,order:t}),getPaymentStatusOrThrow:B({checkout:e,order:t}),getPaymentToken:G({checkout:e,order:t}),getPaymentTokenOrThrow:x({checkout:e,order:t}),getPaymentRedirectUrl:Y({checkout:e,order:t}),getPaymentRedirectUrlOrThrow:H({checkout:e,order:t}),isPaymentDataRequired:j({checkout:e,order:t}),isPaymentDataSubmitted:W({checkout:e,order:t})}}))),Ae=function(){var e=Tn((function(e){return e.errors.applyError}),(function(e){return function(){return e}})),t=Tn((function(e){return!!e.statuses.isApplying}),(function(e){return function(){return e}}));return(0,An.memoizeOne)((function(n){return void 0===n&&(n=Fn),{getApplyError:e(n),isApplying:t(n)}}))}(),be=function(){var e=Tn((function(e){return e.errors.updateError}),(function(e){return function(){return e}})),t=Tn((function(e){return!!e.statuses.isUpdating}),(function(e){return function(){return e}}));return(0,An.memoizeOne)((function(n){return void 0===n&&(n=gn),{getUpdateError:e(n),isUpdating:t(n)}}))}(),Pe=(K=Tn((function(e){return e.data}),(function(e){return function(){return e}})),Q=Tn((function(e){return e.errors.sendError}),(function(e){return function(){return e}})),J=Tn((function(e){return!!e.statuses.isSending}),(function(e){return function(){return e}})),(0,An.memoizeOne)((function(e){return void 0===e&&(e=an),{getEmail:K(e),getSendError:Q(e),isSending:J(e)}}))),Te=function(){var e=Tn((function(e){return e.data}),(function(e){return function(){return e}})),t=Tn((function(e){return e.data}),(function(e){return function(t){return null==e?void 0:e.find((function(e){return e.region===t}))}})),n=Tn((function(e){return e.errors.loadError}),(function(e){return function(){return e}})),r=Tn((function(e){return e.statuses.isLoading}),(function(e){return function(){return!!e}}));return(0,An.memoizeOne)((function(i){return void 0===i&&(i=Ne),{getExtensions:e(i),getExtensionByRegion:t(i),getLoadError:n(i),isLoading:r(i)}}))}();return function(e,t){void 0===t&&(t={});var n,r=X(e.billingAddress),i=$(e.cart),o=ee(e.checkoutButton),a=ne(e.countries),s=re(e.coupons),u=ie(e.customer),c=ae(e.customerStrategies),d=Te(e.extensions),p=ce(e.formFields),l=se(e.giftCertificates),h=ue(e.instruments),f=Ee(e.orderBillingAddress),m=pe(e.paymentMethods),g=le(e.paymentStrategies),y=he(e.pickupOptions),_=fe(e.remoteCheckout),v=me(e.consignments),C=ye(e.shippingCountries),S=_e(e.shippingStrategies),I=be(e.subscriptions),E=Ae(e.storeCredit),w=Pe(e.signInEmail),A=ve(e.consignments,i),b=Ce(e.checkout,r,i,A,s,u,l),P=Se(e.order,f,s),O=we(b,P),T={billingAddress:r,cart:i,checkout:b,checkoutButton:o,config:te(e.config,e.formFields),consignments:A,countries:a,coupons:s,customer:u,customerStrategies:c,extensions:d,form:p,giftCertificates:l,instruments:h,order:P,orderBillingAddress:f,payment:O,paymentMethods:m,paymentStrategies:g,pickupOptions:y,remoteCheckout:_,shippingAddress:v,shippingCountries:C,shippingStrategies:S,signInEmail:w,subscriptions:I,storeCredit:E};return t.shouldWarnMutation?(n=T,Object.keys(n).reduce((function(e,t){return e[t]=Dn(n[t]),e}),{})):T}}function Bn(e,t){void 0===e&&(e={});var n,r,i=(n=new C,["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((function(e){n.register(e,(function(e,t){return new f(e,t)}))})),n.register("invalid_payment_provider",(function(e){return new d(e)})),n.register("payment_config_not_found",(function(e){return new d(e)})),r=n,function(e){return(0,S.from)(e).pipe((0,I.catchError)((function(e){if(e instanceof Error||e.payload instanceof Error)throw e;if((n=e.payload)&&"object"==typeof n&&["body","headers","status","statusText"].every((function(e){return Object.prototype.hasOwnProperty.call(n,e)}))){var t=e.payload.body&&e.payload.body.detail;throw(0,o.__assign)((0,o.__assign)({},e),{payload:r.createError(e.payload,t)})}var n;throw e})))}),s=qn();return(0,a.createDataStore)((0,a.combineReducers)({billingAddress:k,cart:H,checkout:Sn,checkoutButton:ee,config:ae,consignments:Nt,countries:je,coupons:pe,customer:Ee,customerStrategies:Te,extensions:Le,formFields:Ge,giftCertificates:ye,instruments:wt,orderBillingAddress:ot,order:Je,payment:st,paymentMethods:pt,paymentStrategies:_t,pickupOptions:xt,remoteCheckout:Rt,shippingCountries:Kt,shippingStrategies:en,signInEmail:sn,subscriptions:yn,storeCredit:ln}),e,(0,o.__assign)({actionTransformer:i,stateTransformer:function(e){return s(e)}},t))}function Gn(e,t,n){var r=new WeakMap;function i(e){var n=this;return function(){for(var i,a=[],s=0;s=400&&e.status<500)throw new or(e);throw e}))},e.prototype.updateCheckout=function(e,t,n){var r=void 0===n?{}:n,i=r.params,a=(void 0===i?{}:i).include,s=r.timeout,u="/api/storefront/checkout/"+e,c=(0,o.__assign)({Accept:Vn.JsonV1},jn);return this._requestSender.put(u,{params:{include:rr(ir,a)},body:t,headers:c,timeout:s})},e}(),sr=function(){function e(){}return e.prototype.isEqual=function(e,t){return(0,m.isEqual)(this._normalize(e),this._normalize(t))},e.prototype._normalize=function(e){return{cartAmount:e.cartAmount,currency:e.currency,id:e.id,lineItems:{digitalItems:e.lineItems.digitalItems.slice().sort((function(e,t){return(""+e.productId+e.variantId).localeCompare(""+t.productId+t.variantId)})).map((function(e){return{extendedSalePrice:e.extendedSalePrice,productId:e.productId,quantity:e.quantity,variantId:e.variantId}})),giftCertificates:e.lineItems.giftCertificates.slice().sort((function(e,t){return(""+e.id).localeCompare(""+t.id)})).map((function(e){return{amount:e.amount,recipient:e.recipient}})),physicalItems:e.lineItems.physicalItems.slice().sort((function(e,t){return(""+e.productId+e.variantId).localeCompare(""+t.productId+t.variantId)})).map((function(e){return{extendedSalePrice:e.extendedSalePrice,productId:e.productId,quantity:e.quantity,variantId:e.variantId,giftWrapping:e.giftWrapping}}))}}},e}(),ur=function(e){function t(t,n){var r=e.call(this,"An update to your shopping cart has been detected and your available shipping costs have been updated.")||this;return r.name="CartChangedError",r.type="cart_changed",r.data={previous:t,updated:n},r}return(0,o.__extends)(t,e),t}(p),cr=function(){function e(e){this._checkoutRequestSender=e}return e.prototype.validate=function(e,t){var n=this;if(!e)throw new Pn(bn.MissingCheckout);return this._checkoutRequestSender.loadCheckout(e.id,t).then((function(t){var r=new sr;if(!(e.outstandingBalance===t.body.outstandingBalance&&n._compareCoupons(e.coupons,t.body.coupons)&&n._compareGiftCertificates(e.giftCertificates,t.body.giftCertificates)&&r.isEqual(e.cart,t.body.cart)))throw new ur(n._getComparableCheckout(e),n._getComparableCheckout(t.body))}))},e.prototype._compareCoupons=function(e,t){return(0,m.isEqual)((0,m.map)(e,"code"),(0,m.map)(t,"code"))},e.prototype._compareGiftCertificates=function(e,t){return(0,m.isEqual)((0,m.map)(e,"code"),(0,m.map)(t,"code"))},e.prototype._getComparableCheckout=function(e){var t=e.cart,n=e.coupons,r=e.giftCertificates,i=e.outstandingBalance;return{cart:{cartAmount:t.cartAmount,currency:t.currency,lineItems:t.lineItems},coupons:n,giftCertificates:r,outstandingBalance:i}},e}(),dr=function(){function e(e){this._configRequestSender=e}return e.prototype.loadConfig=function(e){var t=this;return S.Observable.create((function(n){n.next((0,a.createAction)(Q.LoadConfigRequested)),t._configRequestSender.loadConfig(e).then((function(e){n.next((0,a.createAction)(Q.LoadConfigSucceeded,e.body)),n.complete()})).catch((function(e){n.error((0,a.createErrorAction)(Q.LoadConfigFailed,e))}))}))},(0,o.__decorate)([Gn],e.prototype,"loadConfig",null),e}(),pr=function(){function e(e){this._requestSender=e}return e.prototype.loadConfig=function(e){var t=void 0===e?{}:e,n=t.timeout,r=t.params;return this._requestSender.get("/api/storefront/checkout-settings",{timeout:n,headers:(0,o.__assign)({Accept:Vn.JsonV1,"X-API-INTERNAL":Hn},jn),params:r}).catch((function(e){if(e.status>=400&&e.status<500)throw new or(e);throw e}))},e}();function lr(e){var t=e;return"object"==typeof t&&"object"==typeof t.payload&&"string"==typeof t.payload.token}const hr=function(){function e(e,t,n){this._customerRequestSender=e,this._checkoutActionCreator=t,this._spamProtectionActionCreator=n}return e.prototype.createCustomer=function(e,t){var n=this;return function(r){var i=r.getState().config.getStoreConfigOrThrow().checkoutSettings.isStorefrontSpamProtectionEnabled,s=function(i){return(0,S.from)(n._customerRequestSender.createAccount((0,o.__assign)((0,o.__assign)({},e),{token:i}),t)).pipe((0,I.switchMap)((function(){return(0,S.concat)(n._checkoutActionCreator.loadCurrentCheckout(t)(r),(0,S.of)((0,a.createAction)(me.CreateCustomerSucceeded)))})))};return(0,S.concat)((0,S.of)((0,a.createAction)(me.CreateCustomerRequested)),i?(0,S.from)(n._spamProtectionActionCreator.execute()(r)).pipe((0,I.switchMap)((function(e){var t;return lr(e)?(0,S.concat)((0,S.of)(e),s(null===(t=e.payload)||void 0===t?void 0:t.token)):(0,S.of)(e)}))):s()).pipe((0,I.catchError)((function(e){return Qn(me.CreateCustomerFailed,e)})))}},e.prototype.createAddress=function(e,t){var n=this;return(0,S.concat)((0,S.of)((0,a.createAction)(me.CreateCustomerAddressRequested)),(0,S.defer)((function(){return(0,o.__awaiter)(n,void 0,void 0,(function(){var n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._customerRequestSender.createAddress(e,t)];case 1:return n=r.sent().body,[2,(0,a.createAction)(me.CreateCustomerAddressSucceeded,n)]}}))}))}))).pipe((0,I.catchError)((function(e){return Qn(me.CreateCustomerAddressFailed,e)})))},e.prototype.signInCustomer=function(e,t){var n=this;return function(r){return(0,S.concat)((0,S.of)((0,a.createAction)(me.SignInCustomerRequested)),(0,S.from)(n._customerRequestSender.signInCustomer(e,t)).pipe((0,I.switchMap)((function(e){var i=e.body;return(0,S.concat)(n._checkoutActionCreator.loadCurrentCheckout(t)(r),(0,S.of)((0,a.createAction)(me.SignInCustomerSucceeded,i.data)))})))).pipe((0,I.catchError)((function(e){return Qn(me.SignInCustomerFailed,e)})))}},e.prototype.signOutCustomer=function(e){var t=this;return function(n){return(0,S.concat)((0,S.of)((0,a.createAction)(me.SignOutCustomerRequested)),(0,S.from)(t._customerRequestSender.signOutCustomer(e)).pipe((0,I.switchMap)((function(r){var i=r.body;return(0,S.concat)(t._checkoutActionCreator.loadCurrentCheckout(e)(n),(0,S.of)((0,a.createAction)(me.SignOutCustomerSucceeded,i.data)))})))).pipe((0,I.catchError)((function(e){return Qn(me.SignOutCustomerFailed,e)})))}},e}(),fr=function(){function e(e){this._requestSender=e}return e.prototype.createAccount=function(e,t){var n=(void 0===t?{}:t).timeout;return this._requestSender.post("/api/storefront/customer",{timeout:n,headers:jn,body:e})},e.prototype.createAddress=function(e,t){var n=(void 0===t?{}:t).timeout;return this._requestSender.post("/api/storefront/customer-address",{timeout:n,headers:jn,body:e})},e.prototype.signInCustomer=function(e,t){var n=(void 0===t?{}:t).timeout;return this._requestSender.post("/internalapi/v1/checkout/customer",{timeout:n,headers:jn,body:e})},e.prototype.signOutCustomer=function(e){var t=(void 0===e?{}:e).timeout;return this._requestSender.delete("/internalapi/v1/checkout/customer",{timeout:t,headers:jn})},e}(),mr=function(){function e(e){this._formFieldsRequestSender=e}return e.prototype.loadFormFields=function(e){var t=this;return(0,S.concat)((0,S.of)((0,a.createAction)(ke.LoadFormFieldsRequested)),(0,S.defer)((function(){return(0,o.__awaiter)(t,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return[4,this._formFieldsRequestSender.loadFields(e)];case 1:return t=n.sent().body,[2,(0,a.createAction)(ke.LoadFormFieldsSucceeded,t)]}}))}))}))).pipe((0,I.catchError)((function(e){return Qn(ke.LoadFormFieldsFailed,e)})))},(0,o.__decorate)([Gn],e.prototype,"loadFormFields",null),e}(),gr=function(){function e(e){this._requestSender=e}return e.prototype.loadFields=function(e){var t=(void 0===e?{}:e).timeout;return this._requestSender.get("/api/storefront/form-fields",{timeout:t,headers:(0,o.__assign)({Accept:Vn.JsonV1,"X-API-INTERNAL":Hn},jn)})},e}(),yr=function(e){var t=this,n=new Promise((function(e,n){t.cancel=n}));this.promise=Promise.race([e,n])},_r=function(e){function t(t){var n=e.call(this,t||"Unable to proceed because the required element is unexpectedly detached from the page.")||this;return n.name="UnexpectedDetachmentError",n.type="unexpected_detachment",n}return(0,o.__extends)(t,e),t}(p),vr=function(){function e(e){this._mutationObserver=e}return e.prototype.ensurePresence=function(e,t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r,i,a;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:n=new yr(t),(r=this._mutationObserver.create((function(t){t.forEach((function(t){0!==Array.from(t.removedNodes).filter((function(t){return e.some((function(e){return t===e||t.contains(e)}))})).length&&n.cancel(new _r)}))}))).observe(document.body,{childList:!0,subtree:!0}),o.label=1;case 1:return o.trys.push([1,3,,4]),[4,n.promise];case 2:return i=o.sent(),r.disconnect(),[2,i];case 3:throw a=o.sent(),r.disconnect(),a;case 4:return[2]}}))}))},e}();var Cr=function(){function e(e){void 0===e&&(e=window),this._window=e}return e.prototype.create=function(e){return new this._window.MutationObserver(e)},e}();const Sr=function(e){function t(t){var n=e.call(this,t||"Invalid arguments have been provided.")||this;return n.name="InvalidArgumentError",n.type="invalid_argument",n}return(0,o.__extends)(t,e),t}(p);function Ir(e){if(!/^(https?:)?\/\//.test(e))throw new Sr("The provided URL must be absolute.");var t=document.createElement("a");t.href=e;var n=t.port&&-1!==e.indexOf(t.hostname+":"+t.port)?t.port:"";return{hash:t.hash,hostname:t.hostname,href:t.href,origin:t.protocol+"//"+t.hostname+(n?":"+n:""),pathname:t.pathname,port:n,protocol:t.protocol,search:t.search}}function Er(e,t){return e.type===t}const wr=function(){function e(e,t){this._targetWindow=t,this._targetOrigin="*"===e?"*":Ir(e).origin}return e.prototype.post=function(e,t){var n=this,r=this._targetWindow;if(window!==r){if(!r)throw new Error("Unable to post message because target window is not set.");var i=t&&(0,S.fromEvent)(window,"message").pipe((0,I.filter)((function(e){return e.origin===n._targetOrigin&&Er(e.data,e.data.type)&&-1!==[t.successType,t.errorType].indexOf(e.data.type)})),(0,I.map)((function(e){if(t.errorType===e.data.type)throw e.data;return e.data})),(0,I.take)(1)).toPromise();return r.postMessage(e,this._targetOrigin),i}},e.prototype.setTarget=function(e){this._targetWindow=e},e}(),Ar=function(e,t,n){return t&&n?br(0,t,n):function(e){var t=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return(0,o.__extends)(t,e),t}(e);return Object.getOwnPropertyNames(e.prototype).forEach((function(n){var r=Object.getOwnPropertyDescriptor(e.prototype,n);r&&"constructor"!==n&&Object.defineProperty(t.prototype,n,br(e.prototype,n,r))})),t}(e)};function br(e,t,n){if("function"!=typeof n.value)return n;var r=n.value;return{get:function(){var e=r.bind(this);return Object.defineProperty(this,t,(0,o.__assign)((0,o.__assign)({},n),{value:e})),e},set:function(e){r=e}}}const Pr=function(){function e(e){var t;this._sourceOrigins=[Ir(e).origin,(t=Ir(e),Ir(0===t.hostname.indexOf("www")?t.href:t.href.replace(t.hostname,"www."+t.hostname))).origin],this._isListening=!1,this._listeners={}}return e.prototype.listen=function(){this._isListening||(this._isListening=!0,window.addEventListener("message",this._handleMessage))},e.prototype.stopListen=function(){this._isListening&&(this._isListening=!1,window.removeEventListener("message",this._handleMessage))},e.prototype.addListener=function(e,t){var n=this._listeners[e];n||(this._listeners[e]=n=[]),-1===n.indexOf(t)&&n.push(t)},e.prototype.removeListener=function(e,t){var n=this._listeners[e];if(n){var r=n.indexOf(t);r>=0&&n.splice(r,1)}},e.prototype.trigger=function(e){var t=this._listeners[e.type];t&&t.forEach((function(t){return t(e)}))},e.prototype._handleMessage=function(e){-1!==this._sourceOrigins.indexOf(e.origin)&&Er(e.data,e.data.type)&&this.trigger(e.data)},(0,o.__decorate)([Ar],e.prototype,"_handleMessage",null),e}(),Or=function(e){function t(){var t=e.call(this,"You haven't complete our spam protection challenge. Please try again.")||this;return t.name="SpamProtectionChallengeNotCompletedError",t.type="spam_protection_challenge_not_completed",t}return(0,o.__extends)(t,e),t}(p),Tr=function(e){function t(){var t=e.call(this,"Please complete our human verification challenge and try again.")||this;return t.name="CardingProtectionChallengeNotCompletedError",t.type="carding_protection_challenge_not_completed",t}return(0,o.__extends)(t,e),t}(p),Rr=function(e){function t(){var t=e.call(this,"We were not able to verify that you are not a robot. Please try again.")||this;return t.name="CardingProtectionFailedError",t.type="carding_protection_failed",t}return(0,o.__extends)(t,e),t}(p),Mr=function(){function e(e){this._googleRecaptcha=e}return e.prototype.handle=function(e,t){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(n){return"string"==typeof e?[2,this.handleWithRecaptchaSitekey(e,t)]:[2,this.handleWithPaymentHumanVerificationRequestError(e)]}))}))},e.prototype.handleWithPaymentHumanVerificationRequestError=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(t){switch(t.label){case 0:if(!this._isPaymentHumanVerificationRequest(e))throw e;return[4,this._initialize(e.body.additional_action_required.data.key)];case 1:return t.sent(),[2,this._performRecaptcha()]}}))}))},e.prototype.handleWithRecaptchaSitekey=function(e,t){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if("recaptcha_v2"!==e)throw Error("Human verification method is not supported.");if(!t)throw Error("Recaptcha site key is missing.");return[4,this._initialize(t)];case 1:return n.sent(),[2,this._performRecaptcha()]}}))}))},e.prototype._performRecaptcha=function(){var e=this;return this._googleRecaptcha.execute().pipe((0,I.take)(1)).pipe((0,I.switchMap)((function(t){var n=t.error,r=t.token;return(0,o.__awaiter)(e,void 0,void 0,(function(){return(0,o.__generator)(this,(function(e){if(n instanceof Or)throw new Tr;if(n||!r)throw new Rr;return[2,{type:"recaptcha_v2_verification",data:{human_verification_token:r}}]}))}))}))).toPromise()},e.prototype._initialize=function(e){var t="cardingProtectionContainer",n=document.getElementById(t);return n&&n.parentNode&&n.parentNode.removeChild(n),(n=document.createElement("div")).setAttribute("id",t),document.body.appendChild(n),this._googleRecaptcha.load(t,e)},e.prototype._isPaymentHumanVerificationRequest=function(e){var t=e.body||{},n=t.additional_action_required;return"additional_action_required"===t.status&&n&&"recaptcha_v2_verification"===n.type},e}();var Dr;!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"}(Dr||(Dr={}));const kr=function(e){function t(t){var n=e.call(this,function(e){switch(e){case Dr.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case Dr.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case Dr.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case Dr.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."}}(t))||this;return n.subtype=t,n.name="NotInitializedError",n.type="not_initialized",n}return(0,o.__extends)(t,e),t}(p),Nr=function(e){function t(){var t=e.call(this,"We were not able to complete your spam protection verification. Please try again.")||this;return t.name="SpamProtectionFailedError",t.type="spam_protection_failed",t}return(0,o.__extends)(t,e),t}(p),Lr=function(e){function t(){var t=e.call(this,"Spam protection is not loaded. Please try again.")||this;return t.name="SpamProtectionNotLoadedError",t.type="spam_protection_failed",t}return(0,o.__extends)(t,e),t}(p),zr=function(){function e(e,t){var n=this;this.googleRecaptchaScriptLoader=e,this.mutationObserverFactory=t,this._memoized=(0,An.memoize)((function(e,t,r){var i=new S.Subject;if(!r)throw new Error;return n._widgetId=e.render(r.id,{sitekey:t,size:"invisible",callback:function(){i.next({token:e.getResponse(n._widgetId)}),e.reset(n._widgetId)},"error-callback":function(){i.next({error:new Nr})}}),i}),{isEqual:function(e,t){return e===t}})}return e.prototype.load=function(e,t){var n=this;return this.googleRecaptchaScriptLoader.load().then((function(r){r&&(n._event$=n._memoized(r,t,document.getElementById(e)),n._recaptcha=r)}))},e.prototype.execute=function(){var e=this;return(0,S.defer)((function(){var t=e._event$,n=e._recaptcha;if(!t||!n)throw new kr(Dr.SpamProtectionNotInitialized);return(0,S.defer)((function(){var e=document.querySelector('iframe[src*="bframe"]');return e?(0,S.of)(e):(0,S.throwError)(new Lr)})).pipe((0,I.retryWhen)((function(e){return e.pipe((0,I.delay)(250),(0,I.switchMap)((function(e,t){return t<28?(0,S.of)(e):(0,S.throwError)(e)})))})),(0,I.switchMap)((function(r){return e._watchRecaptchaChallengeWindow(t,r),n.execute(e._widgetId),t})),(0,I.catchError)((function(e){return(0,S.of)({error:e})})))}))},e.prototype._watchRecaptchaChallengeWindow=function(e,t){var n=t.parentElement;if(!n)throw new Lr;var r=n.parentElement;if(!r)throw new Lr;this.mutationObserverFactory.create((function(){"hidden"===r.style.visibility&&e.next({error:new Or})})).observe(r,{attributes:!0,attributeFilter:["style"]})},e}(),Ur=function(){function e(e,t){void 0===t&&(t=window),this._scriptLoader=e,this._window=t}return e.prototype.load=function(){return this._loadPromise||(this._loadPromise=this._loadScript()),this._loadPromise},e.prototype._loadScript=function(){var e=this,t="initRecaptcha",n=["onload="+t,"render=explicit"].join("&");return new Promise((function(r,i){e._window[t]=function(){return r(e._window.grecaptcha)},e._scriptLoader.loadScript("//www.google.com/recaptcha/api.js?"+n).catch((function(t){e._loadPromise=void 0,i(t)}))}))},e}();function Fr(e){return new zr(new Ur(e),new Cr)}const qr=function(e){function t(t){var n=e.call(this,t||"Unable to proceed due to invalid configuration provided for the hosted payment form.")||this;return n.name="InvalidHostedFormConfigError",n.type="invalid_hosted_form_config",n}return(0,o.__extends)(t,e),t}(p),Br=function(e){function t(t){var n=e.call(this,t||"Unable to proceed due to an unknown error with the hosted payment form.")||this;return n.name="InvalidHostedFormError",n.type="invalid_hosted_form",n}return(0,o.__extends)(t,e),t}(p),Gr=function(e){function t(t){var n=e.call(this,(0,o.__spreadArrays)(["Unable to proceed due to invalid user input values"],(0,m.flatMap)((0,m.values)(t),(function(e){return(0,m.map)(e,(function(e){return e.message}))}))).join(". "))||this;return n.errors=t,n.name="InvalidHostedFormValueError",n.type="invalid_hosted_form_value",n}return(0,o.__extends)(t,e),t}(p);var xr,Yr;!function(e){e.AttachRequested="HOSTED_FIELD:ATTACH_REQUESTED",e.SubmitRequested="HOSTED_FIELD:SUBMITTED_REQUESTED",e.ValidateRequested="HOSTED_FIELD:VALIDATE_REQUESTED"}(xr||(xr={})),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"}(Yr||(Yr={}));const Vr=function(){function e(e,t,n,r,i,o,a,s,u){this._type=e,this._containerId=t,this._placeholder=n,this._accessibilityLabel=r,this._styles=i,this._eventPoster=o,this._eventListener=a,this._detachmentObserver=s,this._cardInstrument=u,this._iframe=document.createElement("iframe"),this._iframe.src="/checkout/payment/hosted-field?version=1.398.2",this._iframe.style.border="none",this._iframe.style.height="100%",this._iframe.style.overflow="hidden",this._iframe.style.width="100%"}return e.prototype.getType=function(){return this._type},e.prototype.attach=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,t,n=this;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:if(!(e=document.getElementById(this._containerId)))throw new qr("Unable to proceed because the provided container ID is not valid.");return e.appendChild(this._iframe),this._eventListener.listen(),t=(0,S.fromEvent)(this._iframe,"load").pipe((0,I.switchMap)((function(e){var t=e.target;return(0,o.__awaiter)(n,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if(!(e=t&&t.contentWindow))throw new Error("The content window of the iframe cannot be accessed.");return this._eventPoster.setTarget(e),[4,this._eventPoster.post({type:xr.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:Yr.AttachSucceeded,errorType:Yr.AttachFailed})];case 1:return n.sent(),[2]}}))}))})),(0,I.take)(1)).toPromise(),[4,this._detachmentObserver.ensurePresence([this._iframe],t)];case 1:return r.sent(),[2]}}))}))},e.prototype.detach=function(){this._iframe.parentElement&&(this._iframe.parentElement.removeChild(this._iframe),this._eventListener.stopListen())},e.prototype.submitForm=function(e,t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),n=this._eventPoster.post({type:xr.SubmitRequested,payload:{fields:e,data:t}},{successType:Yr.SubmitSucceeded,errorType:Yr.SubmitFailed}),[4,this._detachmentObserver.ensurePresence([this._iframe],n)];case 1:return[2,i.sent()];case 2:if(r=i.sent(),this._isSubmitErrorEvent(r)){if("hosted_form_error"===r.payload.error.code)throw new Br(r.payload.error.message);if(r.payload.response)throw y(r.payload.response);throw new Error(r.payload.error.message)}throw r;case 3:return[2]}}))}))},e.prototype.validateForm=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return e=this._eventPoster.post({type:xr.ValidateRequested},{successType:Yr.Validated}),[4,this._detachmentObserver.ensurePresence([this._iframe],e)];case 1:if(!(t=n.sent().payload).isValid)throw new Gr(t.errors);return[2]}}))}))},e.prototype._getFontUrls=function(){var e=this,t="fonts.googleapis.com",n=document.querySelectorAll("link[href*='"+t+"'][rel='stylesheet']");return Array.prototype.slice.call(n).filter((function(e){return Ir(e.href).hostname===t})).filter((function(t){return(0,m.values)(e._styles).map((function(e){return e&&e.fontFamily})).filter((function(e){return"string"==typeof e})).some((function(e){return e.split(/,\s/).some((function(e){return-1!==t.href.indexOf(e.replace(" ","+"))}))}))})).map((function(e){return e.href}))},e.prototype._isSubmitErrorEvent=function(e){return e.type===Yr.SubmitFailed},e}(),Hr=function(){function e(e,t,n,r,i){var a=this;this._fields=e,this._eventListener=t,this._payloadTransformer=n,this._eventCallbacks=r,this._paymentHumanVerificationHandler=i,this._handleEnter=function(e){var t=e.payload;return(0,o.__awaiter)(a,void 0,void 0,(function(){var e,n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,this.validate()];case 1:return r.sent(),[3,3];case 2:if("InvalidHostedFormValueError"!==(e=r.sent()).name)throw e;return[3,3];case 3:return(void 0===(n=this._eventCallbacks.onEnter)?m.noop:n)(t),[2]}}))}))};var s=this._eventCallbacks,u=s.onBlur,c=void 0===u?m.noop:u,d=s.onCardTypeChange,p=void 0===d?m.noop:d,l=s.onFocus,h=void 0===l?m.noop:l,f=s.onValidate,g=void 0===f?m.noop:f;this._eventListener.addListener(Yr.Blurred,(function(e){var t=e.payload;return c(t)})),this._eventListener.addListener(Yr.CardTypeChanged,(function(e){var t=e.payload;return p(t)})),this._eventListener.addListener(Yr.Focused,(function(e){var t=e.payload;return h(t)})),this._eventListener.addListener(Yr.Validated,(function(e){var t=e.payload;return g(t)})),this._eventListener.addListener(Yr.Entered,this._handleEnter),this._eventListener.addListener(Yr.CardTypeChanged,(function(e){var t=e.payload;return a._cardType=t.cardType})),this._eventListener.addListener(Yr.BinChanged,(function(e){var t=e.payload;return a._bin=t.bin}))}return e.prototype.getBin=function(){return this._bin},e.prototype.getCardType=function(){return this._cardType},e.prototype.attach=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return this._eventListener.listen(),e=this._getFirstField(),t=(0,m.without)(this._fields,e),[4,e.attach()];case 1:return n.sent(),[4,Promise.all(t.map((function(e){return e.attach()})))];case 2:return n.sent(),[2]}}))}))},e.prototype.detach=function(){this._eventListener.stopListen(),this._fields.forEach((function(e){e.detach()}))},e.prototype.submit=function(e,t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,5]),[4,this._getFirstField().submitForm(this._fields.map((function(e){return e.getType()})),this._payloadTransformer.transform(e,t))];case 1:case 4:return[2,i.sent()];case 2:return n=i.sent(),[4,this._paymentHumanVerificationHandler.handle(n)];case 3:return r=i.sent(),[4,this._getFirstField().submitForm(this._fields.map((function(e){return e.getType()})),this._payloadTransformer.transform(e,r))];case 5:return[2]}}))}))},e.prototype.validate=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(e){return[2,this._getFirstField().validateForm()]}))}))},e.prototype._getFirstField=function(){var e=this._fields[0];if(!e)throw new qr("Unable to proceed because the payment form has no field defined.");return e},e}();function jr(e){return Boolean(e.instrumentId)}const Wr=function(){function e(e){this._store=e}return e.prototype.transform=function(e,t){var n=this._store.getState(),r=n.checkout.getCheckout(),i=n.config.getConfig(),o=n.instruments.getInstrumentsMeta(),a=n.order.getOrder(),s=n.order.getOrderMeta(),u=(0,m.omit)(e.paymentData,"ccExpiry","ccName","ccNumber","ccCvv"),c=n.paymentMethods.getPaymentMethod(e.methodId,e.gatewayId),d=n.paymentMethods.getPaymentMethodsMeta(),p=o&&u&&jr(u)?n.payment.getPaymentToken()+", "+o.vaultAccessToken:n.payment.getPaymentToken();if(!p)throw new Pn(bn.MissingPaymentToken);return{additionalAction:t,authToken:p,checkout:r,config:i,order:a,orderMeta:s,payment:u,paymentMethod:c,paymentMethodMeta:d}},e}(),Kr=function(){function e(e){this._store=e}return e.prototype.create=function(e,t){var n=this,r=Object.keys(t.fields).reduce((function(r,i){var a=t.fields[i];return a?(0,o.__spreadArrays)(r,[new Vr(i,a.containerId,a.placeholder||"",a.accessibilityLabel||"",t.styles||{},new wr(e),new Pr(e),new vr(new Cr),"instrumentId"in a?n._getCardInstrument(a.instrumentId):void 0)]):r}),[]);return new Hr(r,new Pr(e),new Wr(this._store),(0,m.pick)(t,"onBlur","onEnter","onFocus","onCardTypeChange","onValidate"),new Mr(Fr((0,Kn.createScriptLoader)())))},e.prototype._getCardInstrument=function(e){var t=(0,this._store.getState().instruments.getCardInstrument)(e);if(!t)throw new Pn(bn.MissingPaymentInstrument);return t},e}(),Qr=function(e){function t(){var t=e.call(this,"You haven't complete our spam check. Please try again.")||this;return t.name="SpamProtectionNotCompletedError",t.type="spam_protection_not_completed",t}return(0,o.__extends)(t,e),t}(p),Zr=function(){function e(e,t){this._orderRequestSender=e,this._checkoutValidator=t}return e.prototype.loadOrder=function(e,t){var n=this;return new S.Observable((function(r){r.next((0,a.createAction)(ie.LoadOrderRequested)),n._orderRequestSender.loadOrder(e,t).then((function(e){r.next((0,a.createAction)(ie.LoadOrderSucceeded,e.body)),r.complete()})).catch((function(e){r.error((0,a.createErrorAction)(ie.LoadOrderFailed,e))}))}))},e.prototype.loadOrderPayments=function(e,t){var n=this;return new S.Observable((function(r){r.next((0,a.createAction)(ie.LoadOrderPaymentsRequested)),n._orderRequestSender.loadOrder(e,t).then((function(e){r.next((0,a.createAction)(ie.LoadOrderPaymentsSucceeded,e.body)),r.complete()})).catch((function(e){r.error((0,a.createErrorAction)(ie.LoadOrderPaymentsFailed,e))}))}))},e.prototype.loadCurrentOrder=function(e){var t=this;return function(n){return(0,S.defer)((function(){var r=t._getCurrentOrderId(n.getState());if(!r)throw new Pn(bn.MissingOrderId);return t.loadOrder(r,e)}))}},e.prototype.submitOrder=function(e,t){var n=this;return function(r){return(0,S.concat)((0,S.of)((0,a.createAction)(ie.SubmitOrderRequested)),(0,S.defer)((function(){var i=r.getState(),s=i.config.getExternalSource(),u=i.config.getVariantIdentificationToken(),c=i.checkout.getCheckout();if(!c)throw new Pn(bn.MissingCheckout);if(c.shouldExecuteSpamCheck)throw new Qr;return(0,S.from)(n._checkoutValidator.validate(c,t).then((function(){return n._orderRequestSender.submitOrder(n._mapToOrderRequestBody(null!=e?e:{},c.id,c.customerMessage,s),(0,o.__assign)((0,o.__assign)({},t),{headers:{checkoutVariant:u}}))}))).pipe((0,I.switchMap)((function(e){return(0,S.concat)(n.loadOrder(e.body.data.order.orderId,t),(0,S.of)((0,a.createAction)(ie.SubmitOrderSucceeded,e.body.data,(0,o.__assign)((0,o.__assign)({},e.body.meta),{token:e.headers.token}))))})))})).pipe((0,I.catchError)((function(e){return Qn(ie.SubmitOrderFailed,e)}))))}},e.prototype.finalizeOrder=function(e,t){var n=this;return(0,S.concat)((0,S.of)((0,a.createAction)(ie.FinalizeOrderRequested)),(0,S.from)(this._orderRequestSender.finalizeOrder(e,t)).pipe((0,I.switchMap)((function(r){return(0,S.concat)(n.loadOrder(e,t),(0,S.of)((0,a.createAction)(ie.FinalizeOrderSucceeded,r.body.data)))})))).pipe((0,I.catchError)((function(e){return Qn(ie.FinalizeOrderFailed,e)})))},e.prototype._getCurrentOrderId=function(e){var t=e.order.getOrder(),n=e.checkout.getCheckout();return t&&t.orderId||n&&n.orderId},e.prototype._mapToOrderRequestBody=function(e,t,n,r){var i=e.payment,a=(0,o.__rest)(e,["payment"]);return i?(0,o.__assign)((0,o.__assign)({},a),{cartId:t,customerMessage:n,externalSource:r,payment:{paymentData:i.paymentData,name:i.methodId,gateway:i.gatewayId}}):(0,o.__assign)((0,o.__assign)({},a),{cartId:t,customerMessage:n,externalSource:r})},e}(),Jr=function(e){function t(t){var n=e.call(this,t||"Your checkout could not be processed because some details have changed. Please review your order and try again.")||this;return n.name="CartConsistencyError",n.type="cart_consistency",n}return(0,o.__extends)(t,e),t}(p),Xr=function(e){function t(t){var n=e.call(this,t||"The tax provider is unavailable.")||this;return n.name="OrderTaxProviderUnavailableError",n.type="tax_provider_unavailable",n}return(0,o.__extends)(t,e),t}(p),$r=function(){function e(e){this._requestSender=e}return e.prototype.loadOrder=function(e,t){var n=(void 0===t?{}:t).timeout,r="/api/storefront/orders/"+e,i=(0,o.__assign)({Accept:Vn.JsonV1},jn);return this._requestSender.get(r,{params:{include:nr(["payments","lineItems.physicalItems.socialMedia","lineItems.physicalItems.options","lineItems.physicalItems.categories","lineItems.digitalItems.socialMedia","lineItems.digitalItems.options","lineItems.digitalItems.categories"])},headers:i,timeout:n})},e.prototype.submitOrder=function(e,t){var n=void 0===t?{}:t,r=n.headers,i=n.timeout;return this._requestSender.post("/internalapi/v1/checkout/order",{body:e,headers:(0,m.omitBy)((0,o.__assign)({"X-Checkout-Variant":r&&r.checkoutVariant},jn),m.isNil),timeout:i}).catch((function(e){if("tax_provider_unavailable"===e.body.type)throw new Xr;if("cart_has_changed"===e.body.type)throw new Jr;throw e}))},e.prototype.finalizeOrder=function(e,t){var n=(void 0===t?{}:t).timeout,r="/internalapi/v1/checkout/order/"+e;return this._requestSender.post(r,{timeout:n,headers:jn})},e}(),ei=function(){function e(e,t,n,r){var i=this;this._paymentRequestSender=e,this._orderActionCreator=t,this._paymentRequestTransformer=n,this._paymentHumanVerificationHandler=r,this.initializeOffsitePayment=function(e){var t=e.methodId,n=e.gatewayId,r=e.instrumentId,o=e.target,s=e.promise,u=e.shouldSaveInstrument,c=e.shouldSetAsDefaultInstrument;return function(e){var d;r?d={formattedPayload:{bigpay_token:r}}:u&&(d={formattedPayload:{vault_payment_instrument:u,set_as_default_stored_instrument:c||null}});var p=i._paymentRequestTransformer.transform({gatewayId:n,methodId:t,paymentData:d},e.getState());return(0,S.concat)((0,S.of)((0,a.createAction)(nt.InitializeOffsitePaymentRequested)),Promise.race([i._paymentRequestSender.initializeOffsitePayment(p,o),s].filter(Boolean)).then((function(){return(0,a.createAction)(nt.InitializeOffsitePaymentSucceeded)}))).pipe((0,I.catchError)((function(e){return Qn(nt.InitializeOffsitePaymentFailed,e)})))}}}return e.prototype.submitPayment=function(e){var t=this;return function(n){return(0,S.concat)((0,S.of)((0,a.createAction)(nt.SubmitPaymentRequested)),(0,S.defer)((function(){return(0,o.__awaiter)(t,void 0,void 0,(function(){var t,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,5]),[4,this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform(e,n.getState()))];case 1:case 4:return[2,i.sent()];case 2:return t=i.sent(),[4,this._paymentHumanVerificationHandler.handle(t)];case 3:return r=i.sent(),[4,this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform((0,o.__assign)((0,o.__assign)({},e),{additionalAction:r}),n.getState()))];case 5:return[2]}}))}))})).pipe((0,I.switchMap)((function(e){var r=e.body;return(0,S.concat)(t._orderActionCreator.loadCurrentOrder()(n),(0,S.of)((0,a.createAction)(nt.SubmitPaymentSucceeded,r)))})))).pipe((0,I.catchError)((function(e){return Qn(nt.SubmitPaymentFailed,e)})))}},e}(),ti=function(){function e(e){this._client=e}return e.prototype.submitPayment=function(e){var t=this;return new Promise((function(n,r){t._client.submitPayment(e,(function(e,i){e?r(t._transformResponse(e)):n(t._transformResponse(i))}))}))},e.prototype.initializeOffsitePayment=function(e,t){var n=this;return new Promise((function(){n._client.initializeOffsitePayment(e,null,t)}))},e.prototype._transformResponse=function(e){return{headers:e.headers,body:e.data,status:e.status,statusText:e.statusText}},e}(),ni=require("@bigcommerce/bigpay-client");function ri(e,t){var n;return function(e){return void 0!==e.id}(e)?n=e.id:t&&t.length&&(n=t[0].id),{id:n,firstName:e.firstName,lastName:e.lastName,company:e.company,addressLine1:e.address1,addressLine2:e.address2,city:e.city,province:e.stateOrProvince,provinceCode:e.stateOrProvinceCode,postCode:e.postalCode,country:e.country,countryCode:e.countryCode,phone:e.phone,customFields:e.customFields}}const ii=function(){function e(e){this._decimalPlaces=e}return e.prototype.toInteger=function(e){return Math.round(e*Math.pow(10,this._decimalPlaces))},e}();var oi,ai=["per_item_discount","percentage_discount","per_total_discount","shipping_discount","free_shipping"];function si(e){return{code:e.code,discount:e.displayName,discountType:ai.indexOf(e.couponType)}}function ui(e){return{code:e.code,discountedAmount:e.used,remainingBalance:e.remaining,giftCertificate:{balance:e.balance,code:e.code,purchaseDate:e.purchaseDate}}}function ci(e,t,n){return void 0===n&&(n="id"),Object.keys(e).reduce((function(r,i){return(0,o.__spreadArrays)(r,e[i].map((function(e){return"giftCertificates"===i?function(e,t){var n=new ii(t);return{id:e.id,imageUrl:"",name:e.name,amount:e.amount,amountAfterDiscount:e.amount,discount:0,integerAmount:n.toInteger(e.amount),integerAmountAfterDiscount:n.toInteger(e.amount),integerUnitPrice:n.toInteger(e.amount),integerUnitPriceAfterDiscount:n.toInteger(e.amount),integerDiscount:0,quantity:1,sender:e.sender,recipient:e.recipient,type:"ItemGiftCertificateEntity",attributes:[],variantId:null}}(e,t):function(e,t,n,r){void 0===r&&(r="id");var i=new ii(n);return{id:e[r],imageUrl:e.imageUrl,amount:e.extendedListPrice,amountAfterDiscount:e.extendedSalePrice,discount:e.discountAmount,integerAmount:i.toInteger(e.extendedListPrice),integerAmountAfterDiscount:i.toInteger(e.extendedSalePrice),integerDiscount:i.toInteger(e.discountAmount),integerUnitPrice:i.toInteger(e.listPrice),integerUnitPriceAfterDiscount:i.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((function(e){return{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""}}(i),t,n)})))}),[])}function di(e){var t,n,r=e.cart.currency.decimalPlaces,i=new ii(r);return{id:e.cart.id,items:ci(e.cart.lineItems,r),currency:e.cart.currency.code,coupon:{discountedAmount:(0,m.reduce)(e.cart.coupons,(function(e,t){return e+t.discountedAmount}),0),coupons:e.cart.coupons.map(si)},discount:{amount:e.cart.discountAmount,integerAmount:i.toInteger(e.cart.discountAmount)},discountNotifications:(t=e.promotions,n=[],(t||[]).forEach((function(e){(e.banners||[]).forEach((function(e){n.push({placeholders:[],discountType:null,message:"",messageHtml:e.text})}))})),n),giftCertificate:{totalDiscountedAmount:(0,m.reduce)(e.giftCertificates,(function(e,t){return e+t.used}),0),appliedGiftCertificates:(0,m.keyBy)(e.giftCertificates.map(ui),"code")},shipping:{amount:e.shippingCostTotal,integerAmount:i.toInteger(e.shippingCostTotal),amountBeforeDiscount:e.shippingCostBeforeDiscount,integerAmountBeforeDiscount:i.toInteger(e.shippingCostBeforeDiscount),required:(0,m.some)(e.cart.lineItems.physicalItems,(function(e){return 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)}}}!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.MASTERPASS="masterpass",e.PAYPALEXPRESS="paypalexpress"}(oi||(oi={}));const pi=oi;function li(e,t){var n=e.firstName||t.firstName||"",r=e.lastName||t.lastName||"";return{addresses:(e.addresses||[]).map((function(e){return ri(e)})),customerId:e.id,isGuest:e.isGuest,storeCredit:e.storeCredit,email:e.email||t.email||"",firstName:n,lastName:r,name:e.fullName||[n,r].join(" "),customerGroupName:e.customerGroup&&e.customerGroup.name}}const hi=function(){function e(){}return e.prototype.format=function(e){var t=e.split(new RegExp("\\s*/\\s*")),n=t[0],r=void 0===n?"":n,i=t[1],o=void 0===i?"":i,a=r.slice(0,2),s=4===o.length?o.slice(-2):o?o.slice(0,2):r.slice(2);return e.length<2?r:e.length>3&&!s?a:a+" / "+s},e.prototype.toObject=function(e){var t=e.split(new RegExp("\\s*/\\s*")),n=t[0],r=void 0===n?"":n,i=t[1],o=void 0===i?"":i;return/^\d+$/.test(r)&&/^\d+$/.test(o)?{month:1===r.length?"0"+r:r.slice(0,2),year:2===o.length?"20"+o:o.slice(0,4)}:{month:"",year:""}},e}(),fi=require("card-validator"),mi=function(){function e(){}return e.prototype.format=function(e){var t=(0,fi.number)(e).card;if(!t)return e;var n=(0,m.max)((0,fi.creditCardType)(e).map((function(e){return(0,m.max)(e.lengths)}))),r=this.unformat(e).slice(0,n);return t.gaps.filter((function(e){return r.length>e})).reduce((function(e,t,n){return[e.slice(0,t+n),e.slice(t+n)].join(" ")}),r)},e.prototype.unformat=function(e){return(0,fi.number)(e).card?e.replace(new RegExp(" ","g"),""):e},e}();function gi(e,t){void 0===t&&(t={});var n,r,i=e.currency.decimalPlaces,o=new ii(i);return{id:e.orderId,items:ci(e.lineItems,e.currency.decimalPlaces,"productId"),orderId:e.orderId,currency:e.currency.code,customerCanBeCreated:e.customerCanBeCreated,payment:_i(e.payments,t.payment),subtotal:{amount:e.baseAmount,integerAmount:o.toInteger(e.baseAmount)},coupon:{discountedAmount:(0,m.reduce)(e.coupons,(function(e,t){return e+t.discountedAmount}),0),coupons:e.coupons.map(si)},discount:{amount:e.discountAmount,integerAmount:o.toInteger(e.discountAmount)},token:t.orderToken,callbackUrl:t.callbackUrl,discountNotifications:[],giftCertificate:(n=e.payments,r=(0,m.filter)(n,{providerId:"giftcertificate"}),{totalDiscountedAmount:(0,m.reduce)(r,(function(e,t){return t.amount+e}),0),appliedGiftCertificates:(0,m.keyBy)(r.map((function(e){return{code:e.detail.code,discountedAmount:e.amount,remainingBalance:e.detail.remaining,giftCertificate:{balance:e.amount+e.detail.remaining,code:e.detail.code,purchaseDate:""}}})),"code")}),socialData:Ci(e),status:e.status,hasDigitalItems:e.hasDigitalItems,isDownloadable:e.isDownloadable,isComplete:e.isComplete,shipping:{amount:e.shippingCostTotal,integerAmount:o.toInteger(e.shippingCostTotal),amountBeforeDiscount:e.shippingCostBeforeDiscount,integerAmountBeforeDiscount:o.toInteger(e.shippingCostBeforeDiscount)},storeCredit:{amount:yi(e.payments)},taxes:e.taxes,taxTotal:{amount:e.taxTotal,integerAmount:o.toInteger(e.taxTotal)},handling:{amount:e.handlingCostTotal,integerAmount:o.toInteger(e.handlingCostTotal)},grandTotal:{amount:e.orderAmount,integerAmount:e.orderAmountAsInteger}}}function yi(e){var t=(0,m.find)(e,{providerId:"storecredit"});return t?t.amount:0}function _i(e,t){void 0===t&&(t={});var n,r=(0,m.find)(e,vi);return r?{id:r.providerId,status:(n=r.detail.step,"PAYMENT_STATUS_"+n),helpText:r.detail.instructions,returnUrl:t.returnUrl}:{}}function vi(e){return"giftcertificate"!==e.providerId&&"storecredit"!==e.providerId}function Ci(e){var t={};return(0,o.__spreadArrays)(e.lineItems.physicalItems,e.lineItems.digitalItems).forEach((function(e){var n;t[e.id]=(n=e,["fb","tw","gp"].reduce((function(e,t){var r=n.socialMedia&&(0,m.find)(n.socialMedia,(function(e){return e.code===t}));return r?(e[t]={name:n.name,description:n.name,image:n.imageUrl,url:r.link,shareText:r.text,sharingLink:r.link,channelName:r.channel,channelCode:r.code},e):e}),{}))})),t}function Si(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}}const Ii=function(){function e(){this._cardExpiryFormatter=new hi,this._cardNumberFormatter=new mi}return e.prototype.transform=function(e,t){var n,r=t.billingAddress.getBillingAddress(),i=t.checkout.getCheckout(),a=t.customer.getCustomer(),s=t.order.getOrder(),u=t.paymentMethods.getPaymentMethod(e.methodId,e.gatewayId),c=this._mapShippingAddress(t,u),d=t.consignments.getConsignments(),p=t.consignments.getShippingOption(),l=t.config.getStoreConfig(),h=t.config.getContextConfig(),f=t.instruments.getInstrumentsMeta(),g=t.paymentMethods.getPaymentMethodsMeta(),y=t.order.getOrderMeta(),_=a&&r&&li(a,r),v=f&&e.paymentData&&(jr(e.paymentData)||(n=e.paymentData.formattedPayload)&&("string"==typeof n.bigpay_token||Boolean(n.bigpay_token&&n.bigpay_token.token)))?t.payment.getPaymentToken()+", "+f.vaultAccessToken:t.payment.getPaymentToken();if(!v)throw new Pn(bn.MissingPaymentToken);return{additionalAction:e.additionalAction,authToken:v,customer:_,billingAddress:r&&ri(r),shippingAddress:c&&ri(c,d),shippingOption:p&&Si(p,!0),cart:i&&di(i),order:s&&gi(s,y),orderMeta:y,payment:e.paymentData,paymentMethod:u&&this._transformPaymentMethod(u),quoteMeta:{request:(0,o.__assign)((0,o.__assign)({},g),{geoCountryCode:h&&h.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:(0,m.pick)(l&&l.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}},e.prototype.transformWithHostedFormData=function(e,t,n){var r=t.additionalAction,i=t.authToken,a=t.checkout,s=t.config,u=t.order,c=t.orderMeta,d=t.payment,p=void 0===d?{}:d,l=t.paymentMethod,h=t.paymentMethodMeta,f=a&&a.consignments[0],g=f&&f.shippingAddress,y=f&&f.selectedShippingOption;return{additionalAction:r,authToken:i,paymentMethod:l&&this._transformPaymentMethod(l),customer:u&&u.billingAddress&&a&&li(a.customer,u.billingAddress),billingAddress:u&&u.billingAddress&&ri(u.billingAddress),shippingAddress:g&&a&&ri(g,a.consignments),shippingOption:y&&Si(y,!0),cart:a&&di(a),order:u&&gi(u,c),orderMeta:c,payment:this._transformHostedInputValues(e,p,n),quoteMeta:{request:(0,o.__assign)((0,o.__assign)({},h),{geoCountryCode:s&&s.context.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:s&&(0,m.pick)(s.storeConfig.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}},e.prototype._transformPaymentMethod=function(e){return"multi-option"!==e.method||e.gateway?e.initializationData&&e.initializationData.gateway?(0,o.__assign)((0,o.__assign)({},e),{id:e.initializationData.gateway}):e.id===pi.BRAINTREE_VENMO?(0,o.__assign)((0,o.__assign)({},e),{id:pi.BRAINTREE_PAYPAL}):e:(0,o.__assign)((0,o.__assign)({},e),{gateway:e.id})},e.prototype._transformHostedInputValues=function(e,t,n){return"instrumentId"in t?(0,o.__assign)((0,o.__assign)({},t),{ccCvv:e.cardCodeVerification,ccNumber:e.cardNumberVerification&&this._cardNumberFormatter.unformat(e.cardNumberVerification),hostedFormNonce:n}):(0,o.__assign)((0,o.__assign)({},t),{ccCvv:e.cardCode,ccExpiry:this._cardExpiryFormatter.toObject(e.cardExpiry||""),ccName:e.cardName||"",ccNumber:this._cardNumberFormatter.unformat(e.cardNumber||""),hostedFormNonce:n})},e.prototype._mapShippingAddress=function(e,t){var n,r,i,o;if(t){var a=null===(r=null===(n=t.initializationData)||void 0===n?void 0:n.bopis)||void 0===r?void 0:r.enabled,s=null===(o=null===(i=t.initializationData)||void 0===i?void 0:i.bopis)||void 0===o?void 0:o.requiredAddress,u=e.consignments.getConsignments(),c=null==u?void 0:u.every((function(e){return e.selectedPickupOption}));if(a&&c&&"none"===s)return}return e.shippingAddress.getShippingAddress()},e}();var Ei;!function(e){e.AvailableShippingOptions="consignments.availableShippingOptions",e.PhysicalItemsCategoryNames="cart.lineItems.physicalItems.categoryNames",e.DigitalItemsCategoryNames="cart.lineItems.digitalItems.categoryNames"}(Ei||(Ei={}));const wi=function(){function e(e,t){this._consignmentRequestSender=e,this._checkoutRequestSender=t}return e.prototype.unassignItemsByAddress=function(e,t){var n=this;return function(r){var i=r.getState();if(!i.checkout.getCheckout())throw new Pn(bn.MissingCheckout);var o=n._consignmentHasAddress(e)?e.address:e.shippingAddress,a=i.consignments.getConsignmentByAddress(o);if(!a)throw new Sr("No consignment found for the specified address");var s=n._removeLineItems(e.lineItems,a,i.cart.getCart());return s.length?n.updateConsignment({id:a.id,address:o,lineItems:s},t)(r):n.deleteConsignment(a.id,t)(r)}},e.prototype.assignItemsByAddress=function(e,t){var n=this;return function(r){var i=r.getState(),o=n._consignmentHasAddress(e)?e.address:e.shippingAddress,a=i.consignments.getConsignmentByAddress(o);return n._createOrUpdateConsignment({id:a&&a.id,address:o,lineItems:n._addLineItems(e.lineItems,a,i.cart.getCart())},t)(r)}},e.prototype.selectShippingOption=function(e,t){var n=this;return function(r){return S.Observable.create((function(i){var o=r.getState(),s=o.checkout.getCheckout(),u=o.consignments.getConsignments();if(!s)throw new Pn(bn.MissingCheckout);if(!u||!u.length)throw new Pn(bn.MissingConsignments);var c={id:u[0].id,shippingOptionId:e},d={id:u[0].id};i.next((0,a.createAction)(x.UpdateShippingOptionRequested,void 0,d)),n._consignmentRequestSender.updateConsignment(s.id,c,t).then((function(e){var t=e.body;i.next((0,a.createAction)(x.UpdateShippingOptionSucceeded,t,d)),i.complete()})).catch((function(e){i.error((0,a.createErrorAction)(x.UpdateShippingOptionFailed,e,d))}))}))}},e.prototype.loadShippingOptions=function(e){var t=this;return function(n){return S.Observable.create((function(r){var i=n.getState().checkout.getCheckout();if(!i)throw new Pn(bn.MissingCheckout);r.next((0,a.createAction)(x.LoadShippingOptionsRequested)),t._checkoutRequestSender.loadCheckout(i.id,(0,o.__assign)((0,o.__assign)({},e),{params:{include:[Ei.AvailableShippingOptions]}})).then((function(e){var t=e.body;r.next((0,a.createAction)(x.LoadShippingOptionsSucceeded,t)),r.complete()})).catch((function(e){r.error((0,a.createErrorAction)(x.LoadShippingOptionsFailed,e))}))}))}},e.prototype.updateAddress=function(e,t){var n=this;return function(r){var i=n._getUpdateAddressRequestBody(e,r),o=r.getState().consignments.getConsignments();return o&&o.length&&(i.id=o[0].id),n._createOrUpdateConsignment(i,t)(r)}},e.prototype.createConsignments=function(e,t){var n=this;return function(r){return S.Observable.create((function(i){var o=r.getState().checkout.getCheckout();if(!o||!o.id)throw new Pn(bn.MissingCheckout);i.next((0,a.createAction)(x.CreateConsignmentsRequested)),n._consignmentRequestSender.createConsignments(o.id,e,t).then((function(e){var t=e.body;i.next((0,a.createAction)(x.CreateConsignmentsSucceeded,t)),i.complete()})).catch((function(e){i.error((0,a.createErrorAction)(x.CreateConsignmentsFailed,e))}))}))}},e.prototype.updateConsignment=function(e,t){var n=this;return function(r){return S.Observable.create((function(i){var o=r.getState().checkout.getCheckout();if(!o||!o.id)throw new Pn(bn.MissingCheckout);var s={id:e.id};i.next((0,a.createAction)(x.UpdateConsignmentRequested,void 0,s)),n._consignmentRequestSender.updateConsignment(o.id,e,t).then((function(e){var t=e.body;i.next((0,a.createAction)(x.UpdateConsignmentSucceeded,t,s)),i.complete()})).catch((function(e){i.error((0,a.createErrorAction)(x.UpdateConsignmentFailed,e,s))}))}))}},e.prototype.deleteConsignment=function(e,t){var n=this;return function(r){return S.Observable.create((function(i){var o=r.getState().checkout.getCheckout(),s={id:e};if(!o||!o.id)throw new Pn(bn.MissingCheckout);i.next((0,a.createAction)(x.DeleteConsignmentRequested,void 0,s)),n._consignmentRequestSender.deleteConsignment(o.id,e,t).then((function(e){var t=e.body;i.next((0,a.createAction)(x.DeleteConsignmentSucceeded,t,s)),i.complete()})).catch((function(e){i.error((0,a.createErrorAction)(x.DeleteConsignmentFailed,e,s))}))}))}},e.prototype.updateShippingOption=function(e,t){var n=this;return function(r){return S.Observable.create((function(i){var o=r.getState().checkout.getCheckout();if(!o||!o.id)throw new Pn(bn.MissingCheckout);var s={id:e.id};i.next((0,a.createAction)(x.UpdateShippingOptionRequested,void 0,s)),n._consignmentRequestSender.updateConsignment(o.id,e,t).then((function(e){var t=e.body;i.next((0,a.createAction)(x.UpdateShippingOptionSucceeded,t,s)),i.complete()})).catch((function(e){i.error((0,a.createErrorAction)(x.UpdateShippingOptionFailed,e,s))}))}))}},e.prototype._createOrUpdateConsignment=function(e,t){var n=this;return function(r){var i=r.getState().checkout.getCheckout();if(!i||!i.id)throw new Pn(bn.MissingCheckout);return n._isUpdateConsignmentRequest(e)?n.updateConsignment(e,t)(r):n.createConsignments([e],t)(r)}},e.prototype._getUpdateAddressRequestBody=function(e,t){var n=t.getState().cart.getCart();if(!n)throw new Pn(bn.MissingCart);var r=n.lineItems,i=r.physicalItems,a=r.customItems,s=void 0===a?[]:a;return{address:e,lineItems:(0,o.__spreadArrays)(i,s).map((function(e){return{itemId:e.id,quantity:e.quantity}}))}},e.prototype._removeLineItems=function(e,t,n){if(!n)throw new Pn(bn.MissingCart);return this._hydrateLineItems(t.lineItemIds,n).map((function(t){var n=(0,m.find)(e,(function(e){return e.itemId===t.itemId}));return(0,o.__assign)((0,o.__assign)({},t),{quantity:n?t.quantity-n.quantity:t.quantity})})).filter((function(e){return e.quantity>0}))},e.prototype._addLineItems=function(e,t,n){if(!t)return e;if(!n)throw new Pn(bn.MissingCart);return e.concat(this._hydrateLineItems(t.lineItemIds,n)).filter((function(e){return e.quantity>0}))},e.prototype._hydrateLineItems=function(e,t){return e.map((function(e){var n=(0,m.find)(t.lineItems.physicalItems,(function(t){return t.id===e}));return{itemId:e,quantity:n?n.quantity:0}}))},e.prototype._isUpdateConsignmentRequest=function(e){return!!e.id},e.prototype._consignmentHasAddress=function(e){return"object"==typeof e&&"address"in e},e}();var Ai=["consignments.availableShippingOptions","cart.lineItems.physicalItems.options","cart.lineItems.digitalItems.options","customer","promotions.banners"];const bi=function(){function e(e){this._requestSender=e}return e.prototype.createConsignments=function(e,t,n){var r=void 0===n?{}:n,i=r.timeout,a=r.params,s=(void 0===a?{}:a).include,u="/api/storefront/checkouts/"+e+"/consignments",c=(0,o.__assign)({Accept:Vn.JsonV1},jn);return this._requestSender.post(u,{body:t,params:{include:rr(Ai,s)},headers:c,timeout:i})},e.prototype.updateConsignment=function(e,t,n){var r=void 0===n?{}:n,i=r.timeout,a=r.params,s=(void 0===a?{}:a).include,u=t.id,c=(0,o.__rest)(t,["id"]),d="/api/storefront/checkouts/"+e+"/consignments/"+u,p=(0,o.__assign)({Accept:Vn.JsonV1},jn);return this._requestSender.put(d,{body:c,params:{include:rr(Ai,s)},headers:p,timeout:i})},e.prototype.deleteConsignment=function(e,t,n){var r=(void 0===n?{}:n).timeout,i="/api/storefront/checkouts/"+e+"/consignments/"+t,a=(0,o.__assign)({Accept:Vn.JsonV1},jn),s=nr(Ai);return this._requestSender.delete(i,{params:{include:s},headers:a,timeout:r})},e}(),Pi=function(){function e(e,t){this._googleRecaptcha=e,this._requestSender=t}return e.prototype.initialize=function(e){var t=this;return function(n){return(0,S.concat)((0,S.of)((0,a.createAction)(mn.InitializeRequested,void 0)),(0,S.defer)((function(){return(0,o.__awaiter)(t,void 0,void 0,(function(){var t,r,i,s,u;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:return t=e?e.containerId:"spamProtectionContainer",e||document.getElementById(t)||((r=document.createElement("div")).setAttribute("id",t),document.body.appendChild(r)),i=n.getState(),s=i.config.getStoreConfigOrThrow(),u=s.checkoutSettings.googleRecaptchaSitekey,[4,this._googleRecaptcha.load(t,u)];case 1:return o.sent(),[2,(0,a.createAction)(mn.InitializeSucceeded)]}}))}))}))).pipe((0,I.catchError)((function(e){return Qn(mn.InitializeFailed,e)})))}},e.prototype.verifyCheckoutSpamProtection=function(){var e=this;return function(t){return(0,S.defer)((function(){var n=t.getState().checkout.getCheckout();if(!n)throw new Pn(bn.MissingCheckout);return(0,S.concat)((0,S.of)((0,a.createAction)(mn.VerifyCheckoutRequested)),(0,S.from)(e.execute()(t)).pipe((0,I.switchMap)((function(t){return lr(t)&&t.payload?(0,S.from)(e._requestSender.validate(n.id,t.payload.token)).pipe((0,I.switchMap)((function(e){var n=e.body;return(0,S.concat)((0,S.of)(t),(0,S.of)((0,a.createAction)(mn.VerifyCheckoutSucceeded,n)))}))):(0,S.of)(t)})))).pipe((0,I.catchError)((function(e){return Qn(mn.VerifyCheckoutFailed,e)})))}))}},e.prototype.execute=function(){var e=this;return function(t){return(0,S.concat)((0,S.of)((0,a.createAction)(mn.ExecuteRequested)),e.initialize()(t),e._googleRecaptcha.execute().pipe((0,I.take)(1)).pipe((0,I.switchMap)((function(t){var n=t.error,r=t.token;return(0,o.__awaiter)(e,void 0,void 0,(function(){return(0,o.__generator)(this,(function(e){if(n instanceof Or)throw n;if(n||!r)throw new Nr;return[2,(0,a.createAction)(mn.ExecuteSucceeded,{token:r})]}))}))})))).pipe((0,I.catchError)((function(e){return Qn(mn.ExecuteFailed,e)})))}},e}(),Oi=function(){function e(e){this._requestSender=e}return e.prototype.validate=function(e,t,n){var r=(void 0===n?{}:n).timeout,i="/api/storefront/checkouts/"+e+"/spam-protection",a=(0,o.__assign)({Accept:Vn.JsonV1},jn);return this._requestSender.post(i,{body:{token:t},headers:a,timeout:r})},e}(),Ti=function(){function e(e){this._storeCreditRequestSender=e}return e.prototype.applyStoreCredit=function(e,t){var n=this;return function(r){return(0,S.concat)((0,S.of)((0,a.createAction)(on.ApplyStoreCreditRequested)),(0,S.defer)((function(){return(0,o.__awaiter)(n,void 0,void 0,(function(){var n,i,s;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(n=r.getState(),!(i=n.checkout.getCheckout()))throw new Pn(bn.MissingCheckout);return[4,e?this._storeCreditRequestSender.applyStoreCredit(i.id,t):this._storeCreditRequestSender.removeStoreCredit(i.id,t)];case 1:return s=o.sent().body,[2,(0,a.createAction)(on.ApplyStoreCreditSucceeded,s)]}}))}))}))).pipe((0,I.catchError)((function(e){return Qn(on.ApplyStoreCreditFailed,e)})))}},e}(),Ri=function(){function e(e){this._requestSender=e}return e.prototype.applyStoreCredit=function(e,t){var n=(void 0===t?{}:t).timeout,r="/api/storefront/checkouts/"+e+"/store-credit",i=(0,o.__assign)({Accept:Vn.JsonV1},jn);return this._requestSender.post(r,{headers:i,timeout:n,params:{include:nr(ir)}})},e.prototype.removeStoreCredit=function(e,t){var n=(void 0===t?{}:t).timeout,r="/api/storefront/checkouts/"+e+"/store-credit",i=(0,o.__assign)({Accept:Vn.JsonV1},jn);return this._requestSender.delete(r,{headers:i,timeout:n,params:{include:nr(ir)}})},e}(),Mi=function(e){function t(t){var n=e.call(this,t)||this;return n.name="UpdateSubscriptionsError",n.type="update_subscriptions",n}return(0,o.__extends)(t,e),t}(h),Di=function(){function e(e){this._subscriptionsRequestSender=e}return e.prototype.updateSubscriptions=function(e,t){var n=this;return(0,S.concat)((0,S.of)((0,a.createAction)(A.UpdateSubscriptionsRequested)),(0,S.defer)((function(){return(0,o.__awaiter)(n,void 0,void 0,(function(){var n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._subscriptionsRequestSender.updateSubscriptions(e,t)];case 1:return n=r.sent().body,[2,(0,a.createAction)(A.UpdateSubscriptionsSucceeded,n)]}}))}))}))).pipe((0,I.catchError)((function(e){return Qn(A.UpdateSubscriptionsFailed,new Mi(e))})))},e}(),ki=function(){function e(e){this._requestSender=e}return e.prototype.updateSubscriptions=function(e,t){var n=(void 0===t?{}:t).timeout,r=(0,o.__assign)({Accept:Vn.JsonV1},jn);return this._requestSender.post("/api/storefront/subscriptions",{body:e,headers:r,timeout:n})},e}();var Ni=(0,m.memoize)((function(e){return Array.isArray(e)?e.map((function(e){return Li(e)})):U(e)?Object.keys(e).reduce((function(t,n){var r;return(0,o.__assign)((0,o.__assign)({},t),((r={})[n]=Li(e[n]),r))}),{}):e}));Ni.cache=new WeakMap;var Li=function(e){return"object"==typeof e&&null!==e?Ni(e):e};function zi(e){return function(){for(var t=[],n=0;n55?55:e<25?25:e}function Qo(e){var t=e.billingAddress,n=e.email,r=e.firstName,i=e.lastName,o=e.phone,a=e.shippingAddress,s=t||a;return{email:n,first_name:r,last_name:i,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 Zo(e){var t=e.email,n=e.phone,r=e.shippingAddress,i=((null==r?void 0:r.recipientName)||"").split(" ");return{email:t,first_name:i[0]||"",last_name:i[1]||"",phone_number:n,address_line_1:null==r?void 0:r.line1,address_line_2:null==r?void 0:r.line2,city:null==r?void 0:r.city,state:null==r?void 0:r.state,country_code:null==r?void 0:r.countryCode,postal_code:null==r?void 0:r.postalCode}}const Jo=function(){function e(e,t,n,r,i,o){this._store=e,this._checkoutActionCreator=t,this._cartRequestSender=n,this._braintreeSDKCreator=r,this._formPoster=i,this._window=o}return e.prototype.initialize=function(e){var t,n;return(0,o.__awaiter)(this,void 0,void 0,(function(){var r,i,a,s,u,c,d,p,l,h,f,m,g=this;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(r=e.braintreepaypal,i=e.containerId,a=e.methodId,u=(s=r||{}).messagingContainerId,c=s.onError,!a)throw new Sr('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new Sr('Unable to initialize payment because "options.containerId" argument is not provided.');if(!r)throw new Sr('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');if(!r.buyNowInitializeOptions)return[3,1];if(d=this._store.getState(),p=d.paymentMethods.getPaymentMethodOrThrow(a),!r.currencyCode)throw new Sr('Unable to initialize payment because "options.braintreepaypal.currencyCode" argument is not provided.');return l=r.currencyCode,[3,3];case 1:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 2:d=o.sent(),p=d.paymentMethods.getPaymentMethodOrThrow(a),l=d.cart.getCartOrThrow().currency.code,o.label=3;case 3:if(!p.clientToken)throw new Pn(bn.MissingPaymentMethod);return h={currency:l,intent:null===(t=p.initializationData)||void 0===t?void 0:t.intent,isCreditEnabled:null===(n=p.initializationData)||void 0===n?void 0:n.isCreditEnabled},f=function(e){g._renderPayPalComponents(e,r,i,a,Boolean(p.config.testMode))},m=function(e){return g._handleError(e,i,u,c)},this._braintreeSDKCreator.initialize(p.clientToken),[4,this._braintreeSDKCreator.getPaypalCheckout(h,f,m)];case 4:return o.sent(),[2]}}))}))},e.prototype.deinitialize=function(){return this._braintreeSDKCreator.teardown(),Promise.resolve()},e.prototype._renderPayPalComponents=function(e,t,n,r,i){var o=t.messagingContainerId;this._renderPayPalMessages(o),this._renderPayPalButton(e,t,n,r,i)},e.prototype._renderPayPalButton=function(e,t,n,r,i){var o=this,a=t.style,s=t.shouldProcessPayment,u=t.onAuthorizeError,c=this._window.paypal,d=null==c?void 0:c.FUNDING.PAYPAL;if(c&&d){var p=a?Wo(a):{},l=c.Buttons({env:i?"sandbox":"production",commit:!1,fundingSource:d,style:p,createOrder:function(){return o._setupPayment(e,t,r)},onApprove:function(t){return o._tokenizePayment(t,e,r,s,u)}});l.isEligible()&&l.render("#"+n)}else this._removeElement(n)},e.prototype._renderPayPalMessages=function(e){var t=e&&Boolean(document.getElementById(e)),n=this._window.paypal;if(n&&t){var r=this._store.getState().cart.getCartOrThrow();n.Messages({amount:r.cartAmount,placement:"cart"}).render("#"+e)}else this._removeElement(e)},e.prototype._setupPayment=function(e,t,n){var r,i;return(0,o.__awaiter)(this,void 0,void 0,(function(){var a,s,u,c,d,p,l,h,f,m,g,y;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:a=t.buyNowInitializeOptions,s=t.shippingAddress,u=t.onPaymentError,o.label=1;case 1:return o.trys.push([1,7,,8]),d=this,[4,this._createBuyNowCart({buyNowInitializeOptions:a})];case 2:return d._buyNowCart=o.sent(),this._buyNowCart?(c=this._store.getState(),[3,5]):[3,3];case 3:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 4:c=o.sent(),o.label=5;case 5:return p=c.customer.getCustomer(),l=c.paymentMethods.getPaymentMethodOrThrow(n),h=this._buyNowCart?this._buyNowCart.cartAmount:c.checkout.getCheckoutOrThrow().outstandingBalance,f=null!==(r=t.currencyCode)&&void 0!==r?r:c.config.getStoreConfigOrThrow().currency.code,m=s||(null==p?void 0:p.addresses[0]),g=m?jo(m):void 0,[4,e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:g,amount:h,currency:f,offerCredit:!1,intent:null===(i=l.initializationData)||void 0===i?void 0:i.intent})];case 6:return[2,o.sent()];case 7:throw y=o.sent(),u&&u(y),y;case 8:return[2]}}))}))},e.prototype._createBuyNowCart=function(e){var t=e.buyNowInitializeOptions;return(0,o.__awaiter)(this,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if("function"!=typeof(null==t?void 0:t.getBuyNowCartRequestBody))return[3,4];if(!(e=t.getBuyNowCartRequestBody()))throw new Pn(bn.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._cartRequestSender.createBuyNowCart(e)];case 2:return[2,n.sent().body];case 3:throw n.sent(),new Go;case 4:return[2]}}))}))},e.prototype._tokenizePayment=function(e,t,n,r,i){var a;return(0,o.__awaiter)(this,void 0,void 0,(function(){var s,u,c,d,p,l;return(0,o.__generator)(this,(function(h){switch(h.label){case 0:return h.trys.push([0,3,,4]),[4,this._braintreeSDKCreator.getDataCollector({paypal:!0})];case 1:return s=h.sent().deviceData,[4,t.tokenizePayment(e)];case 2:return u=h.sent(),c=u.details,d=u.nonce,p=null===(a=this._buyNowCart)||void 0===a?void 0:a.id,this._formPoster.postForm("/checkout.php",(0,o.__assign)({payment_type:"paypal",provider:n,action:r?"process_payment":"set_external_checkout",nonce:d,device_data:s,billing_address:JSON.stringify(Qo(c)),shipping_address:JSON.stringify(Zo(c))},p&&{cart_id:p})),[2,u];case 3:throw l=h.sent(),i&&i(l),l;case 4:return[2]}}))}))},e.prototype._handleError=function(e,t,n,r){this._removeElement(t),this._removeElement(n),r&&r(e)},e.prototype._removeElement=function(e){var t=e&&document.getElementById(e);t&&t.remove()},e}();var Xo,$o,ea,ta,na;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(Xo||(Xo={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}($o||($o={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black"}(ea||(ea={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(ta||(ta={})),function(e){e.PILL="pill",e.RECT="rect"}(na||(na={}));const ra=function(){function e(e,t,n,r,i,o){this._store=e,this._checkoutActionCreator=t,this._cartRequestSender=n,this._braintreeSDKCreator=r,this._formPoster=i,this._window=o}return e.prototype.initialize=function(e){var t,n;return(0,o.__awaiter)(this,void 0,void 0,(function(){var r,i,a,s,u,c,d,p,l,h=this;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(r=e.braintreepaypalcredit,i=e.containerId,!(a=e.methodId))throw new Sr('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new Sr('Unable to initialize payment because "options.containerId" argument is not provided.');if(!r)throw new Sr('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');if(!r.buyNowInitializeOptions)return[3,1];if(s=this._store.getState(),u=s.paymentMethods.getPaymentMethodOrThrow(a),!r.currencyCode)throw new Sr('Unable to initialize payment because "options.braintreepaypalcredit.currencyCode" argument is not provided.');return c=r.currencyCode,[3,3];case 1:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 2:s=o.sent(),u=s.paymentMethods.getPaymentMethodOrThrow(a),c=s.cart.getCartOrThrow().currency.code,o.label=3;case 3:if(!u.clientToken)throw new Pn(bn.MissingPaymentMethod);return d={currency:c,intent:null===(t=u.initializationData)||void 0===t?void 0:t.intent,isCreditEnabled:null===(n=u.initializationData)||void 0===n?void 0:n.isCreditEnabled},p=function(e){return h._renderPayPalButton(e,r,i,a,Boolean(u.config.testMode))},l=function(e){return h._handleError(e,i,r.onError)},this._braintreeSDKCreator.initialize(u.clientToken),[4,this._braintreeSDKCreator.getPaypalCheckout(d,p,l)];case 4:return o.sent(),[2]}}))}))},e.prototype.deinitialize=function(){return this._braintreeSDKCreator.teardown(),Promise.resolve()},e.prototype._renderPayPalButton=function(e,t,n,r,i){var a=this,s=t.style,u=t.shouldProcessPayment,c=t.onAuthorizeError,d=this._window.paypal,p=!1;if(d){var l=[d.FUNDING.PAYLATER,d.FUNDING.CREDIT],h=s?Wo(s):{};l.forEach((function(s){var l=s===d.FUNDING.CREDIT?(0,o.__assign)({label:ta.CREDIT},h):h;if(!p){var f=d.Buttons({env:i?"sandbox":"production",commit:!1,fundingSource:s,style:l,createOrder:function(){return a._setupPayment(e,t,r)},onApprove:function(t){return a._tokenizePayment(t,e,r,u,c)}});f.isEligible()&&(f.render("#"+n),p=!0)}}))}d&&p||this._removeElement(n)},e.prototype._setupPayment=function(e,t,n){var r,i;return(0,o.__awaiter)(this,void 0,void 0,(function(){var a,s,u,c,d,p,l,h,f,m,g,y;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:a=t.onPaymentError,s=t.shippingAddress,u=t.buyNowInitializeOptions,o.label=1;case 1:return o.trys.push([1,7,,8]),d=this,[4,this._createBuyNowCart({buyNowInitializeOptions:u})];case 2:return d._buyNowCart=o.sent(),this._buyNowCart?(c=this._store.getState(),[3,5]):[3,3];case 3:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 4:c=o.sent(),o.label=5;case 5:return p=c.customer.getCustomer(),l=c.paymentMethods.getPaymentMethodOrThrow(n),h=this._buyNowCart?this._buyNowCart.cartAmount:c.checkout.getCheckoutOrThrow().outstandingBalance,f=null!==(r=t.currencyCode)&&void 0!==r?r:c.config.getStoreConfigOrThrow().currency.code,m=s||(null==p?void 0:p.addresses[0]),g=m?jo(m):void 0,[4,e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:g,amount:h,currency:f,offerCredit:!0,intent:null===(i=l.initializationData)||void 0===i?void 0:i.intent})];case 6:return[2,o.sent()];case 7:throw y=o.sent(),a&&a(y),y;case 8:return[2]}}))}))},e.prototype._createBuyNowCart=function(e){var t=e.buyNowInitializeOptions;return(0,o.__awaiter)(this,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if("function"!=typeof(null==t?void 0:t.getBuyNowCartRequestBody))return[3,4];if(!(e=t.getBuyNowCartRequestBody()))throw new Pn(bn.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._cartRequestSender.createBuyNowCart(e)];case 2:return[2,n.sent().body];case 3:throw n.sent(),new Go;case 4:return[2]}}))}))},e.prototype._tokenizePayment=function(e,t,n,r,i){var a;return(0,o.__awaiter)(this,void 0,void 0,(function(){var s,u,c,d,p,l;return(0,o.__generator)(this,(function(h){switch(h.label){case 0:return h.trys.push([0,3,,4]),[4,this._braintreeSDKCreator.getDataCollector({paypal:!0})];case 1:return s=h.sent().deviceData,[4,t.tokenizePayment(e)];case 2:return u=h.sent(),c=u.details,d=u.nonce,p=null===(a=this._buyNowCart)||void 0===a?void 0:a.id,this._formPoster.postForm("/checkout.php",(0,o.__assign)({payment_type:"paypal",provider:n,action:r?"process_payment":"set_external_checkout",nonce:d,device_data:s,billing_address:JSON.stringify(Qo(c)),shipping_address:JSON.stringify(Zo(c))},p&&{cart_id:p})),[2,u];case 3:throw l=h.sent(),i&&i(l),l;case 4:return[2]}}))}))},e.prototype._handleError=function(e,t,n){this._removeElement(t),n&&n(e)},e.prototype._removeElement=function(e){var t=e&&document.getElementById(e);t&&t.remove()},e}();var ia={backgroundColor:"#3D95CE",backgroundPosition:"50% 50%",backgroundSize:"80px auto",backgroundImage:'url("/app/assets/img/payment-providers/venmo-logo-white.svg")',backgroundRepeat:"no-repeat",borderRadius:"4px",cursor:"pointer",transition:"0.2s ease",minHeight:"40px",minWidth:"150px",height:"100%",width:"100%"};const oa=function(){function e(e,t,n,r,i){this._store=e,this._paymentMethodActionCreator=t,this._cartRequestSender=n,this._braintreeSDKCreator=r,this._formPoster=i,this._onError=m.noop}return e.prototype.initialize=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,a,s=this;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(t=e.braintreevenmo,n=e.containerId,!(r=e.methodId))throw new Sr('Unable to initialize payment because "options.methodId" argument is not provided.');return[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(r))];case 1:if(i=o.sent(),!(a=i.paymentMethods.getPaymentMethodOrThrow(r)).clientToken)throw new Pn(bn.MissingPaymentMethod);if(!n)throw new Sr('Unable to initialize payment because "options.containerId" argument is not provided.');return this._onError=(null==t?void 0:t.onError)||this._handleError,this._braintreeSDKCreator.initialize(a.clientToken),[4,this._braintreeSDKCreator.getVenmoCheckout((function(e){return s._handleInitializationVenmoSuccess(e,n,null==t?void 0:t.buyNowInitializeOptions)}),(function(e){return s._handleInitializationVenmoError(e,n)}))];case 2:return o.sent(),[2]}}))}))},e.prototype.deinitialize=function(){return this._braintreeSDKCreator.teardown(),Promise.resolve()},e.prototype._handleError=function(e){throw new Error(e.message)},e.prototype._handleInitializationVenmoSuccess=function(e,t,n){return this._renderVenmoButton(e,t,n)},e.prototype._handleInitializationVenmoError=function(e,t){return this._removeVenmoContainer(t),this._onError(e)},e.prototype._removeVenmoContainer=function(e){var t=document.getElementById(e);t&&t.remove()},e.prototype._renderVenmoButton=function(e,t,n){var r=this,i=document.getElementById(t);if(!i)throw new Sr("Unable to create wallet button without valid container ID.");i.setAttribute("aria-label","Venmo"),Object.assign(i.style,ia),i.addEventListener("click",(function(){return(0,o.__awaiter)(r,void 0,void 0,(function(){var t,r=this;return(0,o.__generator)(this,(function(a){switch(a.label){case 0:return i.setAttribute("disabled","true"),[4,this._createBuyNowCart(n)];case 1:return t=a.sent(),e.tokenize&&e.tokenize((function(e,n){return(0,o.__awaiter)(r,void 0,void 0,(function(){return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return i.removeAttribute("disabled"),e?[2,this._onError(e)]:[4,this._handlePostForm(n,null==t?void 0:t.id)];case 1:return r.sent(),[2]}}))}))})),[2]}}))}))})),i.addEventListener("mouseenter",(function(){i.style.backgroundColor="#0a7fc2"})),i.addEventListener("mouseleave",(function(){i.style.backgroundColor=ia.backgroundColor}))},e.prototype._createBuyNowCart=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if("function"!=typeof(null==e?void 0:e.getBuyNowCartRequestBody))return[3,4];if(!(t=e.getBuyNowCartRequestBody()))throw new Pn(bn.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._cartRequestSender.createBuyNowCart(t)];case 2:return[2,n.sent().body];case 3:throw n.sent(),new Go;case 4:return[2]}}))}))},e.prototype._handlePostForm=function(e,t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r,i;return(0,o.__generator)(this,(function(a){switch(a.label){case 0:return[4,this._braintreeSDKCreator.getDataCollector()];case 1:return n=a.sent().deviceData,r=e.nonce,i=e.details,this._formPoster.postForm("/checkout.php",(0,o.__assign)({nonce:r,provider:pi.BRAINTREE_VENMO,payment_type:"paypal",device_data:n,action:"set_external_checkout",billing_address:JSON.stringify(Qo(i)),shipping_address:JSON.stringify(Zo(i))},t&&{cart_id:t})),[2]}}))}))},e}();const aa=function(e){function t(t){var n=e.call(this,t||"Invalid arguments have been provided.")||this;return n.name="InvalidArgumentError",n.type="invalid_argument",n}return(0,o.__extends)(t,e),t}(s);var sa;!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"}(sa||(sa={}));const ua=function(e){function t(t){var n=e.call(this,function(e){switch(e){case sa.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case sa.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case sa.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case sa.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."}}(t))||this;return n.subtype=t,n.name="NotInitializedError",n.type="not_initialized",n}return(0,o.__extends)(t,e),t}(s);var ca;!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"}(ca||(ca={}));const da=function(e){function t(t){var n=e.call(this,function(e){switch(e){case ca.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case ca.MissingCart:return"Unable to proceed because cart data is unavailable.";case ca.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case ca.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case ca.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case ca.MissingCheckoutConfig:case ca.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case ca.MissingOrder:return"Unable to proceed because order data is unavailable.";case ca.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case ca.MissingPayment:return"Unable to proceed because payment data is unavailable.";case ca.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case ca.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case ca.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(t))||this;return n.subtype=t,n.name="MissingDataError",n.type="missing_data",n}return(0,o.__extends)(t,e),t}(s),pa=function(){function e(e,t,n,r,i){this._store=e,this._formPoster=t,this._checkoutActionCreator=n,this._googlePayPaymentProcessor=r,this._cartRequestSender=i}return e.prototype.initialize=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,a,s,u,c,d;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(t=e.containerId,n=e.methodId,r=e.currencyCode,i=this._getGooglePayOptions(e),a=i.buyNowInitializeOptions,!t||!n)throw new aa('Unable to proceed because "containerId" argument is not provided.');if(s=this._store.getState(),u=s.paymentMethods.getPaymentMethod(n),c=((null==u?void 0:u.config)||{}).testMode,this._methodId=n,this._isBuyNowFlow=!!a,!this._isBuyNowFlow)return[3,2];if(!r)throw new aa('Unable to initialize payment because "options.currencyCode" argument is not provided.');return d=i.buyNowInitializeOptions,this._googlePayPaymentProcessor.updateBuyNowFlowFlag(this._isBuyNowFlow),[4,this._googlePayPaymentProcessor.initialize(this._getMethodId(),this._getGooglePayClientOptions(r,c,d))];case 1:return o.sent(),[3,5];case 2:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 3:return o.sent(),[4,this._googlePayPaymentProcessor.initialize(this._getMethodId())];case 4:o.sent(),o.label=5;case 5:return this._walletButton=this._createSignInButton(t,i,r),[2]}}))}))},e.prototype.deinitialize=function(){return this._walletButton&&this._walletButton.parentNode&&(this._walletButton.parentNode.removeChild(this._walletButton),this._walletButton=void 0),this._googlePayPaymentProcessor.deinitialize()},e.prototype._getGooglePayClientOptions=function(e,t,n){var r=this;return{environment:t?"TEST":"PRODUCTION",paymentDataCallbacks:{onPaymentDataChanged:function(t){var i=t.callbackTrigger;return(0,o.__awaiter)(r,void 0,void 0,(function(){var t,r,a,s,u;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(i!==go.INITIALIZE)return[2];o.label=1;case 1:return o.trys.push([1,5,,6]),t=this,[4,this._createBuyNowCart(n)];case 2:return t._buyNowCart=o.sent(),this._buyNowCart?(r=this._buyNowCart,a=r.id,s=r.cartAmount,[4,this._store.dispatch(this._checkoutActionCreator.loadCheckout(a))]):[3,4];case 3:return o.sent(),[2,{newTransactionInfo:{currencyCode:e,totalPrice:String(s),totalPriceStatus:yo.FINAL}}];case 4:return[3,6];case 5:throw u=o.sent(),new Go(u);case 6:return[2]}}))}))}}}},e.prototype._createSignInButton=function(e,t,n){var r=this,i=document.getElementById(e),o=t.buttonType,a=t.buttonColor;if(!i)throw new aa("Unable to create sign-in button without valid container ID.");var s=this._googlePayPaymentProcessor.createButton((function(e){return r._handleWalletButtonClick(e,n)}),o,a);return i.appendChild(s),s},e.prototype._getMethodId=function(){if(!this._methodId)throw new ua(sa.PaymentNotInitialized);return this._methodId},e.prototype._getGooglePayOptions=function(e){if(e.methodId===pi.GOOGLEPAY_ADYENV2&&e.googlepayadyenv2)return e.googlepayadyenv2;if(e.methodId===pi.GOOGLEPAY_ADYENV3&&e.googlepayadyenv3)return e.googlepayadyenv3;if(e.methodId===pi.GOOGLEPAY_AUTHORIZENET&&e.googlepayauthorizenet)return e.googlepayauthorizenet;if(e.methodId===pi.GOOGLEPAY_BNZ&&e.googlepaybnz)return e.googlepaybnz;if(e.methodId===pi.GOOGLEPAY_BRAINTREE&&e.googlepaybraintree)return e.googlepaybraintree;if(e.methodId===pi.GOOGLEPAY_CHECKOUTCOM&&e.googlepaycheckoutcom)return e.googlepaycheckoutcom;if(e.methodId===pi.GOOGLEPAY_CYBERSOURCEV2&&e.googlepaycybersourcev2)return e.googlepaycybersourcev2;if(e.methodId===pi.GOOGLEPAY_ORBITAL&&e.googlepayorbital)return e.googlepayorbital;if(e.methodId===pi.GOOGLEPAY_STRIPE&&e.googlepaystripe)return e.googlepaystripe;if(e.methodId===pi.GOOGLEPAY_STRIPEUPE&&e.googlepaystripeupe)return e.googlepaystripeupe;if(e.methodId===pi.GOOGLEPAY_WORLDPAYACCESS&&e.googlepayworldpayaccess)return e.googlepayworldpayaccess;throw new aa},e.prototype._createBuyNowCart=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if("function"!=typeof(null==e?void 0:e.getBuyNowCartRequestBody))return[3,4];if(!(t=e.getBuyNowCartRequestBody()))throw new da(ca.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._cartRequestSender.createBuyNowCart(t)];case 2:return[2,n.sent().body];case 3:throw n.sent(),new Go;case 4:return[2]}}))}))},e.prototype._handleWalletButtonClick=function(e,t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:e.preventDefault(),i.label=1;case 1:return i.trys.push([1,7,,8]),this._isBuyNowFlow&&t&&this._googlePayPaymentProcessor.updatePaymentDataRequest({transactionInfo:{currencyCode:t,totalPrice:"0",totalPriceStatus:yo.ESTIMATED},callbackIntents:[_o.OFFER]}),[4,this._googlePayPaymentProcessor.displayWallet()];case 2:return n=i.sent(),[4,this._googlePayPaymentProcessor.handleSuccess(n)];case 3:return i.sent(),Xi(this._store.getState().cart.getCartOrThrow())>0&&n.shippingAddress?[4,this._googlePayPaymentProcessor.updateShippingAddress(n.shippingAddress)]:[3,5];case 4:i.sent(),i.label=5;case 5:return[4,this._onPaymentSelectComplete()];case 6:return i.sent(),[3,8];case 7:if((r=i.sent())&&"CANCELED"!==r.message)throw r;return[3,8];case 8:return[2]}}))}))},e.prototype._onPaymentSelectComplete=function(){var e,t=null===(e=this._buyNowCart)||void 0===e?void 0:e.id;this._formPoster.postForm("/checkout.php",(0,o.__assign)({headers:(0,o.__assign)({Accept:"text/html","Content-Type":"application/x-www-form-urlencoded"},jn)},t&&{action:"set_external_checkout",provider:this._methodId,cart_id:t}))},(0,o.__decorate)([Ar],e.prototype,"_handleWalletButtonClick",null),e}();var la={es:["es_es","es_mx","es_pe","es_co","es_ar","es_cl"],en:["en_us","en_gb","en_ca","en_es","en_fr","en_ie","en_sg","en_au","en_nz","en_my","en_hk","en_th","en_ae","en_sa","en_qa","en_kw","en_za"],pt:["pt_br"],zu:["zu_za"],ar:["ar_sa","ar_ae","ar_qa","ar_kw"],zh:["zh_sg","zh_hk"],ms:["ms_my"],uk:["uk_ua"],sv:["sv_se"],hr:["hr_hr"],pl:["pl_pl"],nl:["nl_be"],it:["it_it"],de:["de_de"],fr:["fr_fr","fr_ca"]};function ha(e){var t=e.replace("-","_").toLowerCase().split("_"),n=t[0],r=n+"_"+t[1],i=la[n];return i?i.indexOf(r)>-1?r:i[0]:"en_us"}const fa=function(){function e(e,t,n,r){this._store=e,this._checkoutActionCreator=t,this._masterpassScriptLoader=n,this._locale=r}return e.prototype.initialize=function(e){var t=this,n=e.containerId,r=e.methodId;if(!n||!r)throw new Sr('Unable to proceed because "containerId" argument is not provided.');return this._methodId=r,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()).then((function(e){var n=e.paymentMethods.getPaymentMethod(r);if(!n||!n.initializationData.checkoutId)throw new Pn(bn.MissingPaymentMethod);var i={useMasterpassSrc:n.initializationData.isMasterpassSrcEnabled,language:ha(t._locale),testMode:n.config.testMode,checkoutId:n.initializationData.checkoutId};return t._masterpassScriptLoader.load(i)})).then((function(e){t._masterpassClient=e,t._signInButton=t._createSignInButton(n)}))},e.prototype.deinitialize=function(){return this._signInButton&&this._signInButton.parentNode&&(this._signInButton.removeEventListener("click",this._handleWalletButtonClick),this._signInButton.parentNode.removeChild(this._signInButton),this._signInButton=void 0),Promise.resolve()},e.prototype._createSignInButton=function(e){var t=document.getElementById(e),n=this._store.getState(),r=this._methodId?n.paymentMethods.getPaymentMethod(this._methodId):null,i=n.config.getStoreConfig();if(!t)throw new Error("Need a container to place the button");if(!r)throw new Pn(bn.MissingPaymentMethod);if(!i)throw new Sr("Unable to retrieve store configuration");var o=document.createElement("input");if(o.type="image",r.initializationData.isMasterpassSrcEnabled){var a=r.config.testMode?"sandbox.":"",s=r.initializationData.checkoutId,u=["locale="+ha(this._locale),"paymentmethod=master,visa,amex,discover","checkoutid="+s];o.src=["https://"+a+"src.mastercard.com/assets/img/btn/src_chk_btn_126x030px.svg",u.join("&")].join("?")}else o.src="https://static.masterpass.com/dyn/img/btn/global/mp_chk_btn_160x037px.svg";return t.appendChild(o),o.addEventListener("click",this._handleWalletButtonClick),o},e.prototype._createMasterpassPayload=function(){var e=this._store.getState(),t=e.checkout.getCheckout(),n=this._methodId?e.paymentMethods.getPaymentMethod(this._methodId):null;if(!t)throw new Pn(bn.MissingCheckout);if(!n)throw new Pn(bn.MissingPaymentMethod);return{checkoutId:n.initializationData.checkoutId,allowedCardTypes:n.initializationData.allowedCardTypes,amount:t.cart.cartAmount.toString(),currency:t.cart.currency.code,cartId:t.cart.id,callbackUrl:("cart",window.location.origin+"/checkout.php?action=set_external_checkout&provider=masterpass&gateway=stripe&origin=cart")}},e.prototype._handleWalletButtonClick=function(){if(!this._masterpassClient)throw new kr(Dr.CheckoutButtonNotInitialized);this._masterpassClient.checkout(this._createMasterpassPayload())},(0,o.__decorate)([Ar],e.prototype,"_handleWalletButtonClick",null),e}(),ma=function(){function e(e,t,n,r,i){void 0===i&&(i=""),this._store=e,this._checkoutActionCreator=t,this._paypalScriptLoader=n,this._formPoster=r,this._host=i}return e.prototype.initialize=function(e){var t=this,n=e.paypal,r=this._store.getState(),i=this._paymentMethod=r.paymentMethods.getPaymentMethod(e.methodId);if(!n)throw new Sr;if(!i)throw new Pn(bn.MissingPaymentMethod);return this._paypalScriptLoader.loadPaypal(i.config.merchantId).then((function(r){var a,s,u;if(!i||!i.config.merchantId)throw new Pn(bn.MissingPaymentMethod);var c=i.config.merchantId,d=i.config.testMode?"sandbox":"production",p=((a={})[d]=n.clientId,a),l=r.FUNDING.CREDIT||"credit",h=n.allowCredit?[l]:[],f=n.allowCredit?[]:[l];return r.Button.render({env:d,client:p,commit:n.shouldProcessPayment,funding:{allowed:h,disallowed:f},style:(0,o.__assign)((0,o.__assign)({shape:na.RECT},(0,m.pick)(n.style,"layout","color","label","shape","tagline","fundingicons")),{size:"paypalexpress"===i.id&&"small"===(null===(s=n.style)||void 0===s?void 0:s.size)?$o.RESPONSIVE:null===(u=n.style)||void 0===u?void 0:u.size}),payment:function(e,r){return t._setupPayment(c,r,n.onPaymentError)},onAuthorize:function(e,r){return t._tokenizePayment(e,r,n.shouldProcessPayment,n.onAuthorizeError)}},e.containerId)}))},e.prototype.deinitialize=function(){return this._paymentMethod=void 0,Promise.resolve()},e.prototype._setupPayment=function(e,t,n){var r=this;if(!t)throw new kr(Dr.CheckoutButtonNotInitialized);return this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()).then((function(n){var i=n.cart.getCart(),a=i?i.id:"";return t.request.post(r._host+"/api/storefront/payment/paypalexpress",{merchantId:e,cartId:a},{headers:(0,o.__assign)({"X-API-INTERNAL":Hn},jn)})})).then((function(e){return e.id})).catch((function(e){throw n&&n(e),e}))},e.prototype._tokenizePayment=function(e,t,n,r){var i=this;if(!this._paymentMethod)throw new kr(Dr.CheckoutButtonNotInitialized);if(!t)throw new kr(Dr.CheckoutButtonNotInitialized);if(!e.paymentID||!e.payerID)throw new Pn(bn.MissingPayment);var o=this._paymentMethod.id;return t.payment.get(e.paymentID).then((function(t){i._formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:o,action:n?"process_payment":"set_external_checkout",paymentId:e.paymentID,payerId:e.payerID,payerInfo:JSON.stringify(t.payer.payer_info)})}))},e}();function ga(){try{return process.env.NODE_ENV||0}catch(e){return"development"}}const ya=function(){function e(e){this._console=e}return e.prototype.log=function(){for(var e=[],t=0;t0}));a.length>1&&a[0].matches===a[1].matches&&"development"===ga()&&Ca.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.");var s=a[0];if(s&&s.token)return s.token;if(this._useFallback){var u=null===(n=o.find((function(e){return e.default})))||void 0===n?void 0:n.token;if(u)return u}throw new Error("Unable to resolve to a registered token with the provided token.")},e}();function Ia(e,t){return Object.assign(e,{resolveIds:t})}const Ea=function(e){function t(t){var n=e.call(this,t||"Payment process was cancelled.")||this;return n.name="PaymentMethodCancelledError",n.type="payment_cancelled",n}return(0,o.__extends)(t,e),t}(s);const wa=function(e){function t(t){var n=e.call(this,t||"An unexpected error has occurred during buy now cart creation process. Please try again later.")||this;return n.name="BuyNowCartCreationError",n.type="buy_now_cart_creation_error",n}return(0,o.__extends)(t,e),t}(s);function Aa(e){if(!function(e){return"ApplePaySession"in e}(e))throw new Error("Apple pay is not supported")}const ba=function(){function e(){}return e.prototype.create=function(e){return Aa(window),new ApplePaySession(1,e)},e}();var Pa;!function(e){e.Subtotal="Subtotal",e.Shipping="Shipping"}(Pa||(Pa={}));const Oa=function(){function e(e,t,n){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=n,this._onAuthorizeCallback=m.noop,this._subTotalLabel=Pa.Subtotal,this._shippingLabel=Pa.Shipping}return e.prototype.initialize=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,a,s,u,c;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(t=e.methodId,n=e.containerId,r=e.applepay,Aa(window),!t||!r)throw new da(ca.MissingPaymentMethod);return i=r.buttonClassName,a=r.onPaymentAuthorize,s=r.buyNowInitializeOptions,u=r.requiresShipping,this._requiresShipping=u,this._buyNowInitializeOptions=s,this._onAuthorizeCallback=a,s?[3,2]:[4,this._paymentIntegrationService.loadDefaultCheckout()];case 1:o.sent(),o.label=2;case 2:return[4,this._paymentIntegrationService.loadPaymentMethod(t)];case 3:return o.sent(),c=this._paymentIntegrationService.getState(),this._paymentMethod=c.getPaymentMethodOrThrow(t),[4,this._paymentIntegrationService.verifyCheckoutSpamProtection()];case 4:return o.sent(),this._applePayButton=this._createButton(n,i),this._applePayButton.addEventListener("click",this._handleWalletButtonClick.bind(this)),[2,Promise.resolve()]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype._createButton=function(e,t){void 0===t&&(t="apple-pay-checkout-button");var n=document.getElementById(e);if(!n)throw new aa("Unable to create wallet button without valid container ID.");document.body.classList.add("apple-pay-supported");var r=document.createElement("div");return r.setAttribute("class",t),r.setAttribute("role","button"),r.setAttribute("aria-label","Apple Pay button"),n.appendChild(r),r},e.prototype._handleWalletButtonClick=function(e){var t;return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r,i,a,s,u,c,d,p,l,h,f;return(0,o.__generator)(this,(function(o){if(e.preventDefault(),!this._paymentMethod||!this._paymentMethod.initializationData)throw new da(ca.MissingPaymentMethod);return this._buyNowInitializeOptions&&"function"==typeof this._buyNowInitializeOptions.getBuyNowCartRequestBody?(n=this._paymentMethod.initializationData,r=n.countryCode,i=n.currencyCode,a=n.merchantCapabilities,s=n.supportedNetworks,u=n.storeName,h=this._getRequestWithEmptyTotal(r,i,s,a),this._requiresShipping&&(null===(t=h.requiredShippingContactFields)||void 0===t||t.push("postalAddress")),f=this._sessionFactory.create(h),this._handleApplePayEvents(f,this._paymentMethod,u),f.begin()):(c=this._paymentIntegrationService.getState(),d=c.getCartOrThrow(),p=c.getStoreConfigOrThrow(),l=c.getCheckoutOrThrow(),h=this._getBaseRequest(d,l,p,this._paymentMethod),f=this._sessionFactory.create(h),this._handleApplePayEvents(f,this._paymentMethod,p.storeProfile.storeName),f.begin()),[2]}))}))},e.prototype._getRequestWithEmptyTotal=function(e,t,n,r){return{countryCode:e,currencyCode:t,supportedNetworks:n,merchantCapabilities:r,total:{label:"",amount:"0",type:"pending"},requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"]}},e.prototype._getBaseRequest=function(e,t,n,r){var i,o=n.storeProfile,a=o.storeCountryCode,s=o.storeName,u=e.currency,c=u.code,d=u.decimalPlaces,p=r.initializationData,l=p.merchantCapabilities,h=p.supportedNetworks,f=e.lineItems.physicalItems.length>0,m={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:a,currencyCode:c,merchantCapabilities:l,supportedNetworks:h,lineItems:[],total:f?{label:s,amount:""+t.grandTotal.toFixed(d),type:"pending"}:{label:s,amount:""+t.grandTotal.toFixed(d),type:"final"}};if(f)null===(i=m.requiredShippingContactFields)||void 0===i||i.push("postalAddress");else{var g=[{label:this._subTotalLabel,amount:""+t.subtotal.toFixed(d)}];t.taxes.forEach((function(e){return g.push({label:e.name,amount:""+e.amount.toFixed(d)})})),m.lineItems=g}return m},e.prototype._handleApplePayEvents=function(e,t,n){var r=this;e.onvalidatemerchant=function(n){return(0,o.__awaiter)(r,void 0,void 0,(function(){var r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this._onValidateMerchant(t,n)];case 1:return r=i.sent().body,e.completeMerchantValidation(r),[3,3];case 2:throw i.sent(),new Error("Merchant validation failed");case 3:return[2]}}))}))},this._buyNowInitializeOptions&&!this._requiresShipping&&(e.onpaymentmethodselected=function(){return(0,o.__awaiter)(r,void 0,void 0,(function(){return(0,o.__generator)(this,(function(t){switch(t.label){case 0:return[4,this._createBuyNowCart()];case 1:return t.sent(),this._handlePaymentMethodSelected(e),[2]}}))}))}),e.onshippingcontactselected=function(t){return(0,o.__awaiter)(r,void 0,void 0,(function(){return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return this._buyNowInitializeOptions&&this._requiresShipping?[4,this._createBuyNowCart()]:[3,2];case 1:r.sent(),r.label=2;case 2:return[4,this._handleShippingContactSelected(e,n,t)];case 3:return r.sent(),[2]}}))}))},e.onshippingmethodselected=function(t){return(0,o.__awaiter)(r,void 0,void 0,(function(){return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._handleShippingMethodSelected(e,n,t)];case 1:return r.sent(),[2]}}))}))},e.oncancel=function(){return(0,o.__awaiter)(r,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return n.trys.push([0,3,,4]),e="/remote-checkout/"+t.id+"/signout",[4,this._requestSender.get(e)];case 1:return n.sent(),[4,this._paymentIntegrationService.loadCheckout()];case 2:return[2,n.sent()];case 3:throw n.sent(),new Ea;case 4:return[2]}}))}))},e.onpaymentauthorized=function(n){return(0,o.__awaiter)(r,void 0,void 0,(function(){return(0,o.__generator)(this,(function(r){return[2,this._onPaymentAuthorized(n,e,t)]}))}))}},e.prototype._createBuyNowCart=function(){var e,t;return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:if(i.trys.push([0,3,,4]),!(n=null===(t=null===(e=this._buyNowInitializeOptions)||void 0===e?void 0:e.getBuyNowCartRequestBody)||void 0===t?void 0:t.call(e)))throw new da(ca.MissingCart);return[4,this._paymentIntegrationService.createBuyNowCart(n)];case 1:return r=i.sent(),[4,this._paymentIntegrationService.loadCheckout(r.id)];case 2:return i.sent(),[3,4];case 3:throw i.sent(),new wa;case 4:return[2]}}))}))},e.prototype._handlePaymentMethodSelected=function(e){var t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow(),r=t.getStoreConfigOrThrow(),i=t.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new da(ca.MissingPaymentMethod);var o=this._getBaseRequest(n,i,r,this._paymentMethod);delete o.total.type,e.completePaymentMethodSelection({newTotal:o.total,newLineItems:o.lineItems})},e.prototype._handleShippingContactSelected=function(e,t,n){var r;return(0,o.__awaiter)(this,void 0,void 0,(function(){var i,a,s,u,c,d,p,l,h,f,m,g;return(0,o.__generator)(this,(function(y){switch(y.label){case 0:i=this._transformContactToAddress(n.shippingContact),y.label=1;case 1:return y.trys.push([1,3,,4]),[4,this._paymentIntegrationService.updateShippingAddress(i)];case 2:return y.sent(),[3,4];case 3:throw y.sent(),e.abort(),new Error("Shipping address update failed");case 4:if(a=this._paymentIntegrationService.getState(),s=a.getCartOrThrow().currency.decimalPlaces,u=a.getCheckoutOrThrow(),c=null===(r=u.consignments[0].selectedShippingOption)||void 0===r?void 0:r.id,d=u.consignments[0].availableShippingOptions,p=null==d?void 0:d.find((function(e){return e.id===c})),l=null==d?void 0:d.filter((function(e){return e.id!==c})),h=p?[{label:p.description,amount:""+p.cost.toFixed(s),detail:p.additionalDescription,identifier:p.id}]:[],l&&(0,o.__spreadArrays)(l.filter((function(e){return e.isRecommended})),l.filter((function(e){return!e.isRecommended}))).forEach((function(e){return h.push({label:e.description,amount:""+e.cost.toFixed(s),detail:e.additionalDescription,identifier:e.id})})),!(d instanceof Array))throw new Error("Shipping options not available.");if(0===d.length)return e.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:t,amount:""+u.grandTotal.toFixed(s)},[]),[2];f=d.find((function(e){return e.isRecommended})),m=f?f.id:d[0].id,g=p?p.id:m,y.label=5;case 5:return y.trys.push([5,7,,8]),[4,this._updateShippingOption(g)];case 6:return y.sent(),[3,8];case 7:throw y.sent(),new Error("Shipping options update failed");case 8:return a=this._paymentIntegrationService.getState(),u=a.getCheckoutOrThrow(),e.completeShippingContactSelection({newShippingMethods:h,newTotal:{type:"final",label:t,amount:""+u.grandTotal.toFixed(s)},newLineItems:this._getUpdatedLineItems(u,s)}),[2]}}))}))},e.prototype._handleShippingMethodSelected=function(e,t,n){return(0,o.__awaiter)(this,void 0,void 0,(function(){var r,i,a,s;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:r=n.shippingMethod.identifier,o.label=1;case 1:return o.trys.push([1,3,,4]),[4,this._updateShippingOption(r)];case 2:return o.sent(),[3,4];case 3:throw o.sent(),e.abort(),new Error("Shipping option selection update failed.");case 4:return i=this._paymentIntegrationService.getState(),a=i.getCartOrThrow().currency.decimalPlaces,s=i.getCheckoutOrThrow(),e.completeShippingMethodSelection({newTotal:{type:"final",label:t,amount:""+s.grandTotal.toFixed(a)},newLineItems:this._getUpdatedLineItems(s,a)}),[2]}}))}))},e.prototype._getUpdatedLineItems=function(e,t){var n=[{label:this._subTotalLabel,amount:""+e.subtotal.toFixed(t)}];return e.taxes.forEach((function(e){return n.push({label:e.name,amount:""+e.amount.toFixed(t)})})),n.push({label:this._shippingLabel,amount:""+e.shippingCostTotal.toFixed(t)}),n},e.prototype._updateShippingOption=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(t){return[2,this._paymentIntegrationService.selectShippingOption(e)]}))}))},e.prototype._onValidateMerchant=function(e,t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n;return(0,o.__generator)(this,(function(r){return n=["validationUrl="+t.validationURL,"merchantIdentifier="+e.initializationData.merchantId,"displayName="+e.initializationData.storeName,"domainName="+window.location.hostname].join("&"),[2,this._requestSender.post((i=e.initializationData.paymentsUrl,i+"/api/public/v1/payments/applepay/validate_merchant"),{credentials:!1,headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","X-XSRF-TOKEN":null},body:n})];var i}))}))},e.prototype._onPaymentAuthorized=function(e,t,n){return(0,o.__awaiter)(this,void 0,void 0,(function(){var r,i,a,s,u,c,d,p,l,h,f,m;return(0,o.__generator)(this,(function(g){switch(g.label){case 0:r=e.payment,i=r.token,a=r.billingContact,s=r.shippingContact,u=this._paymentIntegrationService.getState(),c=u.getCartOrThrow(),d=c.lineItems.physicalItems.length>0,p={methodId:n.id,paymentData:{formattedPayload:{apple_pay_token:{payment_data:i.paymentData,payment_method:i.paymentMethod,transaction_id:i.transactionIdentifier}}}},l=this._transformContactToAddress(a),h=this._transformContactToAddress(s),f=null==s?void 0:s.emailAddress,m=(null==s?void 0:s.phoneNumber)||"",g.label=1;case 1:return g.trys.push([1,7,,8]),[4,this._paymentIntegrationService.updateBillingAddress((0,o.__assign)((0,o.__assign)({},l),{email:f,phone:m}))];case 2:return g.sent(),d?[4,this._paymentIntegrationService.updateShippingAddress(h)]:[3,4];case 3:g.sent(),g.label=4;case 4:return[4,this._paymentIntegrationService.submitOrder({useStoreCredit:!1})];case 5:return g.sent(),[4,this._paymentIntegrationService.submitPayment(p)];case 6:return g.sent(),t.completePayment(ApplePaySession.STATUS_SUCCESS),[2,this._onAuthorizeCallback()];case 7:throw g.sent(),t.completePayment(ApplePaySession.STATUS_FAILURE),new Error("Payment cannot complete");case 8:return[2]}}))}))},e.prototype._transformContactToAddress=function(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:[]}},e}(),Ta=Ia((function(e){var t=e.getState().getHost;return new Oa((0,r.createRequestSender)({host:t()}),e,new ba)}),[{id:"applepay"}]),Ra=require("query-string"),Ma=function(e){function t(t){var n=e.call(this,t||"Not implemented.")||this;return n.name="NotImplementedError",n.type="not_implemented",n}return(0,o.__extends)(t,e),t}(s);var Da,ka,Na;!function(e){e.SandboxMode="bolt_sandbox",e.StagingMode="bolt_staging",e.DevelopmentMode="bolt_development"}(Da||(Da={})),function(e){e.Small="small",e.Medium="medium",e.Large="large"}(ka||(ka={})),function(e){e.Pill="pill",e.Rect="rect"}(Na||(Na={}));const La=function(){function e(e,t,n){void 0===n&&(n=window),this.paymentIntegrationService=e,this.boltScriptLoader=t,this.boltHostWindow=n}return e.prototype.initialize=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,a,s,u,c,d,p,l,h,f;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(t=e.bolt,n=e.containerId,r=e.methodId,a=(i=t||{}).buyNowInitializeOptions,s=i.style,!r)throw new aa('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new aa('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new aa('Unable to initialize payment because "options.bolt" argument is not provided.');if(!Boolean(a))throw new Ma("Only buy now flow is implemented for Bolt button");if(!(null==a?void 0:a.storefrontApiToken)||"string"!=typeof a.storefrontApiToken)throw new aa('Unable to initialize payment because "options.storefrontApiToken" argument is not provided.');return u=this.paymentIntegrationService.getState(),c=u.getPaymentMethodOrThrow(r),d=c.initializationData,p=c.config,h=(l=d||{}).publishableKey,f=l.developerConfig,[4,this.boltScriptLoader.loadBoltClient(h,p.testMode,f,"BigCommerce",a.storefrontApiToken)];case 1:return o.sent(),this.renderButton(n,c,s),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.renderButton=function(e,t,n){var r;"function"==typeof(null===(r=this.boltHostWindow.BoltConnect)||void 0===r?void 0:r.setupProductPageCheckout)&&(this.addButtonContainer(e,t,n),this.boltHostWindow.BoltConnect.setupProductPageCheckout())},e.prototype.addButtonContainer=function(e,t,n){var r=document.getElementById(e);if(r){var i=document.createElement("div"),o=document.createElement("object");i.setAttribute("id","product-page-checkout-wrapper"),i.setAttribute("class","bolt-button-wrapper"),i.setAttribute("style","display:none"),i.setAttribute("data-tid","product-page-checkout-wrapper"),o.setAttribute("data",this.getBoltObjectData(t,n)),o.setAttribute("class","bolt-product-checkout-button"),i.append(o),r.innerHTML="",r.append(i)}},e.prototype.getBoltObjectData=function(e,t){var n=e.initializationData,r=e.config,i=n||{},o=i.publishableKey,a=i.developerConfig,s=this.boltScriptLoader.getDomainURL(!!r.testMode,a),u=this.getButtonHeight(null==t?void 0:t.size),c=this.getButtonBorderRadius(null==t?void 0:t.shape,u);return(0,Ra.stringifyUrl)({url:"https://"+s+"/v1/checkout_button",query:{publishable_key:o,variant:"ppc",height:u,border_radius:c}})},e.prototype.getButtonHeight=function(e){if(e)switch(e){case ka.Small:return 25;case ka.Large:return 45;case ka.Medium:default:return 40}},e.prototype.getButtonBorderRadius=function(e,t){if(e)switch(e){case Na.Pill:return t?Math.round(t/2):void 0;case Na.Rect:default:return 4}},e}();const za=function(e){function t(t){var n=e.call(this,t||"Unable to proceed because the client library of a payment method is not loaded or ready to be used.")||this;return n.name="PaymentMethodClientUnavailableError",n.type="payment_method_client_unavailable",n}return(0,o.__extends)(t,e),t}(s),Ua=function(){function e(e,t){void 0===t&&(t=window),this.scriptLoader=e,this.boltHostWindow=t}return e.prototype.loadBoltClient=function(e,t,n,r,i){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(this.boltHostWindow.BoltCheckout)return[2,this.boltHostWindow.BoltCheckout];if(!e)throw new aa('Unable to initialize payment because "publishableKey" argument is not provided.');return[4,this.scriptLoader.loadScript("//"+this.getDomainURL(!!t,n)+"/connect-bigcommerce.js",this.getScriptOptions("bolt-connect",e,r,i))];case 1:return o.sent(),[4,this.scriptLoader.loadScript("//"+this.getDomainURL(!!t,n)+"/track.js",this.getScriptOptions("bolt-track",e))];case 2:if(o.sent(),!this.boltHostWindow.BoltCheckout)throw new za;return[2,this.boltHostWindow.BoltCheckout]}}))}))},e.prototype.loadBoltEmbedded=function(e,t,n){return(0,o.__awaiter)(this,void 0,void 0,(function(){var r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:return r={async:!0,attributes:{id:"bolt-embedded"}},[4,this.scriptLoader.loadScript("//"+this.getDomainURL(!!t,n)+"/embed.js",r)];case 1:if(i.sent(),!this.boltHostWindow.Bolt)throw new za;return[2,this.boltHostWindow.Bolt(e)]}}))}))},e.prototype.getDomainURL=function(e,t){if(!e)return"connect.bolt.com";if(t)switch(t.developerMode){case Da.StagingMode:return"connect-staging.bolt.com";case Da.DevelopmentMode:return"connect."+t.developerDomain}return"connect-sandbox.bolt.com"},e.prototype.getScriptOptions=function(e,t,n,r){return{async:!0,attributes:(0,o.__assign)((0,o.__assign)({id:e,"data-publishable-key":t},n&&{"data-shopping-cart-id":n}),r&&{"data-storefront-api-token":r})}},e}(),Fa=Ia((function(e){return new La(e,new Ua((0,Kn.getScriptLoader)()))}),[{id:"bolt"}]);var qa,Ba,Ga,xa,Ya,Va,Ha;!function(e){e.BuyNow="BUY_NOW"}(qa||(qa={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(Ba||(Ba={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(Ga||(Ga={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(xa||(xa={})),function(e){e.pill="pill",e.rect="rect"}(Ya||(Ya={})),function(e){e.OXXO="oxxo"}(Va||(Va={})),function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED"}(Ha||(Ha={}));const ja=function(){function e(e,t,n,r){this.formPoster=e,this.paymentIntegrationService=t,this.paypalCommerceRequestSender=n,this.paypalCommerceScriptLoader=r}return e.prototype.loadPayPalSdk=function(e,t,n){return(0,o.__awaiter)(this,void 0,void 0,(function(){var r,i,a,s;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:return r=this.paymentIntegrationService.getState(),i=t||r.getCartOrThrow().currency.code,a=r.getPaymentMethodOrThrow(e),s=this,[4,this.paypalCommerceScriptLoader.getPayPalSDK(a,i,n)];case 1:return s.paypalSdk=o.sent(),[2,this.paypalSdk]}}))}))},e.prototype.getPayPalSdkOrThrow=function(){if(!this.paypalSdk)throw new za;return this.paypalSdk},e.prototype.createBuyNowCartOrThrow=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if(!(t=e.getBuyNowCartRequestBody()))throw new da(ca.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.paymentIntegrationService.createBuyNowCart(t)];case 2:return[2,n.sent()];case 3:throw n.sent(),new wa;case 4:return[2]}}))}))},e.prototype.createOrder=function(e,t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return n=this.paymentIntegrationService.getState().getCartOrThrow().id,[4,this.paypalCommerceRequestSender.createOrder(e,(0,o.__assign)({cartId:n},t))];case 1:return[2,r.sent().orderId]}}))}))},e.prototype.updateOrder=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,t,n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getConsignmentsOrThrow()[0],r.label=1;case 1:return r.trys.push([1,3,,4]),[4,this.paypalCommerceRequestSender.updateOrder({availableShippingOptions:n.availableShippingOptions,cartId:t.id,selectedShippingOption:n.selectedShippingOption})];case 2:return r.sent(),[3,4];case 3:throw r.sent(),new c;case 4:return[2]}}))}))},e.prototype.getOrderStatus=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,this.paypalCommerceRequestSender.getOrderStatus()];case 1:return[2,e.sent().status];case 2:throw e.sent(),new c;case 3:return[2]}}))}))},e.prototype.tokenizePayment=function(e,t){var n=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new da(ca.MissingOrderId);return this.formPoster.postForm("/checkout.php",(0,o.__assign)({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},n.source===qa.BuyNow&&{cart_id:n.id}))},e.prototype.submitPayment=function(e,t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return n={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:e,paypal_account:{order_id:t}}},[4,this.paymentIntegrationService.submitPayment({methodId:e,paymentData:n})];case 1:return r.sent(),[2]}}))}))},e.prototype.getShippingOptionOrThrow=function(e){var t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],n=t.availableShippingOptions||[],r=n.find((function(e){return e.isRecommended})),i=(e?n.find((function(t){return t.id===e})):n.find((function(e){var n;return e.id===(null===(n=t.selectedShippingOption)||void 0===n?void 0:n.id)})))||r||n[0];if(!i)throw new Error("Your order can't be shipped to this address");return i},e.prototype.getAddress=function(e){return{firstName:(null==e?void 0:e.firstName)||"",lastName:(null==e?void 0:e.lastName)||"",email:(null==e?void 0:e.email)||"",phone:"",company:"",address1:(null==e?void 0:e.address1)||"",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:[]}},e.prototype.getBillingAddressFromOrderDetails=function(e){var t=e.payer;return this.getAddress({firstName:t.name.given_name,lastName:t.name.surname,email:t.email_address,address1:t.address.address_line_1,city:t.address.admin_area_2,countryCode:t.address.country_code,postalCode:t.address.postal_code,stateOrProvinceCode:t.address.admin_area_1})},e.prototype.getShippingAddressFromOrderDetails=function(e){var t,n,r=e.payer,i=(null===(n=null===(t=e.purchase_units[0])||void 0===t?void 0:t.shipping)||void 0===n?void 0:n.address)||{};return this.getAddress({firstName:r.name.given_name,lastName:r.name.surname,email:r.email_address,address1:i.address_line_1,city:i.admin_area_2,countryCode:i.country_code,postalCode:i.postal_code,stateOrProvinceCode:i.admin_area_1})},e.prototype.getValidButtonStyle=function(e){var t=e||{},n=t.color,r=t.height,i=t.label,o=t.shape,a={color:n&&xa[n]?n:void 0,height:this.getValidHeight(r),label:i&&Ga[i]?i:void 0,shape:o&&Ya[o]?o:void 0};return(0,m.omitBy)(a,m.isNil)},e.prototype.getValidHeight=function(e){return e&&"number"==typeof e?e>55?55:e<25?25:e:40},e.prototype.removeElement=function(e){var t=e&&document.getElementById(e);t&&t.remove()},e}();var Wa,Ka="This API endpoint is for internal use only and may change in the future";!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(Wa||(Wa={}));const Qa=Wa;var Za={"X-Checkout-SDK-Version":"1.398.2"};const Ja=function(){function e(e){this.requestSender=e}return e.prototype.createOrder=function(e,t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r,i;return(0,o.__generator)(this,(function(a){switch(a.label){case 0:return n="/api/storefront/payment/"+e,r=t,i=(0,o.__assign)({"X-API-INTERNAL":Ka,"Content-Type":Qa.Json},Za),[4,this.requestSender.post(n,{headers:i,body:r})];case 1:return[2,a.sent().body]}}))}))},e.prototype.updateOrder=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return t=e,n=(0,o.__assign)({"X-API-INTERNAL":Ka,"Content-Type":Qa.Json},Za),[4,this.requestSender.put("/api/storefront/initialization/paypalcommerce",{headers:n,body:t})];case 1:return[2,r.sent().body]}}))}))},e.prototype.getOrderStatus=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(t){switch(t.label){case 0:return e=(0,o.__assign)({"X-API-INTERNAL":Ka,"Content-Type":Qa.Json},Za),[4,this.requestSender.get("/api/storefront/initialization/paypalcommerce",{headers:e})];case 1:return[2,t.sent().body]}}))}))},e}(),Xa=function(){function e(e){this.scriptLoader=e,this.window=window}return e.prototype.getPayPalSDK=function(e,t,n){return(0,o.__awaiter)(this,void 0,void 0,(function(){var r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:return this.paypalSdk?[3,2]:(r=this,[4,this.loadPayPalSDK(this.getPayPalSdkScriptConfigOrThrow(e,t,n))]);case 1:r.paypalSdk=i.sent(),i.label=2;case 2:return[2,this.paypalSdk]}}))}))},e.prototype.loadPayPalSDK=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(t){switch(t.label){case 0:return this.window.paypalLoadScript?[3,2]:[4,this.scriptLoader.loadScript("https://unpkg.com/@paypal/paypal-js@5.0.5/dist/iife/paypal-js.min.js",{async:!0,attributes:{}})];case 1:if(t.sent(),!this.window.paypalLoadScript)throw new za;t.label=2;case 2:return[4,this.window.paypalLoadScript(e)];case 3:if(t.sent(),!this.window.paypal)throw new za;return[2,this.window.paypal]}}))}))},e.prototype.getPayPalSdkScriptConfigOrThrow=function(e,t,n){void 0===n&&(n=!0);var r=e.id,i=e.clientToken,a=e.initializationData;if(!(null==a?void 0:a.clientId))throw new da(ca.MissingPaymentMethod);var s=a.intent,u=a.clientId,c=a.merchantId,d=a.buyerCountry,p=a.attributionId,l=a.isVenmoEnabled,h=a.isHostedCheckoutEnabled,f=a.isPayPalCreditAvailable,m=a.isDeveloperModeApplicable,g=a.availableAlternativePaymentMethods,y=void 0===g?[]:g,_=a.enabledAlternativePaymentMethods,v=void 0===_?[]:_,C=h||n,S="paypalcommercecreditcards"===r,I=S?["card"]:[],E=S?[]:["card"],w=f?["credit","paylater"]:[],A=f?[]:["credit","paylater"],b=n||!C,P=b&&l?["venmo"]:[],O=b&&l?[]:["venmo"],T=b?v:[],R=b?y.filter((function(e){return!v.includes(e)})):y,M=(0,o.__spreadArrays)(E,A,O,R),D=(0,o.__spreadArrays)(I,w,P,T);return(0,o.__assign)({"client-id":u,"data-partner-attribution-id":p,"data-client-token":i,"merchant-id":c,"enable-funding":D.length>0?D:void 0,"disable-funding":M.length>0?M:void 0,commit:C,components:["buttons","hosted-fields","messages","payment-fields"],currency:t,intent:s},m&&{"buyer-country":d})},e}(),$a=function(e){var t=e.getState().getHost;return new ja((0,i.createFormPoster)(),e,new Ja((0,r.createRequestSender)({host:t()})),new Xa((0,Kn.getScriptLoader)()))},es=function(){function e(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}return e.prototype.initialize=function(e){var t;return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r,i,a,s;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(n=e.paypalcommerce,r=e.containerId,i=e.methodId,a=Boolean(null==n?void 0:n.buyNowInitializeOptions),!i)throw new aa('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new aa('Unable to initialize payment because "options.containerId" argument is not provided.');if(!n)throw new aa('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');if(a&&!n.currencyCode)throw new aa('Unable to initialize payment because "options.paypalcommerce.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null===(t=n.buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody))throw new aa('Unable to initialize payment because "options.paypalcommerce.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');return a?[3,2]:[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:o.sent(),o.label=2;case 2:return s=a?n.currencyCode:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,[4,this.paypalCommerceIntegrationService.loadPayPalSdk(i,s,!1)];case 3:return o.sent(),this.renderButton(r,i,n),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.renderButton=function(e,t,n){var r=this,i=n.buyNowInitializeOptions,a=n.style,s=n.onComplete,u=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),c=(this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t).initializationData||{}).isHostedCheckoutEnabled,d={createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommerce")},onApprove:function(e){var n=e.orderID;return r.paypalCommerceIntegrationService.tokenizePayment(t,n)}},p={onClick:function(){return r.handleClick(i)},onCancel:function(){return r.paymentIntegrationService.loadDefaultCheckout()}},l={onShippingAddressChange:function(e){return r.onShippingAddressChange(e)},onShippingOptionsChange:function(e){return r.onShippingOptionsChange(e)},onApprove:function(e,n){return r.onHostedCheckoutApprove(e,n,t,s)}},h=(0,o.__assign)((0,o.__assign)((0,o.__assign)({fundingSource:u.FUNDING.PAYPAL,style:this.paypalCommerceIntegrationService.getValidButtonStyle(a)},d),i&&p),c&&l),f=u.Buttons(h);f.isEligible()?f.render("#"+e):this.paypalCommerceIntegrationService.removeElement(e)},e.prototype.handleClick=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return e?[4,this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e)]:[3,3];case 1:return t=n.sent(),[4,this.paymentIntegrationService.loadCheckout(t.id)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},e.prototype.onHostedCheckoutApprove=function(e,t,n,r){return(0,o.__awaiter)(this,void 0,void 0,(function(){var i,a,s,u,c,d;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(!e.orderID)throw new da(ca.MissingOrderId);return i=this.paymentIntegrationService.getState(),a=i.getCartOrThrow(),[4,t.order.get()];case 1:s=o.sent(),o.label=2;case 2:return o.trys.push([2,9,,10]),u=this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(s),[4,this.paymentIntegrationService.updateBillingAddress(u)];case 3:return o.sent(),a.lineItems.physicalItems.length>0?(c=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(s),[4,this.paymentIntegrationService.updateShippingAddress(c)]):[3,6];case 4:return o.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:o.sent(),o.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return o.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,e.orderID)];case 8:return o.sent(),r&&"function"==typeof r&&r(),[2,!0];case 9:throw d=o.sent(),new Error(d);case 10:return[2]}}))}))},e.prototype.onShippingAddressChange=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:t=this.paypalCommerceIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.country_code,postalCode:e.shippingAddress.postal_code,stateOrProvinceCode:e.shippingAddress.state}),i.label=1;case 1:return i.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(t)];case 2:return i.sent(),[4,this.paymentIntegrationService.updateShippingAddress(t)];case 3:return i.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return i.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return i.sent(),[3,7];case 6:throw r=i.sent(),new Error(r);case 7:return[2]}}))}))},e.prototype.onShippingOptionsChange=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:t=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(t.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:throw n=r.sent(),new Error(n);case 5:return[2]}}))}))},e}(),ts=Ia((function(e){return new es(e,$a(e))}),[{id:"paypalcommerce"}]),ns=function(){function e(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}return e.prototype.initialize=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,a,s,u,c,d;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(t=e.paypalcommercecredit,n=e.containerId,r=e.methodId,a=(i=t||{}).buyNowInitializeOptions,s=i.currencyCode,u=i.messagingContainerId,c=!!a,!r)throw new aa('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new aa('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new aa('Unable to initialize payment because "options.paypalcommercecredit" argument is not provided.');if(c&&!s)throw new aa('Unable to initialize payment because "options.paypalcommercecredit.currencyCode" argument is not provided.');if(c&&"function"!=typeof(null==a?void 0:a.getBuyNowCartRequestBody))throw new aa('Unable to initialize payment because "options.paypalcommercecredit.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');return c?[3,2]:[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:o.sent(),o.label=2;case 2:return d=c?s:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,[4,this.paypalCommerceIntegrationService.loadPayPalSdk(r,d,!1)];case 3:return o.sent(),this.renderButton(n,r,t),this.renderMessages(u),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.renderButton=function(e,t,n){var r=this,i=n.buyNowInitializeOptions,a=n.style,s=n.onComplete,u=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),c=(this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t).initializationData||{}).isHostedCheckoutEnabled,d={createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommercecredit")},onApprove:function(e){var n=e.orderID;return r.paypalCommerceIntegrationService.tokenizePayment(t,n)}},p={onClick:function(){return r.handleClick(i)},onCancel:function(){return r.paymentIntegrationService.loadDefaultCheckout()}},l={onShippingAddressChange:function(e){return r.onShippingAddressChange(e)},onShippingOptionsChange:function(e){return r.onShippingOptionsChange(e)},onApprove:function(e,n){return r.onHostedCheckoutApprove(e,n,t,s)}},h=[u.FUNDING.PAYLATER,u.FUNDING.CREDIT],f=!1;h.forEach((function(t){if(!f){var n=(0,o.__assign)((0,o.__assign)((0,o.__assign)({fundingSource:t,style:r.paypalCommerceIntegrationService.getValidButtonStyle(a)},d),i&&p),c&&l),s=u.Buttons(n);s.isEligible()&&(s.render("#"+e),f=!0)}})),f||this.paypalCommerceIntegrationService.removeElement(e)},e.prototype.handleClick=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return e?[4,this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e)]:[3,3];case 1:return t=n.sent(),[4,this.paymentIntegrationService.loadCheckout(t.id)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},e.prototype.onHostedCheckoutApprove=function(e,t,n,r){return(0,o.__awaiter)(this,void 0,void 0,(function(){var i,a,s,u,c,d;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(!e.orderID)throw new da(ca.MissingOrderId);return i=this.paymentIntegrationService.getState(),a=i.getCartOrThrow(),[4,t.order.get()];case 1:s=o.sent(),o.label=2;case 2:return o.trys.push([2,9,,10]),u=this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(s),[4,this.paymentIntegrationService.updateBillingAddress(u)];case 3:return o.sent(),a.lineItems.physicalItems.length>0?(c=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(s),[4,this.paymentIntegrationService.updateShippingAddress(c)]):[3,6];case 4:return o.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:o.sent(),o.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return o.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,e.orderID)];case 8:return o.sent(),r&&"function"==typeof r&&r(),[2,!0];case 9:throw d=o.sent(),new Error(d);case 10:return[2]}}))}))},e.prototype.onShippingAddressChange=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:t=this.paypalCommerceIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.country_code,postalCode:e.shippingAddress.postal_code,stateOrProvinceCode:e.shippingAddress.state}),i.label=1;case 1:return i.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(t)];case 2:return i.sent(),[4,this.paymentIntegrationService.updateShippingAddress(t)];case 3:return i.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return i.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return i.sent(),[3,7];case 6:throw r=i.sent(),new Error(r);case 7:return[2]}}))}))},e.prototype.onShippingOptionsChange=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:t=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(t.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:throw n=r.sent(),new Error(n);case 5:return[2]}}))}))},e.prototype.renderMessages=function(e){var t=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();if(e&&document.getElementById(e)){var n={amount:this.paymentIntegrationService.getState().getCartOrThrow().cartAmount,placement:"cart",style:{layout:"text"}};t.Messages(n).render("#"+e)}},e}(),rs=Ia((function(e){return new ns(e,$a(e))}),[{id:"paypalcommercecredit"}]),is=function(){function e(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}return e.prototype.initialize=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,a,s,u,c;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(t=e.paypalcommercevenmo,n=e.containerId,r=e.methodId,a=(i=t||{}).buyNowInitializeOptions,s=i.currencyCode,u=!!a,!r)throw new aa('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new aa('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new aa('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');if(u&&!s)throw new aa('Unable to initialize payment because "options.paypalcommercevenmo.currencyCode" argument is not provided.');if(u&&"function"!=typeof(null==a?void 0:a.getBuyNowCartRequestBody))throw new aa('Unable to initialize payment because "options.paypalcommercevenmo.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');return u?[3,2]:[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:o.sent(),o.label=2;case 2:return c=u?s:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,[4,this.paypalCommerceIntegrationService.loadPayPalSdk(r,c,!1)];case 3:return o.sent(),this.renderButton(n,r,t),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.renderButton=function(e,t,n){var r=this,i=n.buyNowInitializeOptions,a=n.style,s=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),u=s.FUNDING.VENMO,c={createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommercevenmo")},onApprove:function(e){var n=e.orderID;return r.paypalCommerceIntegrationService.tokenizePayment(t,n)}},d={onClick:function(){return r.handleClick(i)},onCancel:function(){return r.paymentIntegrationService.loadDefaultCheckout()}},p=(0,o.__assign)((0,o.__assign)({fundingSource:u,style:this.getValidVenmoButtonStyles(a)},c),i&&d),l=s.Buttons(p);l.isEligible()?l.render("#"+e):this.paypalCommerceIntegrationService.removeElement(e)},e.prototype.getValidVenmoButtonStyles=function(e){var t=this.paypalCommerceIntegrationService.getValidButtonStyle(e);return t.color===xa.gold?(0,o.__assign)((0,o.__assign)({},t),{color:void 0}):t},e.prototype.handleClick=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return e?[4,this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e)]:[3,3];case 1:return t=n.sent(),[4,this.paymentIntegrationService.loadCheckout(t.id)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},e}(),os=Ia((function(e){return new is(e,$a(e))}),[{id:"paypalcommercevenmo"}]),as=function(){function e(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}return e.prototype.initialize=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,a,s,u,c,d;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(t=e.paypalcommercealternativemethods,n=e.containerId,r=e.methodId,a=(i=t||{}).apm,s=i.buyNowInitializeOptions,u=i.currencyCode,c=!!s,!r)throw new aa('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new aa('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new aa('Unable to initialize payment because "options.paypalcommercealternativemethods" argument is not provided.');if(!a)throw new aa('Unable to initialize payment because "options.paypalcommercealternativemethods.apm" argument is not provided.');if(c&&!u)throw new aa('Unable to initialize payment because "options.paypalcommercealternativemethods.currencyCode" argument is not provided.');if(c&&"function"!=typeof(null==s?void 0:s.getBuyNowCartRequestBody))throw new aa('Unable to initialize payment because "options.paypalcommercealternativemethods.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');return c?[3,2]:[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:o.sent(),o.label=2;case 2:return d=c?u:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,[4,this.paypalCommerceIntegrationService.loadPayPalSdk(r,d,!1)];case 3:return o.sent(),this.renderButton(n,r,t),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.renderButton=function(e,t,n){var r=this,i=n.apm,a=n.buyNowInitializeOptions,s=n.style,u=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();if(!Object.values(u.FUNDING).includes(i))throw new aa('Unable to initialize PayPal button because "options.paypalcommercealternativemethods.apm" argument is not valid funding source.');var c={createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommercealternativemethod")},onApprove:function(e){var n=e.orderID;return r.paypalCommerceIntegrationService.tokenizePayment(t,n)}},d={onClick:function(){return r.handleClick(a)},onCancel:function(){return r.paymentIntegrationService.loadDefaultCheckout()}},p=(0,o.__assign)((0,o.__assign)({fundingSource:i,style:this.paypalCommerceIntegrationService.getValidButtonStyle(s)},c),a&&d),l=u.Buttons(p);l.isEligible()?l.render("#"+e):this.paypalCommerceIntegrationService.removeElement(e)},e.prototype.handleClick=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return e?[4,this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e)]:[3,3];case 1:return t=n.sent(),[4,this.paymentIntegrationService.loadCheckout(t.id)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},e}(),ss=Ia((function(e){return new as(e,$a(e))}),[{id:"paypalcommercealternativemethods"}]);var us,cs,ds,ps,ls;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(us||(us={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(cs||(cs={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black"}(ds||(ds={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(ps||(ps={})),function(e){e.PILL="pill",e.RECT="rect"}(ls||(ls={}));const hs=function(){function e(e,t,n){this.paymentIntegrationService=e,this.paypalExpressScriptLoader=t,this.formPoster=n}return e.prototype.initialize=function(e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:if(t=this.paymentIntegrationService.getState(),n=t.getPaymentMethodOrThrow(e.methodId),!e.paypal)throw new aa;if(!n.config.merchantId)throw new da(ca.MissingPaymentMethod);return[4,this.paypalExpressScriptLoader.loadPaypalSDK(n.config.merchantId)];case 1:return r=i.sent(),this.renderButton(e,r),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.renderButton=function(e,t){var n,r=this,i=e.containerId,o=e.methodId,a=e.paypal,s=a.allowCredit,u=a.clientId,c=a.onPaymentError,d=a.shouldProcessPayment,p=a.style,l=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId);if(!l.config.merchantId)throw new da(ca.MissingPaymentMethod);var h=l.config.merchantId,f=l.config.testMode?"sandbox":"production",m=((n={})[f]=u,n),g=t.FUNDING.CREDIT||"credit",y=s?[g]:[],_=s?[]:[g];return t.Button.render({env:f,client:m,commit:d,funding:{allowed:y,disallowed:_},style:this.getStyle(p),payment:function(e,t){return r.setupPayment(h,t,c)},onAuthorize:function(e,t){return r.tokenizePayment(e,o,t,d)}},i)},e.prototype.getStyle=function(e){var t=e||{},n=t.color,r=t.fundingicons,i=t.label,o=t.layout,a=t.shape,s=t.size,u=t.tagline;return{color:n,fundingicons:r,label:i,layout:o,shape:a||ls.RECT,size:"small"===s?cs.RESPONSIVE:s,tagline:u}},e.prototype.setupPayment=function(e,t,n){return(0,o.__awaiter)(this,void 0,void 0,(function(){var r,i,a,s;return(0,o.__generator)(this,(function(u){switch(u.label){case 0:if(!t)throw new ua(sa.CheckoutButtonNotInitialized);u.label=1;case 1:return u.trys.push([1,4,,5]),[4,this.paymentIntegrationService.loadDefaultCheckout()];case 2:return r=u.sent(),i=r.getCartOrThrow().id,a=r.getHost()||"",[4,t.request.post(a+"/api/storefront/payment/paypalexpress",{merchantId:e,cartId:i},{headers:(0,o.__assign)({"X-API-INTERNAL":Ka},Za)})];case 3:return[2,u.sent().id];case 4:throw s=u.sent(),n&&n(s),s;case 5:return[2]}}))}))},e.prototype.tokenizePayment=function(e,t,n,r){return(0,o.__awaiter)(this,void 0,void 0,(function(){var i,a,s;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(!n)throw new ua(sa.CheckoutButtonNotInitialized);if(!e.paymentID||!e.payerID)throw new da(ca.MissingPayment);return i=this.paymentIntegrationService.getState(),a=i.getPaymentMethodOrThrow(t),[4,n.payment.get(e.paymentID)];case 1:return s=o.sent(),[2,this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:a.id,action:r?"process_payment":"set_external_checkout",paymentId:e.paymentID,payerId:e.payerID,payerInfo:JSON.stringify(s.payer.payer_info)})]}}))}))},e}();const fs=function(){function e(e){this.scriptLoader=e,this.window=window}return e.prototype.loadPaypalSDK=function(e){return void 0===e&&(e=""),(0,o.__awaiter)(this,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return t=(0,o.__assign)({async:!0,attributes:{"data-merchant-id":e}},e&&{attributes:{"data-merchant-id":e}}),[4,this.scriptLoader.loadScript("//www.paypalobjects.com/api/checkout.min.js",t)];case 1:if(n.sent(),!this.window.paypal)throw new za;return[2,this.window.paypal]}}))}))},e}(),ms=Ia((function(e){return new hs(e,new fs((0,Kn.getScriptLoader)()),(0,i.createFormPoster)())}),[{id:"paypalexpress"}]);function gs(e){var t=null!=e?e:{},o=t.host,a=t.locale,s=void 0===a?"en":a,u=Bn(),c=(0,r.createRequestSender)({host:o}),d=(0,i.createFormPoster)({host:o}),p=function(e,t){void 0===t&&(t=n);for(var r=new Sa,i=function(t){if(!function(e){return"resolveIds"in e}(t))return"continue";for(var n=0,i=t.resolveIds;n(()=>{var t={89538:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=d(n(66534)),o=d(n(43279)),a=d(n(86202)),u=d(n(98834)),s=d(n(43961)),c=d(n(11906));function d(t){return t&&t.__esModule?t:{default:t}}function l(t){return l="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},l(t)}function f(t,e){for(var n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;e.default={host:""}},56280:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.APPLICATION_JSON=void 0,e.APPLICATION_JSON="application/json"},44955:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var r=n(56280),i=n(99338),o={headers:{Accept:r.APPLICATION_JSON,"Content-Type":r.APPLICATION_JSON},method:i.GET};e.default=o},99338:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.POST=e.GET=e.DELETE=void 0,e.GET="GET",e.POST="POST",e.DELETE="DELETE"},92197:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(5099),n(38490),n(64668),n(16368),n(99023),n(40737),n(74035),n(10951),n(58443),n(34500),n(25959),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i,o=(i=n(66534))&&i.__esModule?i:{default:i},a=n(56280),u=n(60301);function s(t){return s="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},s(t)}function c(t,e){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:a.APPLICATION_JSON;return t&&(0,u.includes)(e,a.APPLICATION_JSON)?JSON.stringify(t):t}},{key:"fromResponse",value:function(t){var e=this.parseResponseHeaders(t.getAllResponseHeaders()),n=t.getResponseHeader("Content-Type"),r=t.status,i=t.statusText,o="response"in t?t.response:t.responseText;return o&&(0,u.includes)(n,a.APPLICATION_JSON)&&(o=JSON.parse(o)),{data:o,headers:e,status:r,statusText:i}}},{key:"parseResponseHeaders",value:function(t){return(t?t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/):[]).reduce((function(t,e){var n=e.split(":"),r=(n.shift()||"").trim();return r?(0,o.default)({},t,function(t,e,n){return(e=d(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}({},r.toLowerCase(),n.join(":").trim())):t}),{})}}],r=[{key:"create",value:function(){return new t}}],n&&c(e.prototype,n),r&&c(e,r),Object.defineProperty(e,"prototype",{writable:!1}),t}();e.default=l},48773:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function o(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=d(n(18712)),o=d(n(66534)),a=n(99338),u=d(n(44955)),s=d(n(92197)),c=d(n(48773));function d(t){return t&&t.__esModule?t:{default:t}}function l(t){return l="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},l(t)}function f(t,e){for(var n=0;n=200&&t.status<300}}])&&f(e.prototype,n),r&&f(e,r),Object.defineProperty(e,"prototype",{writable:!1}),t}();e.default=p},50630:(t,e,n)=>{"use strict";n(6550),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t,e){return!(!Array.isArray(t)&&"string"!=typeof t)&&-1!==t.indexOf(e)}},60301:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"includes",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(e,"isNil",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(e,"isObject",{enumerable:!0,get:function(){return o.default}}),Object.defineProperty(e,"omitEmptyStringAndNil",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(e,"omitNil",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(e,"omitProperty",{enumerable:!0,get:function(){return s.default}}),Object.defineProperty(e,"toNumber",{enumerable:!0,get:function(){return c.default}}),Object.defineProperty(e,"toSnakeCase",{enumerable:!0,get:function(){return d.default}}),Object.defineProperty(e,"toString",{enumerable:!0,get:function(){return l.default}});var r=f(n(50630)),i=f(n(65480)),o=f(n(63387)),a=f(n(91145)),u=f(n(75750)),s=f(n(66206)),c=f(n(30439)),d=f(n(27302)),l=f(n(78267));function f(t){return t&&t.__esModule?t:{default:t}}},57457:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return""===t}},32713:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return(0,r.default)(t)||(0,i.default)(t)};var r=o(n(57457)),i=o(n(65480));function o(t){return t&&t.__esModule?t:{default:t}}},65480:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return null==t}},63387:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}n(93942),n(70472),n(93270),n(38490),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return null!==t&&"object"===i(t)&&!Array.isArray(t)}},91145:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return(0,i.default)(t,r.default)};var r=o(n(32713)),i=o(n(66206));function o(t){return t&&t.__esModule?t:{default:t}}},75750:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return(0,i.default)(t,r.default)};var r=o(n(65480)),i=o(n(66206));function o(t){return t&&t.__esModule?t:{default:t}}},66206:(t,e,n)=>{"use strict";n(13722),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t,e){return(0,i.default)(t)?Object.keys(t).reduce((function(n,r){var i=t[r];return e(i)||(n[r]=i),n}),{}):t};var r,i=(r=n(63387))&&r.__esModule?r:{default:r}},30439:(t,e,n)=>{"use strict";n(83681),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return parseFloat(t)||0}},27302:(t,e,n)=>{"use strict";n(58443),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return"string"!=typeof t?t:t.replace(/([a-z\d])([A-Z]+)/g,"$1_$2").replace(/[-\s]+/g,"_").toLowerCase()}},78267:(t,e,n)=>{"use strict";n(99023),n(80226),n(40737),n(26667),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return"string"==typeof t?t:"number"!=typeof t||Number.isNaN(t)?"":t.toString()}},36438:(t,e,n)=>{"use strict";e.e=function(t){return i.default.create(t)};var r,i=(r=n(89538))&&r.__esModule?r:{default:r}},98834:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=u(n(14735)),o=u(n(15859)),a=u(n(92239));function u(t){return t&&t.__esModule?t:{default:t}}function s(t){return s="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},s(t)}function c(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(13751),o=n(7969),a=s(n(14088)),u=s(n(92239));function s(t){return t&&t.__esModule?t:{default:t}}function c(t){return c="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},c(t)}function d(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e,n){return(e=s(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function u(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(34745),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(26667),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=l(n(66534)),o=n(60301),a=l(n(45860)),u=l(n(31146)),s=l(n(8006)),c=l(n(80720)),d=l(n(85064));function l(t){return t&&t.__esModule?t:{default:t}}function f(t){return f="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},f(t)}function p(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(26667),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.PAYPAL_COMMERCE_VENMO=e.PAYPAL_COMMERCE_CREDIT_CARDS=e.PAYPAL_COMMERCE_CREDIT=e.PAYPAL_COMMERCE_ALTERNATIVE_METHODS=e.PAYPAL_COMMERCE=e.BRAINTREE_VISACHECKOUT=e.BRAINTREE_PAYPAL_CREDIT=e.BRAINTREE_PAYPAL=e.BRAINTREE_LOCAL_METHODS=e.BRAINTREE_GOOGLEPAY=e.BRAINTREE_ACH=e.BRAINTREE=void 0,e.BRAINTREE="braintree",e.BRAINTREE_PAYPAL="braintreepaypal",e.BRAINTREE_PAYPAL_CREDIT="braintreepaypalcredit",e.BRAINTREE_VISACHECKOUT="braintreevisacheckout",e.BRAINTREE_LOCAL_METHODS="braintreelocalmethods",e.BRAINTREE_GOOGLEPAY="googlepaybraintree",e.BRAINTREE_ACH="braintreeach",e.PAYPAL_COMMERCE="paypalcommerce",e.PAYPAL_COMMERCE_ALTERNATIVE_METHODS="paypalcommercealternativemethods",e.PAYPAL_COMMERCE_CREDIT="paypalcommercecredit",e.PAYPAL_COMMERCE_CREDIT_CARDS="paypalcommercecreditcards",e.PAYPAL_COMMERCE_VENMO="paypalcommercevenmo"},80720:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(9257),o=n(86879);function a(t){return a="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},a(t)}function u(t,e){for(var n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.PPSDK_CREDIT_CARD=e.MULTI_OPTION=e.CREDIT_CARD=void 0,e.CREDIT_CARD="credit-card",e.MULTI_OPTION="multi-option",e.PPSDK_CREDIT_CARD="card"},86202:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=c(n(14735)),o=n(7969),a=c(n(86130)),u=c(n(22147)),s=c(n(92239));function c(t){return t&&t.__esModule?t:{default:t}}function d(t){return d="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},d(t)}function l(t,e){for(var n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.SDK=e.OFFLINE=e.HOSTED=e.API=void 0,e.API="PAYMENT_TYPE_API",e.HOSTED="PAYMENT_TYPE_HOSTED",e.OFFLINE="PAYMENT_TYPE_OFFLINE",e.SDK="PAYMENT_TYPE_SDK"},22147:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301),o=n(9257);function a(t){return a="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},a(t)}function u(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function o(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(26667),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(95412),n(16368),n(34745),n(99023),n(40737),n(26667),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301),o=c(n(43085)),a=c(n(11106)),u=c(n(47752)),s=c(n(58332));function c(t){return t&&t.__esModule?t:{default:t}}function d(t){return d="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},d(t)}function l(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=u(n(66534)),o=n(60301),a=u(n(80720));function u(t){return t&&t.__esModule?t:{default:t}}function s(t){return s="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},s(t)}function c(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(26667),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(95412),n(16368),n(34745),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301),o=c(n(45873)),a=c(n(43026)),u=c(n(70170)),s=c(n(23393));function c(t){return t&&t.__esModule?t:{default:t}}function d(t){return d="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},d(t)}function l(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i,o=n(60301),a=(i=n(80720))&&i.__esModule?i:{default:i};function u(t){return u="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},u(t)}function s(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=s(n(14735)),o=n(99338),a=s(n(25682)),u=n(68109);function s(t){return t&&t.__esModule?t:{default:t}}function c(t){return c="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},c(t)}function d(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function o(t,e){for(var n=0;n{"use strict";n(95412),Object.defineProperty(e,"__esModule",{value:!0}),e.mapToHeaders=function(){var t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).authToken;return(0,r.omitNil)({Authorization:t})},e.mapToInstrumentPayload=function(){var t,e,n,o,a=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},u=a.providerName,s=a.defaultInstrument,c=(0,r.omitNil)({name:u});return(0,r.omitNil)({provider:c,credit_card:(t=a,e=t.creditCard,n=void 0===e?{}:e,o=(0,r.omitNil)(n.threeDSecure),(0,r.omitNil)({cardholder_name:n.cardholderName,number:n.number,month:n.month,year:n.year,verification_code:n.verificationCode,issue_month:n.issueMonth,issue_year:n.issueYear,issue_number:n.issueNumber,track_data:n.trackData,is_manual_entry:n.isManualEntry,icc_data:n.iccData,fallback_reason:n.fallbackReason,is_contactless:n.isContactless,encrypted_pin_cryptogram:n.encryptedPinCryptogram,encrypted_pin_ksn:n.encryptedPinKsn,three_d_secure:o})),billing_address:i(a.billingAddress),default_instrument:s})},e.mapToTrustedShippingAddressPayload=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Array.isArray(t.shippingAddress)?(0,r.omitNil)({shipping_addresses:t.shippingAddress.map((function(t){return i(t)}))}):(0,r.omitNil)({shipping_address:i(t.shippingAddress)})};var r=n(60301);function i(){var t,e,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=(t=n.provinceCode,e=n.province,(0,r.omitNil)({code:t,name:e}));return(0,r.omitNil)({address_line_1:n.addressLine1,address_line_2:n.addressLine2,city:n.city,company:n.company,country_code:n.countryCode,email:n.email,first_name:n.firstName,last_name:n.lastName,phone:n.phone,postal_code:n.postCode,state:i})}},119:(t,e,n)=>{"use strict";n(13722),Object.defineProperty(e,"__esModule",{value:!0});var r=n(87275),i=n(10874);e.default=function(t,e){var n=(e||{}).equalityCheck,o=void 0===n?i:n;return function(e,n){return Object.keys(t).reduce((function(i,a){var u,s=t[a],c=e?e[a]:void 0,d=s(c,n);return o(c,d)&&i?i:r.assign({},i,((u={})[a]=d,u))}),e||{})}}},50538:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(51725),n(38490),n(95412),n(16516),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0});var i=n(61699),o=n(87275),a=n(10874);e.default=function(){for(var t=[],e=0;e{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(61699),i=n(87275);e.default=function(t,e,n){if("string"!=typeof t||""===t)throw new Error("`type` must be a string");return r.__assign({type:t},i.omitBy({payload:e,meta:n},(function(t){return void 0===t})))}},17372:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(119),i=n(58941);e.default=function(t,e,n){return"function"==typeof t?new i.default(t,e,n):new i.default(r.default(t,{equalityCheck:n&&n.equalityCheck}),e,n)}},13304:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(61699),i=n(10520);e.default=function(t,e,n){return r.__assign({},i.default(t,e,n),{error:!0})}},58941:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(51725),n(38490),n(95412),n(40737),n(83823),n(10951),n(71806),n(5193),Object.defineProperty(e,"__esModule",{value:!0});var i=n(61699),o=n(87275),a=n(57469),u=n(11065),s=n(10874),c=n(35580),d=n(35643),l=n(25151),f=n(32168),p=function(){function t(t,e,n){void 0===e&&(e={});var r=this;this._reducer=t,this._options=i.__assign({actionTransformer:l.default,equalityCheck:s,shouldWarnMutation:!0,stateTransformer:f.default},n),this._state$=new a.BehaviorSubject(this._options.stateTransformer(e)),this._notification$=new a.Subject,this._dispatchers={},this._dispatchQueue$=new a.Subject,this._errors={},this._dispatchQueue$.pipe(u.mergeMap((function(t){return t.pipe(u.concatMap((function(t){return t})))})),u.filter((function(t){return!!t.type})),u.scan((function(t,e){return r._transformStates(t,e)}),{state:e,transformedState:this._state$.getValue()}),u.distinctUntilChanged((function(t,e){var n=t.state,i=e.state;return r._options.equalityCheck(n,i)})),u.map((function(t){return t.transformedState}))).subscribe(this._state$),this.dispatch({type:"INIT"})}return t.prototype.dispatch=function(t,e){return d.default(t)?this._dispatchObservableAction(t,e):"function"==typeof t?this._dispatchThunkAction(t,e):this._dispatchAction(t)},t.prototype.getState=function(){return this._state$.getValue()},t.prototype.notifyState=function(){this._notification$.next(this.getState())},t.prototype.subscribe=function(t){for(var e=this,n=[],i=1;i0&&(s=s.pipe(u.distinctUntilChanged((function(t,n){return a.every((function(r){return e._options.equalityCheck(r(t),r(n))}))})))),o&&!1===o.initial&&(s=s.pipe(u.skip(1)));var c=[s.subscribe(t),this._notification$.subscribe(t)];return function(){return c.forEach((function(t){return t.unsubscribe()}))}},t.prototype._transformStates=function(t,e){try{var n=!1===this._options.shouldWarnMutation?this._reducer(t.state,e):c.default(this._reducer(t.state,e),{equalityCheck:this._options.equalityCheck,previousValue:t.state});return{state:n,transformedState:this._options.stateTransformer(n)}}catch(n){return this._getDispatchError(e.meta&&e.meta.queueId).next(n),{state:t.state,transformedState:t.transformedState}}},t.prototype._dispatchAction=function(t){return this._dispatchObservableAction(t.error?a.throwError(t):a.of(t))},t.prototype._dispatchObservableAction=function(t,e){var n=this;return void 0===e&&(e={}),new Promise((function(r,i){var s=n._getDispatchError(e.queueId),c=n._options.actionTransformer(a.from(t).pipe(u.map((function(t){return e.queueId?o.merge({},t,{meta:{queueId:e.queueId}}):t}))));n._getDispatcher(e.queueId).next(a.from(c).pipe(u.map((function(t,e){return 0===e&&s.pipe(u.first()).subscribe(i),t.error&&i(t.payload),t})),u.catchError((function(t){return i(t instanceof Error?t:t.payload),a.of(t)})),u.tap({complete:function(){r(n.getState())}})))}))},t.prototype._dispatchThunkAction=function(t,e){var n=this;return void 0===e&&(e={}),this._dispatchObservableAction(a.defer((function(){return t(n)})),e)},t.prototype._getDispatcher=function(t){return void 0===t&&(t="default"),this._dispatchers[t]||(this._dispatchers[t]=new a.Subject,this._dispatchQueue$.next(this._dispatchers[t])),this._dispatchers[t]},t.prototype._getDispatchError=function(t){return void 0===t&&(t="default"),this._errors[t]||(this._errors[t]=new a.Subject),this._errors[t]},t}();e.default=p},35580:(t,e,n)=>{"use strict";n(95412),n(33409),n(60678),n(97814),Object.defineProperty(e,"__esModule",{value:!0});var r=n(87275),i=n(10874);e.default=function t(e,n){try{var o=n||{},a=o.equalityCheck,u=void 0===a?i:a,s=o.previousValue,c=void 0===s?null:s;return u(e,c)&&Object.isFrozen(c)?c:Object.isFrozen(e)||!Array.isArray(e)&&!r.isPlainObject(e)?e:Array.isArray(e)?Object.freeze(e.map((function(e,n){return t(e,{equalityCheck:u,previousValue:Array.isArray(c)?c[n]:void 0})}))):Object.freeze(Object.getOwnPropertyNames(e).reduce((function(n,r){return n[r]=t(e[r],{equalityCheck:u,previousValue:c&&c.hasOwnProperty(r)?c[r]:void 0}),n}),{}))}catch(t){if(t instanceof TypeError)return e;throw t}}},45346:(t,e,n)=>{"use strict";n(58941).default;var r=n(119);e.UY=r.default;var i=n(50538);e.g0=i.default;var o=n(10520);e.PH=o.default;var a=n(17372);e.Mg=a.default;var u=n(13304);e.bR=u.default;var s=n(35580);e._A=s.default},35643:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return"function"==typeof t.subscribe||"function"==typeof t.then}},25151:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return t}},32168:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return t}},78545:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(11077),i=n(51243);e.default=function(t){var e=new r.default;return new i.default(e,t)}},11077:(t,e,n)=>{"use strict";n(13722),n(71806),Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(){}return t.prototype.build=function(t,e,n){var r=this,i=document.createElement("form");return i.style.display="none",i.setAttribute("action",t),i.setAttribute("method","POST"),i.setAttribute("target",n||"_top"),Object.keys(e).forEach((function(t){var n=e[t];i.appendChild(r._createInput(n,t))})),i},t.prototype._createInput=function(t,e){var n=document.createElement("input");return n.setAttribute("name",e),n.setAttribute("type","hidden"),n.setAttribute("value",t),n},t}();e.default=r},51243:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(73543),i=function(){function t(t,e){this._formBuilder=t,this._options=e}return t.prototype.postForm=function(t,e,n,r){var i=this._formBuilder.build(this._prependHost(t),e,r);window.addEventListener("unload",(function t(){window.removeEventListener("unload",t),n&&n()})),document.body.appendChild(i),i.submit(),document.body.removeChild(i)},t.prototype._prependHost=function(t){return this._options&&this._options.host&&!r.isAbsoluteUrl(t)?r.joinPaths(this._options.host,t):t},t}();e.default=i},13751:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(78545);e.createFormPoster=r.default;var i=n(51243);e.FormPoster=i.default},73543:(t,e,n)=>{"use strict";n(58443),Object.defineProperty(e,"__esModule",{value:!0}),e.isAbsoluteUrl=function(t){return/^https?:\/\//.test(t)},e.joinPaths=function(t,e){return t.replace(/\/$/,"")+"/"+e.replace(/^\//,"")}},65934:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.isTerminalCacheKeyMap=function(t){return t.hasOwnProperty("cacheKey")},e.isRootCacheKeyMap=function(t){return t.hasOwnProperty("parentMap")}},67959:(t,e,n)=>{"use strict";n(6550),n(95412),n(16516),n(32345),Object.defineProperty(e,"__esModule",{value:!0});var r=n(61699),i=n(87275),o=r.__importDefault(n(10874)),a=n(65934),u=function(){function t(t){this._lastId=0,this._map={maps:[]},this._usedMaps=[],this._options=r.__assign({isEqual:o.default,maxSize:0,onExpire:i.noop},t)}return t.prototype.getKey=function(){for(var t=[],e=0;e{"use strict";var r=n(78497);e.HP=r.default,e.qe=r.memoizeOne},78497:(t,e,n)=>{"use strict";n(38490),n(34897),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0});var r=n(61699),i=r.__importDefault(n(84026)),o=r.__importDefault(n(10874)),a=r.__importDefault(n(67959));function u(t,e){var n=r.__assign({maxSize:0,isEqual:o.default},e),u=n.maxSize,s=n.isEqual,c=new Map,d=new a.default({isEqual:s,maxSize:u,onExpire:function(t){return c.delete(t)}}),l=i.default(t,(function(){for(var t=[],e=0;e{"use strict";n.d(e,{v:()=>i}),n(13722);var r=n(52163),i=function(){function t(){this._cache={}}return t.prototype.read=function(t,e){var n=this.getKey(t,e.params);return this._cache[n]||null},t.prototype.write=function(t,e,n){var r=this.getKey(t,e.params);this._cache[r]=n},t.prototype.getKey=function(t,e){return void 0===e&&(e={}),0===Object.keys(e).length?t:t+"?"+r.Pz(e)},t}()},78128:(t,e,n)=>{"use strict";n.d(e,{Z:()=>u});var r=n(53028),i=n(70613),o=n(44169),a=n(73185);function u(t){return new a.Z(new o.Z,new i.Z,r,t)}},98215:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i});var r=n(88287);function i(t){return new r.Z(t)}},14121:(t,e,n)=>{"use strict";n.r(e),n.d(e,{RequestSender:()=>o.Z,Timeout:()=>a.Z,createRequestSender:()=>r.Z,createTimeout:()=>i.Z});var r=n(78128),i=n(98215),o=n(73185),a=n(88287)},16927:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function i(t){return!!t&&("object"===r(t)||"function"==typeof t)&&"function"==typeof t.then}n.d(e,{Z:()=>i}),n(93942),n(70472),n(93270),n(38490),n(40737),n(10951),n(5193)},70613:(t,e,n)=>{"use strict";n.d(e,{Z:()=>u}),n(64668),n(58443),n(34500),n(25959);var r=n(61699),i=n(75457),o=/application\/(\w+\+)?json/,a=/application\/x-www-form-urlencoded/;const u=function(){function t(){}return t.prototype.toRequestBody=function(t){var e=t.headers?this._getHeader(t.headers,"Content-Type"):"";if(t.body){if(o.test(e))return JSON.stringify(t.body);if(a.test(e))return(0,i.Z)(t.body)}return t.body},t.prototype.toResponse=function(t){var e=this._parseResponseHeaders(t.getAllResponseHeaders());return{body:this._parseResponseBody("response"in t?t.response:t.responseText,e),headers:e,status:t.status,statusText:t.statusText}},t.prototype._parseResponseBody=function(t,e){var n=this._getHeader(e,"Content-Type");return t&&o.test(n)?JSON.parse(t):t},t.prototype._parseResponseHeaders=function(t){return(t?t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/):[]).reduce((function(t,e){var n,i=e.split(":"),o=(i.shift()||"").trim();return o?(0,r.__assign)((0,r.__assign)({},t),((n={})[o.toLowerCase()]=i.join(":").trim(),n)):t}),{})},t.prototype._getHeader=function(t,e){return t&&e&&(t[e]||t[e.toLowerCase()])||""},t}()},44169:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i}),n(51725),n(13722),n(71806);var r=n(52163);const i=function(){function t(){}return t.prototype.createRequest=function(t,e){var n=new XMLHttpRequest;return this._configureRequest(n,t,e),n},t.prototype._configureRequest=function(t,e,n){void 0===n&&(n={}),t.open(n.method||"GET",this._formatUrl(e,n.params,n.encodeParams),!0),n.headers&&this._configureRequestHeaders(t,n.headers),"boolean"==typeof n.credentials&&(t.withCredentials=n.credentials),"number"==typeof n.timeout&&(t.timeout=n.timeout)},t.prototype._configureRequestHeaders=function(t,e){Object.keys(e).filter((function(t){return null!==e[t]})).forEach((function(n){t.setRequestHeader(n,e[n])}))},t.prototype._formatUrl=function(t,e,n){return void 0===n&&(n=!0),e&&0!==Object.keys(e).length?t+"?"+r.Pz(e,{encode:n}):t},t}()},73185:(t,e,n)=>{"use strict";n.d(e,{Z:()=>c}),n(40737),n(83823),n(58443),n(34500);var r=n(61699),i=n(59947),o=n.n(i),a=n(90956),u=n(16927),s=n(88287);const c=function(){function t(t,e,n,r){void 0===r&&(r={}),this._requestFactory=t,this._payloadTransformer=e,this._cookie=n,this._options=r,this._cache=this._options.cache||new a.v}return t.prototype.sendRequest=function(t,e){var n=this,r=this._mergeDefaultOptions(t,e),i=this._getCachedRequest(t,r);if(i)return Promise.resolve(i);var o=this._requestFactory.createRequest(this._prependHost(t),r);return new Promise((function(e,i){var a=function(){var a=n._payloadTransformer.toResponse(o);a.status>=200&&a.status<300?(n._cacheRequest(t,r,a),e(a)):i(a)};o.onload=a,o.onerror=a,o.onabort=a,o.ontimeout=a,r.timeout instanceof s.Z&&(r.timeout.onComplete((function(){return o.abort()})),r.timeout.start()),(0,u.Z)(r.timeout)&&r.timeout.then((function(){return o.abort()})),o.send(n._payloadTransformer.toRequestBody(r))}))},t.prototype.get=function(t,e){return this.sendRequest(t,(0,r.__assign)((0,r.__assign)({},e),{method:"GET"}))},t.prototype.post=function(t,e){return this.sendRequest(t,(0,r.__assign)((0,r.__assign)({},e),{method:"POST"}))},t.prototype.put=function(t,e){return this.sendRequest(t,(0,r.__assign)((0,r.__assign)({},e),{method:"PUT"}))},t.prototype.patch=function(t,e){return this.sendRequest(t,(0,r.__assign)((0,r.__assign)({},e),{method:"PATCH"}))},t.prototype.delete=function(t,e){return this.sendRequest(t,(0,r.__assign)((0,r.__assign)({},e),{method:"DELETE"}))},t.prototype._mergeDefaultOptions=function(t,e){var n={credentials:!0,encodeParams:!0,headers:{Accept:"application/json, text/plain, */*"},method:"GET"},r=this._cookie.get("XSRF-TOKEN");return r&&n.headers&&!this._isAssetRequest(t,e)&&(n.headers["X-XSRF-TOKEN"]=r),e&&e.body&&n.headers&&(n.headers["Content-Type"]="application/json"),o()({},n,e)},t.prototype._prependHost=function(t){return!this._options.host||/^https?:\/\//.test(t)?t:this._options.host.replace(/\/$/,"")+"/"+t.replace(/^\//,"")},t.prototype._shouldCacheRequest=function(t){return"GET"===(t.method||"GET").toUpperCase()&&Boolean(t.cache)},t.prototype._getCachedRequest=function(t,e){return this._shouldCacheRequest(e)?this._cache.read(t,e):null},t.prototype._cacheRequest=function(t,e,n){this._shouldCacheRequest(e)&&this._cache.write(t,e,n)},t.prototype._isAssetRequest=function(t,e){return(!e||!e.method||"GET"===e.method.toUpperCase())&&/\.(png|gif|jpe?g|css|js|json|svg|html?)$/.test(t.split("?")[0])},t}()},88287:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r}),n(40737),n(83823);const r=function(){function t(t){var e=this;this._delay=t,this._resolve=function(){},this._promise=new Promise((function(t){e._resolve=t}))}return t.prototype.onComplete=function(t){this._promise.then(t)},t.prototype.complete=function(){this._resolve(),this._timeoutToken&&window.clearTimeout(this._timeoutToken)},t.prototype.start=function(){var t=this;this._delay&&(this._timeoutToken=window.setTimeout((function(){return t.complete()}),this._delay))},t}()},75457:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function i(t){return"object"!==r(t)||null===t?t:Object.keys(t).filter((function(e){return void 0!==t[e]})).map((function(e){var n=t[e];return"string"==typeof n?e+"="+encodeURIComponent(n):e+"="+encodeURIComponent(JSON.stringify(n)||"")})).join("&")}n.d(e,{Z:()=>i}),n(93942),n(70472),n(93270),n(51725),n(38490),n(64668),n(95412),n(13722),n(40737),n(10951),n(5193)},52163:(t,e,n)=>{"use strict";n(93942),n(70472),n(93270),n(88033),n(51725),n(6550),n(38490),n(64668),n(95412),n(16516),n(2934),n(99023),n(13722),n(40737),n(10951),n(58443),n(34500),n(25959),n(71806),n(5193);var r=n(29590),i=n(66534);n(99684);function o(t,e){return e.encode?e.strict?r(t):encodeURIComponent(t):t}e.Pz=function(t,e){!1===(e=i({encode:!0,strict:!0,arrayFormat:"none"},e)).sort&&(e.sort=function(){});var n=function(t){switch(t.arrayFormat){case"index":return function(e,n,r){return null===n?[o(e,t),"[",r,"]"].join(""):[o(e,t),"[",o(r,t),"]=",o(n,t)].join("")};case"bracket":return function(e,n){return null===n?o(e,t):[o(e,t),"[]=",o(n,t)].join("")};default:return function(e,n){return null===n?o(e,t):[o(e,t),"=",o(n,t)].join("")}}}(e);return t?Object.keys(t).sort(e.sort).map((function(r){var i=t[r];if(void 0===i)return"";if(null===i)return o(r,e);if(Array.isArray(i)){var a=[];return i.slice().forEach((function(t){void 0!==t&&a.push(n(r,t,a.length))})),a.join("&")}return o(r,e)+"="+o(i,e)})).filter((function(t){return t.length>0})).join("&"):""}},42372:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(){}return t.prototype.canSupportRel=function(t){var e=document.createElement("link");return!!(e.relList&&e.relList.supports&&e.relList.supports(t))},t}();e.default=n},30799:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(14121),i=n(42372),o=n(89379);e.default=function(){return new o.default(new i.default,r.createRequestSender())}},83116:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(14121),i=n(42372),o=n(41583);e.default=function(){return new o.default(new i.default,r.createRequestSender())}},57537:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=n(30799);e.default=function(){return r||(r=i.default()),r}},59136:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=n(83116);e.default=function(){return r||(r=i.default()),r}},56046:(t,e,n)=>{"use strict";n(89379).default;var r=n(30799);e.VD=r.default;var i=n(57537);e.Vr=i.default,n(41583).default,n(83116).default,n(59136).default},89379:(t,e,n)=>{"use strict";n(38490),n(95412),n(13722),n(40737),n(83823),n(10951),n(71806),n(5193),Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){this._browserSupport=t,this._requestSender=e,this._scripts={},this._preloadedScripts={}}return t.prototype.loadScript=function(t,e){var n=this;return this._scripts[t]||(this._scripts[t]=new Promise((function(r,i){var o=document.createElement("script"),a=e||{},u=a.async,s=void 0!==u&&u,c=a.attributes,d=void 0===c?{}:c;Object.keys(d).forEach((function(t){o.setAttribute(t,d[t])})),o.onload=function(){return r()},o.onreadystatechange=function(){return r()},o.onerror=function(e){delete n._scripts[t],i(e)},o.async=s,o.src=t,document.body.appendChild(o)}))),this._scripts[t]},t.prototype.loadScripts=function(t,e){var n=this;return Promise.all(t.map((function(t){return n.loadScript(t,e)}))).then((function(){}))},t.prototype.preloadScript=function(t,e){var n=this;return this._preloadedScripts[t]||(this._preloadedScripts[t]=new Promise((function(r,i){var o=(e||{}).prefetch,a=void 0!==o&&o?"prefetch":"preload";if(n._browserSupport.canSupportRel(a)){var u=document.createElement("link");u.as="script",u.rel=a,u.href=t,u.onload=function(){r()},u.onerror=function(){delete n._preloadedScripts[t],i()},document.head.appendChild(u)}else n._requestSender.get(t,{credentials:!1,headers:{Accept:"application/javascript"}}).then((function(){return r()})).catch(i)}))),this._preloadedScripts[t]},t.prototype.preloadScripts=function(t,e){var n=this;return Promise.all(t.map((function(t){return n.preloadScript(t,e)}))).then((function(){}))},t}();e.default=r},41583:(t,e,n)=>{"use strict";n(38490),n(95412),n(13722),n(40737),n(83823),n(10951),n(71806),n(5193),Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){this._browserSupport=t,this._requestSender=e,this._stylesheets={},this._preloadedStylesheets={}}return t.prototype.loadStylesheet=function(t,e){var n=this;return this._stylesheets[t]||(this._stylesheets[t]=new Promise((function(r,i){var o=document.createElement("link"),a=e||{},u=a.prepend,s=void 0!==u&&u,c=a.attributes,d=void 0===c?{}:c;Object.keys(d).forEach((function(t){o.setAttribute(t,d[t])})),o.onload=function(){return r()},o.onerror=function(e){delete n._stylesheets[t],i(e)},o.rel="stylesheet",o.href=t,s&&document.head.children[0]?document.head.insertBefore(o,document.head.children[0]):document.head.appendChild(o)}))),this._stylesheets[t]},t.prototype.loadStylesheets=function(t,e){var n=this;return Promise.all(t.map((function(t){return n.loadStylesheet(t,e)}))).then((function(){}))},t.prototype.preloadStylesheet=function(t,e){var n=this;return this._preloadedStylesheets[t]||(this._preloadedStylesheets[t]=new Promise((function(r,i){var o=(e||{}).prefetch,a=void 0!==o&&o,u=a?"prefetch":"preload";if(n._browserSupport.canSupportRel(u)){var s=document.createElement("link");s.as="style",s.rel=a?"prefetch":"preload",s.href=t,s.onload=function(){r()},s.onerror=function(e){delete n._preloadedStylesheets[t],i(e)},document.head.appendChild(s)}else n._requestSender.get(t,{credentials:!1,headers:{Accept:"text/css"}}).then((function(){return r()})).catch(i)}))),this._preloadedStylesheets[t]},t.prototype.preloadStylesheets=function(t,e){var n=this;return Promise.all(t.map((function(t){return n.preloadStylesheet(t,e)}))).then((function(){}))},t}();e.default=r},67061:(t,e,n)=>{"use strict";t.exports={number:n(9428),expirationDate:n(10370),expirationMonth:n(86075),expirationYear:n(34005),cvv:n(56348),postalCode:n(46887),creditCardType:n(56897)}},9428:(t,e,n)=>{"use strict";n(58443);var r=n(54442),i=n(56897);function o(t,e,n){return{card:t,isPotentiallyValid:e,isValid:n}}t.exports=function(t,e){var n,a,u,s,c;if(e=e||{},"number"==typeof t&&(t=String(t)),"string"!=typeof t)return o(null,!1,!1);if(t=t.replace(/\-|\s/g,""),!/^\d*$/.test(t))return o(null,!1,!1);if(0===(n=i(t)).length)return o(null,!1,!1);if(1!==n.length)return o(null,!0,!1);if(a=n[0],e.maxLength&&t.length>e.maxLength)return o(a,!1,!1);for(u=a.type===i.types.UNIONPAY&&!0!==e.luhnValidateUnionPay||r(t),c=Math.max.apply(null,a.lengths),e.maxLength&&(c=Math.min(e.maxLength,c)),s=0;s{"use strict";function e(t,e){return{isValid:t,isPotentiallyValid:e}}t.exports=function(t,n){return n=(n=n||3)instanceof Array?n:[n],"string"!=typeof t?e(!1,!1):/^\d*$/.test(t)?function(t,e){for(var n=0;nfunction(t){for(var e=3,n=0;ne?t[n]:e;return e}(n)?e(!1,!1):e(!0,!0):e(!1,!1)}},10370:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(38490),n(40737),n(10951),n(58443),n(5193);var i=n(30443),o=n(86075),a=n(34005);function u(t,e,n,r){return{isValid:t,isPotentiallyValid:e,month:n,year:r}}t.exports=function(t,e){var n,s,c,d;if("string"==typeof t)t=t.replace(/^(\d\d) (\d\d(\d\d)?)$/,"$1/$2"),n=i(t);else{if(null===t||"object"!==r(t))return u(!1,!1,null,null);n={month:String(t.month),year:String(t.year)}}if(s=o(n.month),c=a(n.year,e),s.isValid){if(c.isCurrentYear)return u(d=s.isValidForThisYear,d,n.month,n.year);if(c.isValid)return u(!0,!0,n.month,n.year)}return s.isPotentiallyValid&&c.isPotentiallyValid?u(!1,!0,null,null):u(!1,!1,null,null)}},86075:(t,e,n)=>{"use strict";function r(t,e,n){return{isValid:t,isPotentiallyValid:e,isValidForThisYear:n||!1}}n(50633),n(58443),t.exports=function(t){var e,n,i=(new Date).getMonth()+1;return"string"!=typeof t?r(!1,!1):""===t.replace(/\s/g,"")||"0"===t?r(!1,!0):/^\d*$/.test(t)?(e=parseInt(t,10),isNaN(t)?r(!1,!1):r(n=e>0&&e<13,n,n&&e>=i)):r(!1,!1)}},34005:(t,e,n)=>{"use strict";n(16516),n(99023),n(50633),n(58443);function r(t,e,n){return{isValid:t,isPotentiallyValid:e,isCurrentYear:n||!1}}t.exports=function(t,e){var n,i,o,a,u;return e=e||19,"string"!=typeof t?r(!1,!1):""===t.replace(/\s/g,"")?r(!1,!0):/^\d*$/.test(t)?(i=t.length)<2?r(!1,!0):(n=(new Date).getFullYear(),3===i?r(!1,t.slice(0,2)===String(n).slice(0,2)):i>4?r(!1,!1):(t=parseInt(t,10),o=Number(String(n).substr(2,2)),2===i?(u=o===t,a=t>=o&&t<=o+e):4===i&&(u=n===t,a=t>=n&&t<=n+e),r(a,a,u))):r(!1,!1)}},16108:(t,e,n)=>{"use strict";n(40737),n(26667),t.exports=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},54442:(t,e,n)=>{"use strict";n(50633),t.exports=function(t){for(var e,n=0,r=!1,i=t.length-1;i>=0;)e=parseInt(t.charAt(i),10),r&&(e*=2)>9&&(e=e%10+1),r=!r,n+=e,i--;return n%10==0}},30443:(t,e,n)=>{"use strict";n(64668),n(72590),n(16516),n(99023),n(34500);var r=n(34005),i=n(16108);t.exports=function(t){var e,n,o,a,u;return/^\d{4}-\d{1,2}$/.test(t)?t=t.split("-").reverse():/\//.test(t)?t=t.split(/\s*\/\s*/g):/\s/.test(t)&&(t=t.split(/ +/g)),i(t)?{month:t[0]||"",year:t.slice(1).join()}:(o=t,n=0===(u=Number(o[0]))?2:u>1||1===u&&Number(o[1])>2?1:1===u?(a=o.substr(1),r(a).isPotentiallyValid?1:2):5===o.length?1:o.length>5?2:1,{month:e=t.substr(0,n),year:t.substr(e.length)})}},46887:t=>{"use strict";function e(t,e){return{isValid:t,isPotentiallyValid:e}}t.exports=function(t,n){var r;return r=(n=n||{}).minLength||3,"string"!=typeof t?e(!1,!1):t.length{"use strict";n(6550),n(95412),n(32345),n(13722),n(71806);var r,i=n(18906),o=n(80826),a=n(16538),u=n(76754),s=n(25578),c={},d={VISA:"visa",MASTERCARD:"mastercard",AMERICAN_EXPRESS:"american-express",DINERS_CLUB:"diners-club",DISCOVER:"discover",JCB:"jcb",UNIONPAY:"unionpay",MAESTRO:"maestro",ELO:"elo",MIR:"mir",HIPER:"hiper",HIPERCARD:"hipercard"},l=[d.VISA,d.MASTERCARD,d.AMERICAN_EXPRESS,d.DINERS_CLUB,d.DISCOVER,d.JCB,d.UNIONPAY,d.MAESTRO,d.ELO,d.MIR,d.HIPER,d.HIPERCARD];function f(t){return c[t]||i[t]}function p(t,e){var n=r.indexOf(t);if(!e&&-1===n)throw new Error('"'+t+'" is not a supported card type.');return n}function h(t){var e,n=[];return u(t)?0===t.length?r.map((function(t){return o(f(t))})):(r.forEach((function(e){var r=f(e);s(t,r,n)})),(e=a(n))?[e]:n):[]}r=o(l),h.getTypeInfo=function(t){return o(f(t))},h.removeCard=function(t){var e=p(t);r.splice(e,1)},h.addCard=function(t){var e=p(t.type,!0);c[t.type]=t,-1===e&&r.push(t.type)},h.updateCard=function(t,e){var n,r=c[t]||i[t];if(!r)throw new Error('"'+t+'" is not a recognized type. Use `addCard` instead.');if(e.type&&r.type!==e.type)throw new Error("Cannot overwrite type parameter.");n=o(r,!0),Object.keys(n).forEach((function(t){e[t]&&(n[t]=e[t])})),c[n.type]=n},h.changeOrder=function(t,e){var n=p(t);r.splice(n,1),r.splice(e,0,t)},h.resetModifications=function(){r=o(l),c={}},h.types=d,t.exports=h},25578:(t,e,n)=>{"use strict";var r=n(80826),i=n(90013);t.exports=function(t,e,n){var o,a,u,s;for(o=0;o=u&&(s.matchStrength=u),n.push(s);break}}},18906:t=>{"use strict";t.exports={visa:{niceType:"Visa",type:"visa",patterns:[4],gaps:[4,8,12],lengths:[16,18,19],code:{name:"CVV",size:3}},mastercard:{niceType:"Mastercard",type:"mastercard",patterns:[[51,55],[2221,2229],[223,229],[23,26],[270,271],2720],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},"american-express":{niceType:"American Express",type:"american-express",patterns:[34,37],gaps:[4,10],lengths:[15],code:{name:"CID",size:4}},"diners-club":{niceType:"Diners Club",type:"diners-club",patterns:[[300,305],36,38,39],gaps:[4,10],lengths:[14,16,19],code:{name:"CVV",size:3}},discover:{niceType:"Discover",type:"discover",patterns:[6011,[644,649],65],gaps:[4,8,12],lengths:[16,19],code:{name:"CID",size:3}},jcb:{niceType:"JCB",type:"jcb",patterns:[2131,1800,[3528,3589]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVV",size:3}},unionpay:{niceType:"UnionPay",type:"unionpay",patterns:[620,[624,626],[62100,62182],[62184,62187],[62185,62197],[62200,62205],[622010,622999],622018,[622019,622999],[62207,62209],[622126,622925],[623,626],6270,6272,6276,[627700,627779],[627781,627799],[6282,6289],6291,6292,810,[8110,8131],[8132,8151],[8152,8163],[8164,8171]],gaps:[4,8,12],lengths:[14,15,16,17,18,19],code:{name:"CVN",size:3}},maestro:{niceType:"Maestro",type:"maestro",patterns:[493698,[5e5,506698],[506779,508999],[56,59],63,67,6],gaps:[4,8,12],lengths:[12,13,14,15,16,17,18,19],code:{name:"CVC",size:3}},elo:{niceType:"Elo",type:"elo",patterns:[401178,401179,438935,457631,457632,431274,451416,457393,504175,[506699,506778],[509e3,509999],627780,636297,636368,[650031,650033],[650035,650051],[650405,650439],[650485,650538],[650541,650598],[650700,650718],[650720,650727],[650901,650978],[651652,651679],[655e3,655019],[655021,655058]],gaps:[4,8,12],lengths:[16],code:{name:"CVE",size:3}},mir:{niceType:"Mir",type:"mir",patterns:[[2200,2204]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVP2",size:3}},hiper:{niceType:"Hiper",type:"hiper",patterns:[637095,637568,637599,637609,637612],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},hipercard:{niceType:"Hipercard",type:"hipercard",patterns:[606282],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}}}},80826:t=>{"use strict";t.exports=function(t){return t?JSON.parse(JSON.stringify(t)):null}},16538:(t,e,n)=>{"use strict";n(51725),t.exports=function(t){if(function(t){var e=t.filter((function(t){return t.matchStrength})).length;return e>0&&e===t.length}(t))return t.reduce((function(t,e){return t?t.matchStrength{"use strict";t.exports=function(t){return"string"==typeof t||t instanceof String}},90013:(t,e,n)=>{"use strict";n(50633),t.exports=function(t,e){return Array.isArray(e)?function(t,e,n){var r=String(e).length,i=t.substr(0,r),o=parseInt(i,10);return e=parseInt(String(e).substr(0,i.length),10),n=parseInt(String(n).substr(0,i.length),10),o>=e&&o<=n}(t,e[0],e[1]):function(t,e){return(e=String(e)).substring(0,t.length)===t.substring(0,e.length)}(t,e)}},99684:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(88033),n(38490),n(64668),n(16516),n(13722),n(40737),n(84868),n(26667),n(10951),n(15483),n(58443),n(5193);var i="%[a-f0-9]{2}",o=new RegExp("("+i+")|([^%]+?)","gi"),a=new RegExp("("+i+")+","gi");function u(t,e){try{return[decodeURIComponent(t.join(""))]}catch(t){}if(1===t.length)return t;e=e||1;var n=t.slice(0,e),r=t.slice(e);return Array.prototype.concat.call([],u(n),u(r))}function s(t){try{return decodeURIComponent(t)}catch(r){for(var e=t.match(o)||[],n=1;n{"use strict";n(93942);var r=n(59788),i=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable;function a(t,e,n){var o=e[n];if(null!=o){if(i.call(t,n)&&(void 0===t[n]||null===t[n]))throw new TypeError("Cannot convert undefined or null to object ("+n+")");i.call(t,n)&&r(o)?t[n]=u(Object(t[n]),e[n]):t[n]=o}}function u(t,e){if(t===e)return t;for(var n in e=Object(e))i.call(e,n)&&a(t,e,n);if(Object.getOwnPropertySymbols)for(var r=Object.getOwnPropertySymbols(e),u=0;u{"use strict";n(6550),n(13722),t.exports=function(t,e){for(var n={},r=Object.keys(t),i=Array.isArray(e),o=0;o{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(38490),n(40737),n(10951),n(5193),t.exports=function(t){var e=r(t);return null!==t&&("object"===e||"function"===e)}},53028:(t,e,n)=>{function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(38490),n(64668),n(16516),n(40737),n(10951),n(58443),n(34500),n(5193),function(n){var i;if("function"==typeof define&&define.amd&&(define(n),i=!0),"object"===r(e)&&(t.exports=n(),i=!0),!i){var o=window.Cookies,a=window.Cookies=n();a.noConflict=function(){return window.Cookies=o,a}}}((function(){function t(){for(var t=0,e={};t{function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(38490),n(95412),n(32345),n(40737),n(84868),n(26667),n(10951),n(58443),n(5193);var i,o="Expected a function",a="__lodash_hash_undefined__",u="[object Function]",s="[object GeneratorFunction]",c=/^\[object .+?Constructor\]$/,d="object"==(void 0===n.g?"undefined":r(n.g))&&n.g&&n.g.Object===Object&&n.g,l="object"==("undefined"==typeof self?"undefined":r(self))&&self&&self.Object===Object&&self,f=d||l||Function("return this")(),p=Array.prototype,h=Function.prototype,y=Object.prototype,m=f["__core-js_shared__"],v=(i=/[^.]+$/.exec(m&&m.keys&&m.keys.IE_PROTO||""))?"Symbol(src)_1."+i:"",g=h.toString,_=y.hasOwnProperty,b=y.toString,S=RegExp("^"+g.call(_).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),w=p.splice,C=x(f,"Map"),E=x(Object,"create");function I(t){var e=-1,n=t?t.length:0;for(this.clear();++e-1},P.prototype.set=function(t,e){var n=this.__data__,r=O(n,t);return r<0?n.push([t,e]):n[r][1]=e,this},A.prototype.clear=function(){this.__data__={hash:new I,map:new(C||P),string:new I}},A.prototype.delete=function(t){return T(this,t).delete(t)},A.prototype.get=function(t){return T(this,t).get(t)},A.prototype.has=function(t){return T(this,t).has(t)},A.prototype.set=function(t,e){return T(this,t).set(t,e),this},R.Cache=A,t.exports=R},59947:(t,e,n)=>{function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}t=n.nmd(t),n(93942),n(70472),n(93270),n(38490),n(95412),n(16516),n(32345),n(71582),n(40737),n(84868),n(26667),n(10951),n(58443),n(5193);var i="__lodash_hash_undefined__",o=9007199254740991,a="[object Arguments]",u="[object AsyncFunction]",s="[object Function]",c="[object GeneratorFunction]",d="[object Null]",l="[object Object]",f="[object Proxy]",p="[object Undefined]",h=/^\[object .+?Constructor\]$/,y=/^(?:0|[1-9]\d*)$/,m={};m["[object Float32Array]"]=m["[object Float64Array]"]=m["[object Int8Array]"]=m["[object Int16Array]"]=m["[object Int32Array]"]=m["[object Uint8Array]"]=m["[object Uint8ClampedArray]"]=m["[object Uint16Array]"]=m["[object Uint32Array]"]=!0,m[a]=m["[object Array]"]=m["[object ArrayBuffer]"]=m["[object Boolean]"]=m["[object DataView]"]=m["[object Date]"]=m["[object Error]"]=m[s]=m["[object Map]"]=m["[object Number]"]=m[l]=m["[object RegExp]"]=m["[object Set]"]=m["[object String]"]=m["[object WeakMap]"]=!1;var v,g,_,b="object"==(void 0===n.g?"undefined":r(n.g))&&n.g&&n.g.Object===Object&&n.g,S="object"==("undefined"==typeof self?"undefined":r(self))&&self&&self.Object===Object&&self,w=b||S||Function("return this")(),C="object"==r(e)&&e&&!e.nodeType&&e,E=C&&"object"==r(t)&&t&&!t.nodeType&&t,I=E&&E.exports===C,P=I&&b.process,A=function(){try{return E&&E.require&&E.require("util").types||P&&P.binding&&P.binding("util")}catch(t){}}(),O=A&&A.isTypedArray,T=Array.prototype,x=Function.prototype,R=Object.prototype,k=w["__core-js_shared__"],M=x.toString,N=R.hasOwnProperty,D=(v=/[^.]+$/.exec(k&&k.keys&&k.keys.IE_PROTO||""))?"Symbol(src)_1."+v:"",L=R.toString,z=M.call(Object),j=RegExp("^"+M.call(N).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),U=I?w.Buffer:void 0,F=w.Symbol,q=w.Uint8Array,B=(U&&U.allocUnsafe,g=Object.getPrototypeOf,_=Object,function(t){return g(_(t))}),G=Object.create,V=R.propertyIsEnumerable,Y=T.splice,H=F?F.toStringTag:void 0,W=function(){try{var t=ht(Object,"defineProperty");return t({},"",{}),t}catch(t){}}(),K=U?U.isBuffer:void 0,Z=Math.max,$=Date.now,J=ht(w,"Map"),Q=ht(Object,"create"),X=function(){function t(){}return function(e){if(!Pt(e))return{};if(G)return G(e);t.prototype=e;var n=new t;return t.prototype=void 0,n}}();function tt(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e-1},et.prototype.set=function(t,e){var n=this.__data__,r=at(n,t);return r<0?(++this.size,n.push([t,e])):n[r][1]=e,this},nt.prototype.clear=function(){this.size=0,this.__data__={hash:new tt,map:new(J||et),string:new tt}},nt.prototype.delete=function(t){var e=pt(this,t).delete(t);return this.size-=e?1:0,e},nt.prototype.get=function(t){return pt(this,t).get(t)},nt.prototype.has=function(t){return pt(this,t).has(t)},nt.prototype.set=function(t,e){var n=pt(this,t),r=n.size;return n.set(t,e),this.size+=n.size==r?0:1,this},rt.prototype.clear=function(){this.__data__=new et,this.size=0},rt.prototype.delete=function(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n},rt.prototype.get=function(t){return this.__data__.get(t)},rt.prototype.has=function(t){return this.__data__.has(t)},rt.prototype.set=function(t,e){var n=this.__data__;if(n instanceof et){var r=n.__data__;if(!J||r.length<199)return r.push([t,e]),this.size=++n.size,this;n=this.__data__=new nt(r)}return n.set(t,e),this.size=n.size,this};var st=function(t,e,n){for(var r=-1,i=Object(t),o=n(t),a=o.length;a--;){var u=o[++r];if(!1===e(i[u],u,i))break}return t};function ct(t){return null==t?void 0===t?p:d:H&&H in Object(t)?function(t){var e=N.call(t,H),n=t[H];try{t[H]=void 0;var r=!0}catch(t){}var i=L.call(t);return r&&(e?t[H]=n:delete t[H]),i}(t):function(t){return L.call(t)}(t)}function dt(t){return At(t)&&ct(t)==a}function lt(t,e,n,r,i){t!==e&&st(e,(function(o,a){if(i||(i=new rt),Pt(o))!function(t,e,n,r,i,o,a){var u=vt(t,n),s=vt(e,n),c=a.get(s);if(c)it(t,n,c);else{var d,f,p,h,y,m=o?o(u,s,n+"",t,e,a):void 0,v=void 0===m;if(v){var g=St(s),_=!g&&Ct(s),b=!g&&!_&&Ot(s);m=s,g||_||b?St(u)?m=u:At(y=u)&&wt(y)?m=function(t,e){var n=-1,r=t.length;for(e||(e=Array(r));++n-1&&t%1==0&&t0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(ft);function _t(t,e){return t===e||t!=t&&e!=e}var bt=dt(function(){return arguments}())?dt:function(t){return At(t)&&N.call(t,"callee")&&!V.call(t,"callee")},St=Array.isArray;function wt(t){return null!=t&&It(t.length)&&!Et(t)}var Ct=K||function(){return!1};function Et(t){if(!Pt(t))return!1;var e=ct(t);return e==s||e==c||e==u||e==f}function It(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=o}function Pt(t){var e=r(t);return null!=t&&("object"==e||"function"==e)}function At(t){return null!=t&&"object"==r(t)}var Ot=O?function(t){return function(e){return t(e)}}(O):function(t){return At(t)&&It(t.length)&&!!m[ct(t)]};function Tt(t){return wt(t)?function(t,e){var n=St(t),r=!n&&bt(t),i=!n&&!r&&Ct(t),o=!n&&!r&&!i&&Ot(t),a=n||r||i||o,u=a?function(t,e){for(var n=-1,r=Array(t);++n1?e[i-1]:void 0,a=i>2?e[2]:void 0;for(o=xt.length>3&&"function"==typeof o?(i--,o):void 0,a&&function(t,e,n){if(!Pt(n))return!1;var i=r(e);return!!("number"==i?wt(n)&&yt(e,n.length):"string"==i&&e in n)&&_t(n[e],t)}(e[0],e[1],a)&&(o=i<3?void 0:o,i=1),t=Object(t);++n"']/g,W=RegExp(Y.source),K=RegExp(H.source),Z=/<%-([\s\S]+?)%>/g,$=/<%([\s\S]+?)%>/g,J=/<%=([\s\S]+?)%>/g,Q=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,X=/^\w*$/,tt=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,et=/[\\^$.*+?()[\]{}|]/g,nt=RegExp(et.source),rt=/^\s+/,it=/\s/,ot=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,at=/\{\n\/\* \[wrapped with (.+)\] \*/,ut=/,? & /,st=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,ct=/[()=,{}\[\]\/\s]/,dt=/\\(\\)?/g,lt=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,ft=/\w*$/,pt=/^[-+]0x[0-9a-f]+$/i,ht=/^0b[01]+$/i,yt=/^\[object .+?Constructor\]$/,mt=/^0o[0-7]+$/i,vt=/^(?:0|[1-9]\d*)$/,gt=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,_t=/($^)/,bt=/['\n\r\u2028\u2029\\]/g,St="\\ud800-\\udfff",wt="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",Ct="\\u2700-\\u27bf",Et="a-z\\xdf-\\xf6\\xf8-\\xff",It="A-Z\\xc0-\\xd6\\xd8-\\xde",Pt="\\ufe0e\\ufe0f",At="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",Ot="["+St+"]",Tt="["+At+"]",xt="["+wt+"]",Rt="\\d+",kt="["+Ct+"]",Mt="["+Et+"]",Nt="[^"+St+At+Rt+Ct+Et+It+"]",Dt="\\ud83c[\\udffb-\\udfff]",Lt="[^"+St+"]",zt="(?:\\ud83c[\\udde6-\\uddff]){2}",jt="[\\ud800-\\udbff][\\udc00-\\udfff]",Ut="["+It+"]",Ft="\\u200d",qt="(?:"+Mt+"|"+Nt+")",Bt="(?:"+Ut+"|"+Nt+")",Gt="(?:['’](?:d|ll|m|re|s|t|ve))?",Vt="(?:['’](?:D|LL|M|RE|S|T|VE))?",Yt="(?:"+xt+"|"+Dt+")?",Ht="["+Pt+"]?",Wt=Ht+Yt+"(?:"+Ft+"(?:"+[Lt,zt,jt].join("|")+")"+Ht+Yt+")*",Kt="(?:"+[kt,zt,jt].join("|")+")"+Wt,Zt="(?:"+[Lt+xt+"?",xt,zt,jt,Ot].join("|")+")",$t=RegExp("['’]","g"),Jt=RegExp(xt,"g"),Qt=RegExp(Dt+"(?="+Dt+")|"+Zt+Wt,"g"),Xt=RegExp([Ut+"?"+Mt+"+"+Gt+"(?="+[Tt,Ut,"$"].join("|")+")",Bt+"+"+Vt+"(?="+[Tt,Ut+qt,"$"].join("|")+")",Ut+"?"+qt+"+"+Gt,Ut+"+"+Vt,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",Rt,Kt].join("|"),"g"),te=RegExp("["+Ft+St+wt+Pt+"]"),ee=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,ne=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],re=-1,ie={};ie[M]=ie[N]=ie[D]=ie[L]=ie[z]=ie[j]=ie[U]=ie[F]=ie[q]=!0,ie[y]=ie[m]=ie[R]=ie[v]=ie[k]=ie[g]=ie[_]=ie[b]=ie[w]=ie[C]=ie[E]=ie[P]=ie[A]=ie[O]=ie[x]=!1;var oe={};oe[y]=oe[m]=oe[R]=oe[k]=oe[v]=oe[g]=oe[M]=oe[N]=oe[D]=oe[L]=oe[z]=oe[w]=oe[C]=oe[E]=oe[P]=oe[A]=oe[O]=oe[T]=oe[j]=oe[U]=oe[F]=oe[q]=!0,oe[_]=oe[b]=oe[x]=!1;var ae={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},ue=parseFloat,se=parseInt,ce="object"==(void 0===n.g?"undefined":r(n.g))&&n.g&&n.g.Object===Object&&n.g,de="object"==("undefined"==typeof self?"undefined":r(self))&&self&&self.Object===Object&&self,le=ce||de||Function("return this")(),fe="object"==r(e)&&e&&!e.nodeType&&e,pe=fe&&"object"==r(t)&&t&&!t.nodeType&&t,he=pe&&pe.exports===fe,ye=he&&ce.process,me=function(){try{return pe&&pe.require&&pe.require("util").types||ye&&ye.binding&&ye.binding("util")}catch(t){}}(),ve=me&&me.isArrayBuffer,ge=me&&me.isDate,_e=me&&me.isMap,be=me&&me.isRegExp,Se=me&&me.isSet,we=me&&me.isTypedArray;function Ce(t,e,n){switch(n.length){case 0:return t.call(e);case 1:return t.call(e,n[0]);case 2:return t.call(e,n[0],n[1]);case 3:return t.call(e,n[0],n[1],n[2])}return t.apply(e,n)}function Ee(t,e,n,r){for(var i=-1,o=null==t?0:t.length;++i-1}function xe(t,e,n){for(var r=-1,i=null==t?0:t.length;++r-1;);return n}function Xe(t,e){for(var n=t.length;n--&&Ue(e,t[n],0)>-1;);return n}var tn=Ve({À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"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:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"}),en=Ve({"&":"&","<":"<",">":">",'"':""","'":"'"});function nn(t){return"\\"+ae[t]}function rn(t){return te.test(t)}function on(t){var e=-1,n=Array(t.size);return t.forEach((function(t,r){n[++e]=[r,t]})),n}function an(t,e){return function(n){return t(e(n))}}function un(t,e){for(var n=-1,r=t.length,i=0,o=[];++n",""":'"',"'":"'"}),hn=function t(e){var n,it=(e=null==e?le:hn.defaults(le.Object(),e,hn.pick(le,ne))).Array,St=e.Date,wt=e.Error,Ct=e.Function,Et=e.Math,It=e.Object,Pt=e.RegExp,At=e.String,Ot=e.TypeError,Tt=it.prototype,xt=Ct.prototype,Rt=It.prototype,kt=e["__core-js_shared__"],Mt=xt.toString,Nt=Rt.hasOwnProperty,Dt=0,Lt=(n=/[^.]+$/.exec(kt&&kt.keys&&kt.keys.IE_PROTO||""))?"Symbol(src)_1."+n:"",zt=Rt.toString,jt=Mt.call(It),Ut=le._,Ft=Pt("^"+Mt.call(Nt).replace(et,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),qt=he?e.Buffer:i,Bt=e.Symbol,Gt=e.Uint8Array,Vt=qt?qt.allocUnsafe:i,Yt=an(It.getPrototypeOf,It),Ht=It.create,Wt=Rt.propertyIsEnumerable,Kt=Tt.splice,Zt=Bt?Bt.isConcatSpreadable:i,Qt=Bt?Bt.iterator:i,te=Bt?Bt.toStringTag:i,ae=function(){try{var t=co(It,"defineProperty");return t({},"",{}),t}catch(t){}}(),ce=e.clearTimeout!==le.clearTimeout&&e.clearTimeout,de=St&&St.now!==le.Date.now&&St.now,fe=e.setTimeout!==le.setTimeout&&e.setTimeout,pe=Et.ceil,ye=Et.floor,me=It.getOwnPropertySymbols,Le=qt?qt.isBuffer:i,Ve=e.isFinite,yn=Tt.join,mn=an(It.keys,It),vn=Et.max,gn=Et.min,_n=St.now,bn=e.parseInt,Sn=Et.random,wn=Tt.reverse,Cn=co(e,"DataView"),En=co(e,"Map"),In=co(e,"Promise"),Pn=co(e,"Set"),An=co(e,"WeakMap"),On=co(It,"create"),Tn=An&&new An,xn={},Rn=jo(Cn),kn=jo(En),Mn=jo(In),Nn=jo(Pn),Dn=jo(An),Ln=Bt?Bt.prototype:i,zn=Ln?Ln.valueOf:i,jn=Ln?Ln.toString:i;function Un(t){if(eu(t)&&!Va(t)&&!(t instanceof Gn)){if(t instanceof Bn)return t;if(Nt.call(t,"__wrapped__"))return Uo(t)}return new Bn(t)}var Fn=function(){function t(){}return function(e){if(!tu(e))return{};if(Ht)return Ht(e);t.prototype=e;var n=new t;return t.prototype=i,n}}();function qn(){}function Bn(t,e){this.__wrapped__=t,this.__actions__=[],this.__chain__=!!e,this.__index__=0,this.__values__=i}function Gn(t){this.__wrapped__=t,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=p,this.__views__=[]}function Vn(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e=e?t:e)),t}function ur(t,e,n,r,o,a){var u,s=1&e,c=2&e,d=4&e;if(n&&(u=o?n(t,r,o,a):n(t)),u!==i)return u;if(!tu(t))return t;var l=Va(t);if(l){if(u=function(t){var e=t.length,n=new t.constructor(e);return e&&"string"==typeof t[0]&&Nt.call(t,"index")&&(n.index=t.index,n.input=t.input),n}(t),!s)return Ai(t,u)}else{var f=po(t),p=f==b||f==S;if(Ka(t))return Si(t,s);if(f==E||f==y||p&&!o){if(u=c||p?{}:yo(t),!s)return c?function(t,e){return Oi(t,fo(t),e)}(t,function(t,e){return t&&Oi(e,ku(e),t)}(u,t)):function(t,e){return Oi(t,lo(t),e)}(t,rr(u,t))}else{if(!oe[f])return o?t:{};u=function(t,e,n){var r,i=t.constructor;switch(e){case R:return wi(t);case v:case g:return new i(+t);case k:return function(t,e){var n=e?wi(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.byteLength)}(t,n);case M:case N:case D:case L:case z:case j:case U:case F:case q:return Ci(t,n);case w:return new i;case C:case O:return new i(t);case P:return function(t){var e=new t.constructor(t.source,ft.exec(t));return e.lastIndex=t.lastIndex,e}(t);case A:return new i;case T:return r=t,zn?It(zn.call(r)):{}}}(t,f,s)}}a||(a=new Kn);var h=a.get(t);if(h)return h;a.set(t,u),au(t)?t.forEach((function(r){u.add(ur(r,e,n,r,t,a))})):nu(t)&&t.forEach((function(r,i){u.set(i,ur(r,e,n,i,t,a))}));var m=l?i:(d?c?no:eo:c?ku:Ru)(t);return Ie(m||t,(function(r,i){m&&(r=t[i=r]),tr(u,i,ur(r,e,n,i,t,a))})),u}function sr(t,e,n){var r=n.length;if(null==t)return!r;for(t=It(t);r--;){var o=n[r],a=e[o],u=t[o];if(u===i&&!(o in t)||!a(u))return!1}return!0}function cr(t,e,n){if("function"!=typeof t)throw new Ot(o);return To((function(){t.apply(i,n)}),e)}function dr(t,e,n,r){var i=-1,o=Te,a=!0,u=t.length,s=[],c=e.length;if(!u)return s;n&&(e=Re(e,Ze(n))),r?(o=xe,a=!1):e.length>=200&&(o=Je,a=!1,e=new Wn(e));t:for(;++i-1},Yn.prototype.set=function(t,e){var n=this.__data__,r=er(n,t);return r<0?(++this.size,n.push([t,e])):n[r][1]=e,this},Hn.prototype.clear=function(){this.size=0,this.__data__={hash:new Vn,map:new(En||Yn),string:new Vn}},Hn.prototype.delete=function(t){var e=uo(this,t).delete(t);return this.size-=e?1:0,e},Hn.prototype.get=function(t){return uo(this,t).get(t)},Hn.prototype.has=function(t){return uo(this,t).has(t)},Hn.prototype.set=function(t,e){var n=uo(this,t),r=n.size;return n.set(t,e),this.size+=n.size==r?0:1,this},Wn.prototype.add=Wn.prototype.push=function(t){return this.__data__.set(t,a),this},Wn.prototype.has=function(t){return this.__data__.has(t)},Kn.prototype.clear=function(){this.__data__=new Yn,this.size=0},Kn.prototype.delete=function(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n},Kn.prototype.get=function(t){return this.__data__.get(t)},Kn.prototype.has=function(t){return this.__data__.has(t)},Kn.prototype.set=function(t,e){var n=this.__data__;if(n instanceof Yn){var r=n.__data__;if(!En||r.length<199)return r.push([t,e]),this.size=++n.size,this;n=this.__data__=new Hn(r)}return n.set(t,e),this.size=n.size,this};var lr=Ri(_r),fr=Ri(br,!0);function pr(t,e){var n=!0;return lr(t,(function(t,r,i){return n=!!e(t,r,i)})),n}function hr(t,e,n){for(var r=-1,o=t.length;++r0&&n(u)?e>1?mr(u,e-1,n,r,i):ke(i,u):r||(i[i.length]=u)}return i}var vr=ki(),gr=ki(!0);function _r(t,e){return t&&vr(t,e,Ru)}function br(t,e){return t&&gr(t,e,Ru)}function Sr(t,e){return Oe(e,(function(e){return Ja(t[e])}))}function wr(t,e){for(var n=0,r=(e=vi(e,t)).length;null!=t&&ne}function Pr(t,e){return null!=t&&Nt.call(t,e)}function Ar(t,e){return null!=t&&e in It(t)}function Or(t,e,n){for(var r=n?xe:Te,o=t[0].length,a=t.length,u=a,s=it(a),c=1/0,d=[];u--;){var l=t[u];u&&e&&(l=Re(l,Ze(e))),c=gn(l.length,c),s[u]=!n&&(e||o>=120&&l.length>=120)?new Wn(u&&l):i}l=t[0];var f=-1,p=s[0];t:for(;++f=u?s:s*("desc"==n[r]?-1:1)}return t.index-e.index}(t,e,n)}));r--;)t[r]=t[r].value;return t}(i)}function Gr(t,e,n){for(var r=-1,i=e.length,o={};++r-1;)u!==t&&Kt.call(u,s,1),Kt.call(t,s,1);return t}function Yr(t,e){for(var n=t?e.length:0,r=n-1;n--;){var i=e[n];if(n==r||i!==o){var o=i;vo(i)?Kt.call(t,i,1):ci(t,i)}}return t}function Hr(t,e){return t+ye(Sn()*(e-t+1))}function Wr(t,e){var n="";if(!t||e<1||e>l)return n;do{e%2&&(n+=t),(e=ye(e/2))&&(t+=t)}while(e);return n}function Kr(t,e){return xo(Io(t,e,rs),t+"")}function Zr(t){return $n(Fu(t))}function $r(t,e){var n=Fu(t);return Mo(n,ar(e,0,n.length))}function Jr(t,e,n,r){if(!tu(t))return t;for(var o=-1,a=(e=vi(e,t)).length,u=a-1,s=t;null!=s&&++oi?0:i+e),(n=n>i?i:n)<0&&(n+=i),i=e>n?0:n-e>>>0,e>>>=0;for(var o=it(i);++r>>1,a=t[o];null!==a&&!su(a)&&(n?a<=e:a=200){var c=e?null:Wi(t);if(c)return sn(c);a=!1,i=Je,s=new Wn}else s=e?[]:u;t:for(;++r=r?t:ei(t,e,n)}var bi=ce||function(t){return le.clearTimeout(t)};function Si(t,e){if(e)return t.slice();var n=t.length,r=Vt?Vt(n):new t.constructor(n);return t.copy(r),r}function wi(t){var e=new t.constructor(t.byteLength);return new Gt(e).set(new Gt(t)),e}function Ci(t,e){var n=e?wi(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.length)}function Ei(t,e){if(t!==e){var n=t!==i,r=null===t,o=t==t,a=su(t),u=e!==i,s=null===e,c=e==e,d=su(e);if(!s&&!d&&!a&&t>e||a&&u&&c&&!s&&!d||r&&u&&c||!n&&c||!o)return 1;if(!r&&!a&&!d&&t1?n[o-1]:i,u=o>2?n[2]:i;for(a=t.length>3&&"function"==typeof a?(o--,a):i,u&&go(n[0],n[1],u)&&(a=o<3?i:a,o=1),e=It(e);++r-1?o[a?e[u]:u]:i}}function zi(t){return to((function(e){var n=e.length,r=n,a=Bn.prototype.thru;for(t&&e.reverse();r--;){var u=e[r];if("function"!=typeof u)throw new Ot(o);if(a&&!s&&"wrapper"==io(u))var s=new Bn([],!0)}for(r=s?r:n;++r1&&_.reverse(),f&&ds))return!1;var d=a.get(t),l=a.get(e);if(d&&l)return d==e&&l==t;var f=-1,p=!0,h=2&n?new Wn:i;for(a.set(t,e),a.set(e,t);++f-1&&t%1==0&&t1?"& ":"")+e[r],e=e.join(n>2?", ":" "),t.replace(ot,"{\n/* [wrapped with "+e+"] */\n")}(r,function(t,e){return Ie(h,(function(n){var r="_."+n[0];e&n[1]&&!Te(t,r)&&t.push(r)})),t.sort()}(function(t){var e=t.match(at);return e?e[1].split(ut):[]}(r),n)))}function ko(t){var e=0,n=0;return function(){var r=_n(),o=16-(r-n);if(n=r,o>0){if(++e>=800)return arguments[0]}else e=0;return t.apply(i,arguments)}}function Mo(t,e){var n=-1,r=t.length,o=r-1;for(e=e===i?r:e;++n1?t[e-1]:i;return n="function"==typeof n?(t.pop(),n):i,oa(t,n)}));function fa(t){var e=Un(t);return e.__chain__=!0,e}function pa(t,e){return e(t)}var ha=to((function(t){var e=t.length,n=e?t[0]:0,r=this.__wrapped__,o=function(e){return or(e,t)};return!(e>1||this.__actions__.length)&&r instanceof Gn&&vo(n)?((r=r.slice(n,+n+(e?1:0))).__actions__.push({func:pa,args:[o],thisArg:i}),new Bn(r,this.__chain__).thru((function(t){return e&&!t.length&&t.push(i),t}))):this.thru(o)})),ya=Ti((function(t,e,n){Nt.call(t,n)?++t[n]:ir(t,n,1)})),ma=Li(Go),va=Li(Vo);function ga(t,e){return(Va(t)?Ie:lr)(t,ao(e,3))}function _a(t,e){return(Va(t)?Pe:fr)(t,ao(e,3))}var ba=Ti((function(t,e,n){Nt.call(t,n)?t[n].push(e):ir(t,n,[e])})),Sa=Kr((function(t,e,n){var r=-1,i="function"==typeof e,o=Ha(t)?it(t.length):[];return lr(t,(function(t){o[++r]=i?Ce(e,t,n):Tr(t,e,n)})),o})),wa=Ti((function(t,e,n){ir(t,n,e)}));function Ca(t,e){return(Va(t)?Re:zr)(t,ao(e,3))}var Ea=Ti((function(t,e,n){t[n?0:1].push(e)}),(function(){return[[],[]]})),Ia=Kr((function(t,e){if(null==t)return[];var n=e.length;return n>1&&go(t,e[0],e[1])?e=[]:n>2&&go(e[0],e[1],e[2])&&(e=[e[0]]),Br(t,mr(e,1),[])})),Pa=de||function(){return le.Date.now()};function Aa(t,e,n){return e=n?i:e,e=t&&null==e?t.length:e,Zi(t,c,i,i,i,i,e)}function Oa(t,e){var n;if("function"!=typeof e)throw new Ot(o);return t=hu(t),function(){return--t>0&&(n=e.apply(this,arguments)),t<=1&&(e=i),n}}var Ta=Kr((function(t,e,n){var r=1;if(n.length){var i=un(n,oo(Ta));r|=s}return Zi(t,r,e,n,i)})),xa=Kr((function(t,e,n){var r=3;if(n.length){var i=un(n,oo(xa));r|=s}return Zi(e,r,t,n,i)}));function Ra(t,e,n){var r,a,u,s,c,d,l=0,f=!1,p=!1,h=!0;if("function"!=typeof t)throw new Ot(o);function y(e){var n=r,o=a;return r=a=i,l=e,s=t.apply(o,n)}function m(t){var n=t-d;return d===i||n>=e||n<0||p&&t-l>=u}function v(){var t=Pa();if(m(t))return g(t);c=To(v,function(t){var n=e-(t-d);return p?gn(n,u-(t-l)):n}(t))}function g(t){return c=i,h&&r?y(t):(r=a=i,s)}function _(){var t=Pa(),n=m(t);if(r=arguments,a=this,d=t,n){if(c===i)return function(t){return l=t,c=To(v,e),f?y(t):s}(d);if(p)return bi(c),c=To(v,e),y(d)}return c===i&&(c=To(v,e)),s}return e=mu(e)||0,tu(n)&&(f=!!n.leading,u=(p="maxWait"in n)?vn(mu(n.maxWait)||0,e):u,h="trailing"in n?!!n.trailing:h),_.cancel=function(){c!==i&&bi(c),l=0,r=d=a=c=i},_.flush=function(){return c===i?s:g(Pa())},_}var ka=Kr((function(t,e){return cr(t,1,e)})),Ma=Kr((function(t,e,n){return cr(t,mu(e)||0,n)}));function Na(t,e){if("function"!=typeof t||null!=e&&"function"!=typeof e)throw new Ot(o);var n=function n(){var r=arguments,i=e?e.apply(this,r):r[0],o=n.cache;if(o.has(i))return o.get(i);var a=t.apply(this,r);return n.cache=o.set(i,a)||o,a};return n.cache=new(Na.Cache||Hn),n}function Da(t){if("function"!=typeof t)throw new Ot(o);return function(){var e=arguments;switch(e.length){case 0:return!t.call(this);case 1:return!t.call(this,e[0]);case 2:return!t.call(this,e[0],e[1]);case 3:return!t.call(this,e[0],e[1],e[2])}return!t.apply(this,e)}}Na.Cache=Hn;var La=gi((function(t,e){var n=(e=1==e.length&&Va(e[0])?Re(e[0],Ze(ao())):Re(mr(e,1),Ze(ao()))).length;return Kr((function(r){for(var i=-1,o=gn(r.length,n);++i=e})),Ga=xr(function(){return arguments}())?xr:function(t){return eu(t)&&Nt.call(t,"callee")&&!Wt.call(t,"callee")},Va=it.isArray,Ya=ve?Ze(ve):function(t){return eu(t)&&Er(t)==R};function Ha(t){return null!=t&&Xa(t.length)&&!Ja(t)}function Wa(t){return eu(t)&&Ha(t)}var Ka=Le||ms,Za=ge?Ze(ge):function(t){return eu(t)&&Er(t)==g};function $a(t){if(!eu(t))return!1;var e=Er(t);return e==_||"[object DOMException]"==e||"string"==typeof t.message&&"string"==typeof t.name&&!iu(t)}function Ja(t){if(!tu(t))return!1;var e=Er(t);return e==b||e==S||"[object AsyncFunction]"==e||"[object Proxy]"==e}function Qa(t){return"number"==typeof t&&t==hu(t)}function Xa(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=l}function tu(t){var e=r(t);return null!=t&&("object"==e||"function"==e)}function eu(t){return null!=t&&"object"==r(t)}var nu=_e?Ze(_e):function(t){return eu(t)&&po(t)==w};function ru(t){return"number"==typeof t||eu(t)&&Er(t)==C}function iu(t){if(!eu(t)||Er(t)!=E)return!1;var e=Yt(t);if(null===e)return!0;var n=Nt.call(e,"constructor")&&e.constructor;return"function"==typeof n&&n instanceof n&&Mt.call(n)==jt}var ou=be?Ze(be):function(t){return eu(t)&&Er(t)==P},au=Se?Ze(Se):function(t){return eu(t)&&po(t)==A};function uu(t){return"string"==typeof t||!Va(t)&&eu(t)&&Er(t)==O}function su(t){return"symbol"==r(t)||eu(t)&&Er(t)==T}var cu=we?Ze(we):function(t){return eu(t)&&Xa(t.length)&&!!ie[Er(t)]},du=Vi(Lr),lu=Vi((function(t,e){return t<=e}));function fu(t){if(!t)return[];if(Ha(t))return uu(t)?ln(t):Ai(t);if(Qt&&t[Qt])return function(t){for(var e,n=[];!(e=t.next()).done;)n.push(e.value);return n}(t[Qt]());var e=po(t);return(e==w?on:e==A?sn:Fu)(t)}function pu(t){return t?(t=mu(t))===d||t===-1/0?17976931348623157e292*(t<0?-1:1):t==t?t:0:0===t?t:0}function hu(t){var e=pu(t),n=e%1;return e==e?n?e-n:e:0}function yu(t){return t?ar(hu(t),0,p):0}function mu(t){if("number"==typeof t)return t;if(su(t))return f;if(tu(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=tu(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=Ke(t);var n=ht.test(t);return n||mt.test(t)?se(t.slice(2),n?2:8):pt.test(t)?f:+t}function vu(t){return Oi(t,ku(t))}function gu(t){return null==t?"":ui(t)}var _u=xi((function(t,e){if(wo(e)||Ha(e))Oi(e,Ru(e),t);else for(var n in e)Nt.call(e,n)&&tr(t,n,e[n])})),bu=xi((function(t,e){Oi(e,ku(e),t)})),Su=xi((function(t,e,n,r){Oi(e,ku(e),t,r)})),wu=xi((function(t,e,n,r){Oi(e,Ru(e),t,r)})),Cu=to(or),Eu=Kr((function(t,e){t=It(t);var n=-1,r=e.length,o=r>2?e[2]:i;for(o&&go(e[0],e[1],o)&&(r=1);++n1),e})),Oi(t,no(t),n),r&&(n=ur(n,7,Qi));for(var i=e.length;i--;)ci(n,e[i]);return n})),Lu=to((function(t,e){return null==t?{}:function(t,e){return Gr(t,e,(function(e,n){return Au(t,n)}))}(t,e)}));function zu(t,e){if(null==t)return{};var n=Re(no(t),(function(t){return[t]}));return e=ao(e),Gr(t,n,(function(t,n){return e(t,n[0])}))}var ju=Ki(Ru),Uu=Ki(ku);function Fu(t){return null==t?[]:$e(t,Ru(t))}var qu=Ni((function(t,e,n){return e=e.toLowerCase(),t+(n?Bu(e):e)}));function Bu(t){return $u(gu(t).toLowerCase())}function Gu(t){return(t=gu(t))&&t.replace(gt,tn).replace(Jt,"")}var Vu=Ni((function(t,e,n){return t+(n?"-":"")+e.toLowerCase()})),Yu=Ni((function(t,e,n){return t+(n?" ":"")+e.toLowerCase()})),Hu=Mi("toLowerCase"),Wu=Ni((function(t,e,n){return t+(n?"_":"")+e.toLowerCase()})),Ku=Ni((function(t,e,n){return t+(n?" ":"")+$u(e)})),Zu=Ni((function(t,e,n){return t+(n?" ":"")+e.toUpperCase()})),$u=Mi("toUpperCase");function Ju(t,e,n){return t=gu(t),(e=n?i:e)===i?function(t){return ee.test(t)}(t)?function(t){return t.match(Xt)||[]}(t):function(t){return t.match(st)||[]}(t):t.match(e)||[]}var Qu=Kr((function(t,e){try{return Ce(t,i,e)}catch(t){return $a(t)?t:new wt(t)}})),Xu=to((function(t,e){return Ie(e,(function(e){e=zo(e),ir(t,e,Ta(t[e],t))})),t}));function ts(t){return function(){return t}}var es=zi(),ns=zi(!0);function rs(t){return t}function is(t){return Nr("function"==typeof t?t:ur(t,1))}var os=Kr((function(t,e){return function(n){return Tr(n,t,e)}})),as=Kr((function(t,e){return function(n){return Tr(t,n,e)}}));function us(t,e,n){var r=Ru(e),i=Sr(e,r);null!=n||tu(e)&&(i.length||!r.length)||(n=e,e=t,t=this,i=Sr(e,Ru(e)));var o=!(tu(n)&&"chain"in n&&!n.chain),a=Ja(t);return Ie(i,(function(n){var r=e[n];t[n]=r,a&&(t.prototype[n]=function(){var e=this.__chain__;if(o||e){var n=t(this.__wrapped__);return(n.__actions__=Ai(this.__actions__)).push({func:r,args:arguments,thisArg:t}),n.__chain__=e,n}return r.apply(t,ke([this.value()],arguments))})})),t}function ss(){}var cs=qi(Re),ds=qi(Ae),ls=qi(De);function fs(t){return _o(t)?Ge(zo(t)):function(t){return function(e){return wr(e,t)}}(t)}var ps=Gi(),hs=Gi(!0);function ys(){return[]}function ms(){return!1}var vs,gs=Fi((function(t,e){return t+e}),0),_s=Hi("ceil"),bs=Fi((function(t,e){return t/e}),1),Ss=Hi("floor"),ws=Fi((function(t,e){return t*e}),1),Cs=Hi("round"),Es=Fi((function(t,e){return t-e}),0);return Un.after=function(t,e){if("function"!=typeof e)throw new Ot(o);return t=hu(t),function(){if(--t<1)return e.apply(this,arguments)}},Un.ary=Aa,Un.assign=_u,Un.assignIn=bu,Un.assignInWith=Su,Un.assignWith=wu,Un.at=Cu,Un.before=Oa,Un.bind=Ta,Un.bindAll=Xu,Un.bindKey=xa,Un.castArray=function(){if(!arguments.length)return[];var t=arguments[0];return Va(t)?t:[t]},Un.chain=fa,Un.chunk=function(t,e,n){e=(n?go(t,e,n):e===i)?1:vn(hu(e),0);var r=null==t?0:t.length;if(!r||e<1)return[];for(var o=0,a=0,u=it(pe(r/e));oo?0:o+n),(r=r===i||r>o?o:hu(r))<0&&(r+=o),r=n>r?0:yu(r);n>>0)?(t=gu(t))&&("string"==typeof e||null!=e&&!ou(e))&&!(e=ui(e))&&rn(t)?_i(ln(t),0,n):t.split(e,n):[]},Un.spread=function(t,e){if("function"!=typeof t)throw new Ot(o);return e=null==e?0:vn(hu(e),0),Kr((function(n){var r=n[e],i=_i(n,0,e);return r&&ke(i,r),Ce(t,this,i)}))},Un.tail=function(t){var e=null==t?0:t.length;return e?ei(t,1,e):[]},Un.take=function(t,e,n){return t&&t.length?ei(t,0,(e=n||e===i?1:hu(e))<0?0:e):[]},Un.takeRight=function(t,e,n){var r=null==t?0:t.length;return r?ei(t,(e=r-(e=n||e===i?1:hu(e)))<0?0:e,r):[]},Un.takeRightWhile=function(t,e){return t&&t.length?li(t,ao(e,3),!1,!0):[]},Un.takeWhile=function(t,e){return t&&t.length?li(t,ao(e,3)):[]},Un.tap=function(t,e){return e(t),t},Un.throttle=function(t,e,n){var r=!0,i=!0;if("function"!=typeof t)throw new Ot(o);return tu(n)&&(r="leading"in n?!!n.leading:r,i="trailing"in n?!!n.trailing:i),Ra(t,e,{leading:r,maxWait:e,trailing:i})},Un.thru=pa,Un.toArray=fu,Un.toPairs=ju,Un.toPairsIn=Uu,Un.toPath=function(t){return Va(t)?Re(t,zo):su(t)?[t]:Ai(Lo(gu(t)))},Un.toPlainObject=vu,Un.transform=function(t,e,n){var r=Va(t),i=r||Ka(t)||cu(t);if(e=ao(e,4),null==n){var o=t&&t.constructor;n=i?r?new o:[]:tu(t)&&Ja(o)?Fn(Yt(t)):{}}return(i?Ie:_r)(t,(function(t,r,i){return e(n,t,r,i)})),n},Un.unary=function(t){return Aa(t,1)},Un.union=ea,Un.unionBy=na,Un.unionWith=ra,Un.uniq=function(t){return t&&t.length?si(t):[]},Un.uniqBy=function(t,e){return t&&t.length?si(t,ao(e,2)):[]},Un.uniqWith=function(t,e){return e="function"==typeof e?e:i,t&&t.length?si(t,i,e):[]},Un.unset=function(t,e){return null==t||ci(t,e)},Un.unzip=ia,Un.unzipWith=oa,Un.update=function(t,e,n){return null==t?t:di(t,e,mi(n))},Un.updateWith=function(t,e,n,r){return r="function"==typeof r?r:i,null==t?t:di(t,e,mi(n),r)},Un.values=Fu,Un.valuesIn=function(t){return null==t?[]:$e(t,ku(t))},Un.without=aa,Un.words=Ju,Un.wrap=function(t,e){return za(mi(e),t)},Un.xor=ua,Un.xorBy=sa,Un.xorWith=ca,Un.zip=da,Un.zipObject=function(t,e){return hi(t||[],e||[],tr)},Un.zipObjectDeep=function(t,e){return hi(t||[],e||[],Jr)},Un.zipWith=la,Un.entries=ju,Un.entriesIn=Uu,Un.extend=bu,Un.extendWith=Su,us(Un,Un),Un.add=gs,Un.attempt=Qu,Un.camelCase=qu,Un.capitalize=Bu,Un.ceil=_s,Un.clamp=function(t,e,n){return n===i&&(n=e,e=i),n!==i&&(n=(n=mu(n))==n?n:0),e!==i&&(e=(e=mu(e))==e?e:0),ar(mu(t),e,n)},Un.clone=function(t){return ur(t,4)},Un.cloneDeep=function(t){return ur(t,5)},Un.cloneDeepWith=function(t,e){return ur(t,5,e="function"==typeof e?e:i)},Un.cloneWith=function(t,e){return ur(t,4,e="function"==typeof e?e:i)},Un.conformsTo=function(t,e){return null==e||sr(t,e,Ru(e))},Un.deburr=Gu,Un.defaultTo=function(t,e){return null==t||t!=t?e:t},Un.divide=bs,Un.endsWith=function(t,e,n){t=gu(t),e=ui(e);var r=t.length,o=n=n===i?r:ar(hu(n),0,r);return(n-=e.length)>=0&&t.slice(n,o)==e},Un.eq=Fa,Un.escape=function(t){return(t=gu(t))&&K.test(t)?t.replace(H,en):t},Un.escapeRegExp=function(t){return(t=gu(t))&&nt.test(t)?t.replace(et,"\\$&"):t},Un.every=function(t,e,n){var r=Va(t)?Ae:pr;return n&&go(t,e,n)&&(e=i),r(t,ao(e,3))},Un.find=ma,Un.findIndex=Go,Un.findKey=function(t,e){return ze(t,ao(e,3),_r)},Un.findLast=va,Un.findLastIndex=Vo,Un.findLastKey=function(t,e){return ze(t,ao(e,3),br)},Un.floor=Ss,Un.forEach=ga,Un.forEachRight=_a,Un.forIn=function(t,e){return null==t?t:vr(t,ao(e,3),ku)},Un.forInRight=function(t,e){return null==t?t:gr(t,ao(e,3),ku)},Un.forOwn=function(t,e){return t&&_r(t,ao(e,3))},Un.forOwnRight=function(t,e){return t&&br(t,ao(e,3))},Un.get=Pu,Un.gt=qa,Un.gte=Ba,Un.has=function(t,e){return null!=t&&ho(t,e,Pr)},Un.hasIn=Au,Un.head=Ho,Un.identity=rs,Un.includes=function(t,e,n,r){t=Ha(t)?t:Fu(t),n=n&&!r?hu(n):0;var i=t.length;return n<0&&(n=vn(i+n,0)),uu(t)?n<=i&&t.indexOf(e,n)>-1:!!i&&Ue(t,e,n)>-1},Un.indexOf=function(t,e,n){var r=null==t?0:t.length;if(!r)return-1;var i=null==n?0:hu(n);return i<0&&(i=vn(r+i,0)),Ue(t,e,i)},Un.inRange=function(t,e,n){return e=pu(e),n===i?(n=e,e=0):n=pu(n),function(t,e,n){return t>=gn(e,n)&&t=-9007199254740991&&t<=l},Un.isSet=au,Un.isString=uu,Un.isSymbol=su,Un.isTypedArray=cu,Un.isUndefined=function(t){return t===i},Un.isWeakMap=function(t){return eu(t)&&po(t)==x},Un.isWeakSet=function(t){return eu(t)&&"[object WeakSet]"==Er(t)},Un.join=function(t,e){return null==t?"":yn.call(t,e)},Un.kebabCase=Vu,Un.last=$o,Un.lastIndexOf=function(t,e,n){var r=null==t?0:t.length;if(!r)return-1;var o=r;return n!==i&&(o=(o=hu(n))<0?vn(r+o,0):gn(o,r-1)),e==e?function(t,e,n){for(var r=n+1;r--;)if(t[r]===e)return r;return r}(t,e,o):je(t,qe,o,!0)},Un.lowerCase=Yu,Un.lowerFirst=Hu,Un.lt=du,Un.lte=lu,Un.max=function(t){return t&&t.length?hr(t,rs,Ir):i},Un.maxBy=function(t,e){return t&&t.length?hr(t,ao(e,2),Ir):i},Un.mean=function(t){return Be(t,rs)},Un.meanBy=function(t,e){return Be(t,ao(e,2))},Un.min=function(t){return t&&t.length?hr(t,rs,Lr):i},Un.minBy=function(t,e){return t&&t.length?hr(t,ao(e,2),Lr):i},Un.stubArray=ys,Un.stubFalse=ms,Un.stubObject=function(){return{}},Un.stubString=function(){return""},Un.stubTrue=function(){return!0},Un.multiply=ws,Un.nth=function(t,e){return t&&t.length?qr(t,hu(e)):i},Un.noConflict=function(){return le._===this&&(le._=Ut),this},Un.noop=ss,Un.now=Pa,Un.pad=function(t,e,n){t=gu(t);var r=(e=hu(e))?dn(t):0;if(!e||r>=e)return t;var i=(e-r)/2;return Bi(ye(i),n)+t+Bi(pe(i),n)},Un.padEnd=function(t,e,n){t=gu(t);var r=(e=hu(e))?dn(t):0;return e&&re){var r=t;t=e,e=r}if(n||t%1||e%1){var o=Sn();return gn(t+o*(e-t+ue("1e-"+((o+"").length-1))),e)}return Hr(t,e)},Un.reduce=function(t,e,n){var r=Va(t)?Me:Ye,i=arguments.length<3;return r(t,ao(e,4),n,i,lr)},Un.reduceRight=function(t,e,n){var r=Va(t)?Ne:Ye,i=arguments.length<3;return r(t,ao(e,4),n,i,fr)},Un.repeat=function(t,e,n){return e=(n?go(t,e,n):e===i)?1:hu(e),Wr(gu(t),e)},Un.replace=function(){var t=arguments,e=gu(t[0]);return t.length<3?e:e.replace(t[1],t[2])},Un.result=function(t,e,n){var r=-1,o=(e=vi(e,t)).length;for(o||(o=1,t=i);++rl)return[];var n=p,r=gn(t,p);e=ao(e),t-=p;for(var i=We(r,e);++n=a)return t;var s=n-dn(r);if(s<1)return r;var c=u?_i(u,0,s).join(""):t.slice(0,s);if(o===i)return c+r;if(u&&(s+=c.length-s),ou(o)){if(t.slice(s).search(o)){var d,l=c;for(o.global||(o=Pt(o.source,gu(ft.exec(o))+"g")),o.lastIndex=0;d=o.exec(l);)var f=d.index;c=c.slice(0,f===i?s:f)}}else if(t.indexOf(ui(o),s)!=s){var p=c.lastIndexOf(o);p>-1&&(c=c.slice(0,p))}return c+r},Un.unescape=function(t){return(t=gu(t))&&W.test(t)?t.replace(Y,pn):t},Un.uniqueId=function(t){var e=++Dt;return gu(t)+e},Un.upperCase=Zu,Un.upperFirst=$u,Un.each=ga,Un.eachRight=_a,Un.first=Ho,us(Un,(vs={},_r(Un,(function(t,e){Nt.call(Un.prototype,e)||(vs[e]=t)})),vs),{chain:!1}),Un.VERSION="4.17.21",Ie(["bind","bindKey","curry","curryRight","partial","partialRight"],(function(t){Un[t].placeholder=Un})),Ie(["drop","take"],(function(t,e){Gn.prototype[t]=function(n){n=n===i?1:vn(hu(n),0);var r=this.__filtered__&&!e?new Gn(this):this.clone();return r.__filtered__?r.__takeCount__=gn(n,r.__takeCount__):r.__views__.push({size:gn(n,p),type:t+(r.__dir__<0?"Right":"")}),r},Gn.prototype[t+"Right"]=function(e){return this.reverse()[t](e).reverse()}})),Ie(["filter","map","takeWhile"],(function(t,e){var n=e+1,r=1==n||3==n;Gn.prototype[t]=function(t){var e=this.clone();return e.__iteratees__.push({iteratee:ao(t,3),type:n}),e.__filtered__=e.__filtered__||r,e}})),Ie(["head","last"],(function(t,e){var n="take"+(e?"Right":"");Gn.prototype[t]=function(){return this[n](1).value()[0]}})),Ie(["initial","tail"],(function(t,e){var n="drop"+(e?"":"Right");Gn.prototype[t]=function(){return this.__filtered__?new Gn(this):this[n](1)}})),Gn.prototype.compact=function(){return this.filter(rs)},Gn.prototype.find=function(t){return this.filter(t).head()},Gn.prototype.findLast=function(t){return this.reverse().find(t)},Gn.prototype.invokeMap=Kr((function(t,e){return"function"==typeof t?new Gn(this):this.map((function(n){return Tr(n,t,e)}))})),Gn.prototype.reject=function(t){return this.filter(Da(ao(t)))},Gn.prototype.slice=function(t,e){t=hu(t);var n=this;return n.__filtered__&&(t>0||e<0)?new Gn(n):(t<0?n=n.takeRight(-t):t&&(n=n.drop(t)),e!==i&&(n=(e=hu(e))<0?n.dropRight(-e):n.take(e-t)),n)},Gn.prototype.takeRightWhile=function(t){return this.reverse().takeWhile(t).reverse()},Gn.prototype.toArray=function(){return this.take(p)},_r(Gn.prototype,(function(t,e){var n=/^(?:filter|find|map|reject)|While$/.test(e),r=/^(?:head|last)$/.test(e),o=Un[r?"take"+("last"==e?"Right":""):e],a=r||/^find/.test(e);o&&(Un.prototype[e]=function(){var e=this.__wrapped__,u=r?[1]:arguments,s=e instanceof Gn,c=u[0],d=s||Va(e),l=function(t){var e=o.apply(Un,ke([t],u));return r&&f?e[0]:e};d&&n&&"function"==typeof c&&1!=c.length&&(s=d=!1);var f=this.__chain__,p=!!this.__actions__.length,h=a&&!f,y=s&&!p;if(!a&&d){e=y?e:new Gn(this);var m=t.apply(e,u);return m.__actions__.push({func:pa,args:[l],thisArg:i}),new Bn(m,f)}return h&&y?t.apply(this,u):(m=this.thru(l),h?r?m.value()[0]:m.value():m)})})),Ie(["pop","push","shift","sort","splice","unshift"],(function(t){var e=Tt[t],n=/^(?:push|sort|unshift)$/.test(t)?"tap":"thru",r=/^(?:pop|shift)$/.test(t);Un.prototype[t]=function(){var t=arguments;if(r&&!this.__chain__){var i=this.value();return e.apply(Va(i)?i:[],t)}return this[n]((function(n){return e.apply(Va(n)?n:[],t)}))}})),_r(Gn.prototype,(function(t,e){var n=Un[e];if(n){var r=n.name+"";Nt.call(xn,r)||(xn[r]=[]),xn[r].push({name:e,func:n})}})),xn[ji(i,2).name]=[{name:"wrapper",func:i}],Gn.prototype.clone=function(){var t=new Gn(this.__wrapped__);return t.__actions__=Ai(this.__actions__),t.__dir__=this.__dir__,t.__filtered__=this.__filtered__,t.__iteratees__=Ai(this.__iteratees__),t.__takeCount__=this.__takeCount__,t.__views__=Ai(this.__views__),t},Gn.prototype.reverse=function(){if(this.__filtered__){var t=new Gn(this);t.__dir__=-1,t.__filtered__=!0}else(t=this.clone()).__dir__*=-1;return t},Gn.prototype.value=function(){var t=this.__wrapped__.value(),e=this.__dir__,n=Va(t),r=e<0,i=n?t.length:0,o=function(t,e,n){for(var r=-1,i=n.length;++r=this.__values__.length;return{done:t,value:t?i:this.__values__[this.__index__++]}},Un.prototype.plant=function(t){for(var e,n=this;n instanceof qn;){var r=Uo(n);r.__index__=0,r.__values__=i,e?o.__wrapped__=r:e=r;var o=r;n=n.__wrapped__}return o.__wrapped__=t,e},Un.prototype.reverse=function(){var t=this.__wrapped__;if(t instanceof Gn){var e=t;return this.__actions__.length&&(e=new Gn(this)),(e=e.reverse()).__actions__.push({func:pa,args:[ta],thisArg:i}),new Bn(e,this.__chain__)}return this.thru(ta)},Un.prototype.toJSON=Un.prototype.valueOf=Un.prototype.value=function(){return fi(this.__wrapped__,this.__actions__)},Un.prototype.first=Un.prototype.head,Qt&&(Un.prototype[Qt]=function(){return this}),Un}();"function"==typeof define&&"object"==r(define.amd)&&define.amd?(le._=hn,define((function(){return hn}))):pe?((pe.exports=hn)._=hn,fe._=hn):le._=hn}.call(this)},66534:(t,e,n)=>{"use strict";n(93942),n(64668),n(95412),n(27835),n(60678),n(13722),n(34500);var r=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable;t.exports=function(){try{if(!Object.assign)return!1;var t=new String("abc");if(t[5]="de","5"===Object.getOwnPropertyNames(t)[0])return!1;for(var e={},n=0;n<10;n++)e["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(e).map((function(t){return e[t]})).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach((function(t){r[t]=t})),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(t){return!1}}()?Object.assign:function(t,e){for(var n,a,u=function(t){if(null==t)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}(t),s=1;s{"use strict";function r(t,e,n){return(e=function(t){var e=function(t,e){if("object"!==o(t)||null===t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,"string");if("object"!==o(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"===o(e)?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function i(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,i,o,a,u=[],s=!0,c=!1;try{if(o=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;s=!1}else for(;!(s=(r=o.call(n)).done)&&(u.push(r.value),u.length!==e);s=!0);}catch(t){c=!0,i=t}finally{try{if(!s&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return u}}(t,e)||u(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function o(t){return o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},o(t)}function a(t){return function(t){if(Array.isArray(t))return s(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||u(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function u(t,e){if(t){if("string"==typeof t)return s(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?s(t,e):void 0}}function s(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n0})).join("&")},e.parseUrl=function(t,e){e=Object.assign({decode:!0},e);var n=i(l(t,"#"),2),r=n[0],o=n[1];return Object.assign({url:r.split("?")[0]||"",query:S(_(t),e)},e&&e.parseFragmentIdentifier&&o?{fragmentIdentifier:m(o,e)}:{})},e.stringifyUrl=function(t,n){n=Object.assign(r({encode:!0,strict:!0},p,!0),n);var i=g(t.url).split("?")[0]||"",o=e.extract(t.url),a=e.parse(o,{sort:!1}),u=Object.assign(a,t.query),s=e.stringify(u,n);s&&(s="?".concat(s));var c=function(t){var e="",n=t.indexOf("#");return-1!==n&&(e=t.slice(n)),e}(t.url);return t.fragmentIdentifier&&(c="#".concat(n[p]?y(t.fragmentIdentifier,n):t.fragmentIdentifier)),"".concat(i).concat(s).concat(c)},e.pick=function(t,n,i){i=Object.assign(r({parseFragmentIdentifier:!0},p,!1),i);var o=e.parseUrl(t,i),a=o.url,u=o.query,s=o.fragmentIdentifier;return e.stringifyUrl({url:a,query:f(u,n),fragmentIdentifier:s},i)},e.exclude=function(t,n,r){var i=Array.isArray(n)?function(t){return!n.includes(t)}:function(t,e){return!n(t,e)};return e.pick(t,i,r)}},89311:(t,e,n)=>{"use strict";n(40737),n(26667),n(58443),t.exports=function(t){return encodeURIComponent(t).replace(/[!'()*]/g,(function(t){return"%".concat(t.charCodeAt(0).toString(16).toUpperCase())}))}},57469:(t,e,n)=>{"use strict";n.r(e),n.d(e,{ArgumentOutOfRangeError:()=>x.W,AsyncSubject:()=>d.c,BehaviorSubject:()=>s.X,ConnectableObservable:()=>i.c,EMPTY:()=>Z.E,EmptyError:()=>R.K,GroupedObservable:()=>o.T,NEVER:()=>dt,Notification:()=>I.P,NotificationKind:()=>I.W,ObjectUnsubscribedError:()=>k.N,Observable:()=>r.y,ReplaySubject:()=>c.t,Scheduler:()=>w.b,Subject:()=>u.xQ,Subscriber:()=>E.L,Subscription:()=>C.w,TimeoutError:()=>N.W,UnsubscriptionError:()=>M.B,VirtualAction:()=>S,VirtualTimeScheduler:()=>b,animationFrame:()=>_,animationFrameScheduler:()=>g,asap:()=>l.e,asapScheduler:()=>l.E,async:()=>f.P,asyncScheduler:()=>f.z,bindCallback:()=>U,bindNodeCallback:()=>B,combineLatest:()=>H.aj,concat:()=>W.z,config:()=>Ot.v,defer:()=>K.P,empty:()=>Z.c,forkJoin:()=>Q,from:()=>J.D,fromEvent:()=>tt.R,fromEventPattern:()=>nt,generate:()=>rt,identity:()=>O.y,iif:()=>ot,interval:()=>ut,isObservable:()=>T,merge:()=>ct.T,never:()=>lt,noop:()=>A.Z,observable:()=>a.L,of:()=>ft.of,onErrorResumeNext:()=>pt,pairs:()=>ht,partition:()=>_t,pipe:()=>P.z,queue:()=>p.c,queueScheduler:()=>p.N,race:()=>bt.S3,range:()=>St,scheduled:()=>At.x,throwError:()=>Ct._,timer:()=>Et.H,using:()=>It,zip:()=>Pt.$R});var r=n(64074),i=n(46700),o=n(82727),a=n(86916),u=n(99357),s=n(41735),c=n(28646),d=n(2503),l=n(18420),f=n(26858),p=n(30396),h=n(61699),y=n(674),m=function(t){function e(e,n){var r=t.call(this,e,n)||this;return r.scheduler=e,r.work=n,r}return h.__extends(e,t),e.prototype.requestAsyncId=function(e,n,r){return void 0===r&&(r=0),null!==r&&r>0?t.prototype.requestAsyncId.call(this,e,n,r):(e.actions.push(this),e.scheduled||(e.scheduled=requestAnimationFrame((function(){return e.flush(null)}))))},e.prototype.recycleAsyncId=function(e,n,r){if(void 0===r&&(r=0),null!==r&&r>0||null===r&&this.delay>0)return t.prototype.recycleAsyncId.call(this,e,n,r);0===e.actions.length&&(cancelAnimationFrame(n),e.scheduled=void 0)},e}(y.o),v=n(41978),g=new(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return h.__extends(e,t),e.prototype.flush=function(t){this.active=!0,this.scheduled=void 0;var e,n=this.actions,r=-1,i=n.length;t=t||n.shift();do{if(e=t.execute(t.state,t.delay))break}while(++re.index?1:-1:t.delay>e.delay?1:-1},e}(y.o),w=n(78379),C=n(75838),E=n(90782),I=n(48811),P=n(76252),A=n(38375),O=n(16726);function T(t){return!!t&&(t instanceof r.y||"function"==typeof t.lift&&"function"==typeof t.subscribe)}var x=n(4069),R=n(2246),k=n(42046),M=n(42135),N=n(76960),D=(n(88033),n(92160)),L=n(12411),z=n(24937),j=n(79917);function U(t,e,n){if(e){if(!(0,j.K)(e))return function(){for(var r=[],i=0;i=e){r.complete();break}if(r.next(o++),r.closed)break}}))}function wt(t){var e=t.start,n=t.index,r=t.count,i=t.subscriber;n>=r?i.complete():(i.next(e),i.closed||(t.index=n+1,t.start=e+1,this.schedule(t)))}var Ct=n(78665),Et=n(12670);function It(t,e){return new r.y((function(n){var r,i;try{r=t()}catch(t){return void n.error(t)}try{i=e(r)}catch(t){return void n.error(t)}var o=(i?(0,J.D)(i):Z.E).subscribe(n);return function(){o.unsubscribe(),r&&r.unsubscribe()}}))}var Pt=n(66436),At=n(77488),Ot=n(84850)},2503:(t,e,n)=>{"use strict";n.d(e,{c:()=>a});var r=n(61699),i=n(99357),o=n(75838),a=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.value=null,e.hasNext=!1,e.hasCompleted=!1,e}return r.__extends(e,t),e.prototype._subscribe=function(e){return this.hasError?(e.error(this.thrownError),o.w.EMPTY):this.hasCompleted&&this.hasNext?(e.next(this.value),e.complete(),o.w.EMPTY):t.prototype._subscribe.call(this,e)},e.prototype.next=function(t){this.hasCompleted||(this.value=t,this.hasNext=!0)},e.prototype.error=function(e){this.hasCompleted||t.prototype.error.call(this,e)},e.prototype.complete=function(){this.hasCompleted=!0,this.hasNext&&t.prototype.next.call(this,this.value),t.prototype.complete.call(this)},e}(i.xQ)},41735:(t,e,n)=>{"use strict";n.d(e,{X:()=>a});var r=n(61699),i=n(99357),o=n(42046),a=function(t){function e(e){var n=t.call(this)||this;return n._value=e,n}return r.__extends(e,t),Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!0,configurable:!0}),e.prototype._subscribe=function(e){var n=t.prototype._subscribe.call(this,e);return n&&!n.closed&&e.next(this._value),n},e.prototype.getValue=function(){if(this.hasError)throw this.thrownError;if(this.closed)throw new o.N;return this._value},e.prototype.next=function(e){t.prototype.next.call(this,this._value=e)},e}(i.xQ)},48811:(t,e,n)=>{"use strict";n.d(e,{P:()=>u,W:()=>r});var r,i=n(14585),o=n(12309),a=n(78665);r||(r={});var u=function(){function t(t,e,n){this.kind=t,this.value=e,this.error=n,this.hasValue="N"===t}return t.prototype.observe=function(t){switch(this.kind){case"N":return t.next&&t.next(this.value);case"E":return t.error&&t.error(this.error);case"C":return t.complete&&t.complete()}},t.prototype.do=function(t,e,n){switch(this.kind){case"N":return t&&t(this.value);case"E":return e&&e(this.error);case"C":return n&&n()}},t.prototype.accept=function(t,e,n){return t&&"function"==typeof t.next?this.observe(t):this.do(t,e,n)},t.prototype.toObservable=function(){switch(this.kind){case"N":return(0,o.of)(this.value);case"E":return(0,a._)(this.error);case"C":return(0,i.c)()}throw new Error("unexpected notification kind value")},t.createNext=function(e){return void 0!==e?new t("N",e):t.undefinedValueNotification},t.createError=function(e){return new t("E",void 0,e)},t.createComplete=function(){return t.completeNotification},t.completeNotification=new t("C"),t.undefinedValueNotification=new t("N",void 0),t}()},64074:(t,e,n)=>{"use strict";n.d(e,{y:()=>s}),n(40737),n(83823),n(71806);var r=n(12411),i=n(54752),o=n(86916),a=n(76252),u=n(84850),s=function(){function t(t){this._isScalar=!1,t&&(this._subscribe=t)}return t.prototype.lift=function(e){var n=new t;return n.source=this,n.operator=e,n},t.prototype.subscribe=function(t,e,n){var r=this.operator,o=(0,i.Y)(t,e,n);if(r?o.add(r.call(o,this.source)):o.add(this.source||u.v.useDeprecatedSynchronousErrorHandling&&!o.syncErrorThrowable?this._subscribe(o):this._trySubscribe(o)),u.v.useDeprecatedSynchronousErrorHandling&&o.syncErrorThrowable&&(o.syncErrorThrowable=!1,o.syncErrorThrown))throw o.syncErrorValue;return o},t.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(e){u.v.useDeprecatedSynchronousErrorHandling&&(t.syncErrorThrown=!0,t.syncErrorValue=e),(0,r._)(t)?t.error(e):console.warn(e)}},t.prototype.forEach=function(t,e){var n=this;return new(e=c(e))((function(e,r){var i;i=n.subscribe((function(e){try{t(e)}catch(t){r(t),i&&i.unsubscribe()}}),r,e)}))},t.prototype._subscribe=function(t){var e=this.source;return e&&e.subscribe(t)},t.prototype[o.L]=function(){return this},t.prototype.pipe=function(){for(var t=[],e=0;e{"use strict";n.d(e,{c:()=>o});var r=n(84850),i=n(61554),o={closed:!0,next:function(t){},error:function(t){if(r.v.useDeprecatedSynchronousErrorHandling)throw t;(0,i.z)(t)},complete:function(){}}},64809:(t,e,n)=>{"use strict";n.d(e,{L:()=>i});var r=n(61699),i=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return r.__extends(e,t),e.prototype.notifyNext=function(t,e,n,r,i){this.destination.next(e)},e.prototype.notifyError=function(t,e){this.destination.error(t)},e.prototype.notifyComplete=function(t){this.destination.complete()},e}(n(90782).L)},28646:(t,e,n)=>{"use strict";n.d(e,{t:()=>d}),n(32345),n(99023);var r=n(61699),i=n(99357),o=n(30396),a=n(75838),u=n(9202),s=n(42046),c=n(17630),d=function(t){function e(e,n,r){void 0===e&&(e=Number.POSITIVE_INFINITY),void 0===n&&(n=Number.POSITIVE_INFINITY);var i=t.call(this)||this;return i.scheduler=r,i._events=[],i._infiniteTimeWindow=!1,i._bufferSize=e<1?1:e,i._windowTime=n<1?1:n,n===Number.POSITIVE_INFINITY?(i._infiniteTimeWindow=!0,i.next=i.nextInfiniteTimeWindow):i.next=i.nextTimeWindow,i}return r.__extends(e,t),e.prototype.nextInfiniteTimeWindow=function(e){if(!this.isStopped){var n=this._events;n.push(e),n.length>this._bufferSize&&n.shift()}t.prototype.next.call(this,e)},e.prototype.nextTimeWindow=function(e){this.isStopped||(this._events.push(new l(this._getNow(),e)),this._trimBufferThenGetEvents()),t.prototype.next.call(this,e)},e.prototype._subscribe=function(t){var e,n=this._infiniteTimeWindow,r=n?this._events:this._trimBufferThenGetEvents(),i=this.scheduler,o=r.length;if(this.closed)throw new s.N;if(this.isStopped||this.hasError?e=a.w.EMPTY:(this.observers.push(t),e=new c.W(this,t)),i&&t.add(t=new u.ht(t,i)),n)for(var d=0;de&&(o=Math.max(o,i-e)),o>0&&r.splice(0,o),r},e}(i.xQ),l=function(){return function(t,e){this.time=t,this.value=e}}()},78379:(t,e,n)=>{"use strict";n.d(e,{b:()=>r});var r=function(){function t(e,n){void 0===n&&(n=t.now),this.SchedulerAction=e,this.now=n}return t.prototype.schedule=function(t,e,n){return void 0===e&&(e=0),new this.SchedulerAction(this,t).schedule(n,e)},t.now=function(){return Date.now()},t}()},99357:(t,e,n)=>{"use strict";n.d(e,{Yc:()=>d,xQ:()=>l}),n(16516);var r=n(61699),i=n(64074),o=n(90782),a=n(75838),u=n(42046),s=n(17630),c=n(70239),d=function(t){function e(e){var n=t.call(this,e)||this;return n.destination=e,n}return r.__extends(e,t),e}(o.L),l=function(t){function e(){var e=t.call(this)||this;return e.observers=[],e.closed=!1,e.isStopped=!1,e.hasError=!1,e.thrownError=null,e}return r.__extends(e,t),e.prototype[c.b]=function(){return new d(this)},e.prototype.lift=function(t){var e=new f(this,this);return e.operator=t,e},e.prototype.next=function(t){if(this.closed)throw new u.N;if(!this.isStopped)for(var e=this.observers,n=e.length,r=e.slice(),i=0;i{"use strict";n.d(e,{W:()=>i}),n(6550),n(32345);var r=n(61699),i=function(t){function e(e,n){var r=t.call(this)||this;return r.subject=e,r.subscriber=n,r.closed=!1,r}return r.__extends(e,t),e.prototype.unsubscribe=function(){if(!this.closed){this.closed=!0;var t=this.subject,e=t.observers;if(this.subject=null,e&&0!==e.length&&!t.isStopped&&!t.closed){var n=e.indexOf(this.subscriber);-1!==n&&e.splice(n,1)}}},e}(n(75838).w)},90782:(t,e,n)=>{"use strict";n.d(e,{L:()=>l}),n(93942),n(70472),n(93270),n(38490),n(40737),n(10951),n(5193);var r=n(61699),i=n(11169),o=n(43610),a=n(75838),u=n(70239),s=n(84850),c=n(61554);function d(t){return d="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},d(t)}var l=function(t){function e(n,r,i){var a=t.call(this)||this;switch(a.syncErrorValue=null,a.syncErrorThrown=!1,a.syncErrorThrowable=!1,a.isStopped=!1,arguments.length){case 0:a.destination=o.c;break;case 1:if(!n){a.destination=o.c;break}if("object"===d(n)){n instanceof e?(a.syncErrorThrowable=n.syncErrorThrowable,a.destination=n,n.add(a)):(a.syncErrorThrowable=!0,a.destination=new f(a,n));break}default:a.syncErrorThrowable=!0,a.destination=new f(a,n,r,i)}return a}return r.__extends(e,t),e.prototype[u.b]=function(){return this},e.create=function(t,n,r){var i=new e(t,n,r);return i.syncErrorThrowable=!1,i},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this))},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){this.destination.error(t),this.unsubscribe()},e.prototype._complete=function(){this.destination.complete(),this.unsubscribe()},e.prototype._unsubscribeAndRecycle=function(){var t=this._parentOrParents;return this._parentOrParents=null,this.unsubscribe(),this.closed=!1,this.isStopped=!1,this._parentOrParents=t,this},e}(a.w),f=function(t){function e(e,n,r,a){var u,s=t.call(this)||this;s._parentSubscriber=e;var c=s;return(0,i.m)(n)?u=n:n&&(u=n.next,r=n.error,a=n.complete,n!==o.c&&(c=Object.create(n),(0,i.m)(c.unsubscribe)&&s.add(c.unsubscribe.bind(c)),c.unsubscribe=s.unsubscribe.bind(s))),s._context=c,s._next=u,s._error=r,s._complete=a,s}return r.__extends(e,t),e.prototype.next=function(t){if(!this.isStopped&&this._next){var e=this._parentSubscriber;s.v.useDeprecatedSynchronousErrorHandling&&e.syncErrorThrowable?this.__tryOrSetError(e,this._next,t)&&this.unsubscribe():this.__tryOrUnsub(this._next,t)}},e.prototype.error=function(t){if(!this.isStopped){var e=this._parentSubscriber,n=s.v.useDeprecatedSynchronousErrorHandling;if(this._error)n&&e.syncErrorThrowable?(this.__tryOrSetError(e,this._error,t),this.unsubscribe()):(this.__tryOrUnsub(this._error,t),this.unsubscribe());else if(e.syncErrorThrowable)n?(e.syncErrorValue=t,e.syncErrorThrown=!0):(0,c.z)(t),this.unsubscribe();else{if(this.unsubscribe(),n)throw t;(0,c.z)(t)}}},e.prototype.complete=function(){var t=this;if(!this.isStopped){var e=this._parentSubscriber;if(this._complete){var n=function(){return t._complete.call(t._context)};s.v.useDeprecatedSynchronousErrorHandling&&e.syncErrorThrowable?(this.__tryOrSetError(e,n),this.unsubscribe()):(this.__tryOrUnsub(n),this.unsubscribe())}else this.unsubscribe()}},e.prototype.__tryOrUnsub=function(t,e){try{t.call(this._context,e)}catch(t){if(this.unsubscribe(),s.v.useDeprecatedSynchronousErrorHandling)throw t;(0,c.z)(t)}},e.prototype.__tryOrSetError=function(t,e,n){if(!s.v.useDeprecatedSynchronousErrorHandling)throw new Error("bad call");try{e.call(this._context,n)}catch(e){return s.v.useDeprecatedSynchronousErrorHandling?(t.syncErrorValue=e,t.syncErrorThrown=!0,!0):((0,c.z)(e),!0)}return!1},e.prototype._unsubscribe=function(){var t=this._parentSubscriber;this._context=null,this._parentSubscriber=null,t.unsubscribe()},e}(l)},75838:(t,e,n)=>{"use strict";n.d(e,{w:()=>s}),n(93942),n(70472),n(93270),n(88033),n(6550),n(38490),n(32345),n(40737),n(10951),n(5193);var r=n(24937),i=n(46308),o=n(11169),a=n(42135);function u(t){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},u(t)}var s=function(){function t(t){this.closed=!1,this._parentOrParents=null,this._subscriptions=null,t&&(this._ctorUnsubscribe=!0,this._unsubscribe=t)}var e;return t.prototype.unsubscribe=function(){var e;if(!this.closed){var n=this,u=n._parentOrParents,s=n._ctorUnsubscribe,d=n._unsubscribe,l=n._subscriptions;if(this.closed=!0,this._parentOrParents=null,this._subscriptions=null,u instanceof t)u.remove(this);else if(null!==u)for(var f=0;f{"use strict";n.d(e,{v:()=>i});var r=!1,i={Promise:void 0,set useDeprecatedSynchronousErrorHandling(t){t&&(new Error).stack,r=t},get useDeprecatedSynchronousErrorHandling(){return r}}},56431:(t,e,n)=>{"use strict";n.d(e,{Ds:()=>s,IY:()=>u,ft:()=>c});var r=n(61699),i=n(90782),o=n(64074),a=n(28817),u=function(t){function e(e){var n=t.call(this)||this;return n.parent=e,n}return r.__extends(e,t),e.prototype._next=function(t){this.parent.notifyNext(t)},e.prototype._error=function(t){this.parent.notifyError(t),this.unsubscribe()},e.prototype._complete=function(){this.parent.notifyComplete(),this.unsubscribe()},e}(i.L),s=(i.L,function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return r.__extends(e,t),e.prototype.notifyNext=function(t){this.destination.next(t)},e.prototype.notifyError=function(t){this.destination.error(t)},e.prototype.notifyComplete=function(){this.destination.complete()},e}(i.L));function c(t,e){if(!e.closed){if(t instanceof o.y)return t.subscribe(e);var n;try{n=(0,a.s)(t)(e)}catch(t){e.error(t)}return n}}i.L},46700:(t,e,n)=>{"use strict";n.d(e,{N:()=>d,c:()=>c});var r=n(61699),i=n(99357),o=n(64074),a=n(90782),u=n(75838),s=n(16807),c=function(t){function e(e,n){var r=t.call(this)||this;return r.source=e,r.subjectFactory=n,r._refCount=0,r._isComplete=!1,r}return r.__extends(e,t),e.prototype._subscribe=function(t){return this.getSubject().subscribe(t)},e.prototype.getSubject=function(){var t=this._subject;return t&&!t.isStopped||(this._subject=this.subjectFactory()),this._subject},e.prototype.connect=function(){var t=this._connection;return t||(this._isComplete=!1,(t=this._connection=new u.w).add(this.source.subscribe(new l(this.getSubject(),this))),t.closed&&(this._connection=null,t=u.w.EMPTY)),t},e.prototype.refCount=function(){return(0,s.x)()(this)},e}(o.y),d=function(){var t=c.prototype;return{operator:{value:null},_refCount:{value:0,writable:!0},_subject:{value:null,writable:!0},_connection:{value:null,writable:!0},_subscribe:{value:t._subscribe},_isComplete:{value:t._isComplete,writable:!0},getSubject:{value:t.getSubject},connect:{value:t.connect},refCount:{value:t.refCount}}}(),l=function(t){function e(e,n){var r=t.call(this,e)||this;return r.connectable=n,r}return r.__extends(e,t),e.prototype._error=function(e){this._unsubscribe(),t.prototype._error.call(this,e)},e.prototype._complete=function(){this.connectable._isComplete=!0,this._unsubscribe(),t.prototype._complete.call(this)},e.prototype._unsubscribe=function(){var t=this.connectable;if(t){this.connectable=null;var e=t._connection;t._refCount=0,t._subject=null,t._connection=null,e&&e.unsubscribe()}},e}(i.Yc);a.L},12206:(t,e,n)=>{"use strict";n.d(e,{Ms:()=>l,aj:()=>d}),n(38490),n(16516),n(40737),n(5193);var r=n(61699),i=n(79917),o=n(24937),a=n(64809),u=n(30121),s=n(42178),c={};function d(){for(var t=[],e=0;e{"use strict";n.d(e,{z:()=>o});var r=n(12309),i=n(54110);function o(){for(var t=[],e=0;e{"use strict";n.d(e,{P:()=>a});var r=n(64074),i=n(73531),o=n(14585);function a(t){return new r.y((function(e){var n;try{n=t()}catch(t){return void e.error(t)}return(n?(0,i.D)(n):(0,o.c)()).subscribe(e)}))}},14585:(t,e,n)=>{"use strict";n.d(e,{E:()=>i,c:()=>o});var r=n(64074),i=new r.y((function(t){return t.complete()}));function o(t){return t?function(t){return new r.y((function(e){return t.schedule((function(){return e.complete()}))}))}(t):i}},73531:(t,e,n)=>{"use strict";n.d(e,{D:()=>a});var r=n(64074),i=n(28817),o=n(77488);function a(t,e){return e?(0,o.x)(t,e):t instanceof r.y?t:new r.y((0,i.s)(t))}},42178:(t,e,n)=>{"use strict";n.d(e,{n:()=>a});var r=n(64074),i=n(97327),o=n(75077);function a(t,e){return e?(0,o.r)(t,e):new r.y((0,i.V)(t))}},55343:(t,e,n)=>{"use strict";n.d(e,{R:()=>u}),n(16516),n(40737),n(26667);var r=n(64074),i=n(24937),o=n(11169),a=n(92160);function u(t,e,n,c){return(0,o.m)(n)&&(c=n,n=void 0),c?u(t,e,n).pipe((0,a.U)((function(t){return(0,i.k)(t)?c.apply(void 0,t):c(t)}))):new r.y((function(r){s(t,e,(function(t){arguments.length>1?r.next(Array.prototype.slice.call(arguments)):r.next(t)}),r,n)}))}function s(t,e,n,r,i){var o;if(function(t){return t&&"function"==typeof t.addEventListener&&"function"==typeof t.removeEventListener}(t)){var a=t;t.addEventListener(e,n,i),o=function(){return a.removeEventListener(e,n,i)}}else if(function(t){return t&&"function"==typeof t.on&&"function"==typeof t.off}(t)){var u=t;t.on(e,n),o=function(){return u.off(e,n)}}else if(function(t){return t&&"function"==typeof t.addListener&&"function"==typeof t.removeListener}(t)){var c=t;t.addListener(e,n),o=function(){return c.removeListener(e,n)}}else{if(!t||!t.length)throw new TypeError("Invalid event target");for(var d=0,l=t.length;d{"use strict";n.d(e,{T:()=>u}),n(99023);var r=n(64074),i=n(79917),o=n(64688),a=n(42178);function u(){for(var t=[],e=0;e1&&"number"==typeof t[t.length-1]&&(n=t.pop())):"number"==typeof s&&(n=t.pop()),null===u&&1===t.length&&t[0]instanceof r.y?t[0]:(0,o.J)(n)((0,a.n)(t,u))}},12309:(t,e,n)=>{"use strict";n.d(e,{of:()=>a});var r=n(79917),i=n(42178),o=n(75077);function a(){for(var t=[],e=0;e{"use strict";n.d(e,{S3:()=>s});var r=n(61699),i=n(24937),o=n(42178),a=n(64809),u=n(30121);function s(){for(var t=[],e=0;e{"use strict";n.d(e,{_:()=>i});var r=n(64074);function i(t,e){return e?new r.y((function(n){return e.schedule(o,0,{error:t,subscriber:n})})):new r.y((function(e){return e.error(t)}))}function o(t){var e=t.error;t.subscriber.error(e)}},12670:(t,e,n)=>{"use strict";n.d(e,{H:()=>u}),n(99023);var r=n(64074),i=n(26858),o=n(13491),a=n(79917);function u(t,e,n){void 0===t&&(t=0);var u=-1;return(0,o.k)(e)?u=Number(e)<1?1:Number(e):(0,a.K)(e)&&(n=e),(0,a.K)(n)||(n=i.P),new r.y((function(e){var r=(0,o.k)(t)?t:+t-n.now();return n.schedule(s,r,{index:0,period:u,subscriber:e})}))}function s(t){var e=t.index,n=t.period,r=t.subscriber;if(r.next(e),!r.closed){if(-1===n)return r.complete();t.index=e+1,this.schedule(t,n)}}},66436:(t,e,n)=>{"use strict";n.d(e,{$R:()=>c,mx:()=>d});var r=n(61699),i=n(42178),o=n(24937),a=n(90782),u=n(42e3),s=n(56431);function c(){for(var t=[],e=0;ethis.index},t.prototype.hasCompleted=function(){return this.array.length===this.index},t}(),h=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.parent=n,i.observable=r,i.stillUnsubscribed=!0,i.buffer=[],i.isComplete=!1,i}return r.__extends(e,t),e.prototype[u.hZ]=function(){return this},e.prototype.next=function(){var t=this.buffer;return 0===t.length&&this.isComplete?{value:null,done:!0}:{value:t.shift(),done:!1}},e.prototype.hasValue=function(){return this.buffer.length>0},e.prototype.hasCompleted=function(){return 0===this.buffer.length&&this.isComplete},e.prototype.notifyComplete=function(){this.buffer.length>0?(this.isComplete=!0,this.parent.notifyInactive()):this.destination.complete()},e.prototype.notifyNext=function(t){this.buffer.push(t),this.parent.checkIterators()},e.prototype.subscribe=function(){return(0,s.ft)(this.observable,new s.IY(this))},e}(s.Ds)},63660:(t,e,n)=>{"use strict";n.d(e,{K:()=>o});var r=n(61699),i=n(56431);function o(t){return function(e){var n=new a(t),r=e.lift(n);return n.caught=r}}var a=function(){function t(t){this.selector=t}return t.prototype.call=function(t,e){return e.subscribe(new u(t,this.selector,this.caught))},t}(),u=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.selector=n,i.caught=r,i}return r.__extends(e,t),e.prototype.error=function(e){if(!this.isStopped){var n=void 0;try{n=this.selector(e,this.caught)}catch(e){return void t.prototype.error.call(this,e)}this._unsubscribeAndRecycle();var r=new i.IY(this);this.add(r);var o=(0,i.ft)(n,r);o!==r&&this.add(o)}},e}(i.Ds)},54110:(t,e,n)=>{"use strict";n.d(e,{u:()=>i});var r=n(64688);function i(){return(0,r.J)(1)}},5026:(t,e,n)=>{"use strict";n.d(e,{g:()=>s});var r=n(61699),i=n(26858),o=n(79903),a=n(90782),u=n(48811);function s(t,e){void 0===e&&(e=i.P);var n=(0,o.J)(t)?+t-e.now():Math.abs(t);return function(t){return t.lift(new c(n,e))}}var c=function(){function t(t,e){this.delay=t,this.scheduler=e}return t.prototype.call=function(t,e){return e.subscribe(new d(t,this.delay,this.scheduler))},t}(),d=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.delay=n,i.scheduler=r,i.queue=[],i.active=!1,i.errored=!1,i}return r.__extends(e,t),e.dispatch=function(t){for(var e=t.source,n=e.queue,r=t.scheduler,i=t.destination;n.length>0&&n[0].time-r.now()<=0;)n.shift().notification.observe(i);if(n.length>0){var o=Math.max(0,n[0].time-r.now());this.schedule(t,o)}else this.unsubscribe(),e.active=!1},e.prototype._schedule=function(t){this.active=!0,this.destination.add(t.schedule(e.dispatch,this.delay,{source:this,destination:this.destination,scheduler:t}))},e.prototype.scheduleNotification=function(t){if(!0!==this.errored){var e=this.scheduler,n=new l(e.now()+this.delay,t);this.queue.push(n),!1===this.active&&this._schedule(e)}},e.prototype._next=function(t){this.scheduleNotification(u.P.createNext(t))},e.prototype._error=function(t){this.errored=!0,this.queue=[],this.destination.error(t),this.unsubscribe()},e.prototype._complete=function(){this.scheduleNotification(u.P.createComplete()),this.unsubscribe()},e}(a.L),l=function(){return function(t,e){this.time=t,this.notification=e}}()},57603:(t,e,n)=>{"use strict";n.d(e,{x:()=>o});var r=n(61699),i=n(90782);function o(t,e){return function(n){return n.lift(new a(t,e))}}var a=function(){function t(t,e){this.compare=t,this.keySelector=e}return t.prototype.call=function(t,e){return e.subscribe(new u(t,this.compare,this.keySelector))},t}(),u=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.keySelector=r,i.hasKey=!1,"function"==typeof n&&(i.compare=n),i}return r.__extends(e,t),e.prototype.compare=function(t,e){return t===e},e.prototype._next=function(t){var e;try{var n=this.keySelector;e=n?n(t):t}catch(t){return this.destination.error(t)}var r=!1;if(this.hasKey)try{r=(0,this.compare)(this.key,e)}catch(t){return this.destination.error(t)}else this.hasKey=!0;r||(this.key=e,this.destination.next(t))},e}(i.L)},20239:(t,e,n)=>{"use strict";n.d(e,{h:()=>o});var r=n(61699),i=n(90782);function o(t,e){return function(n){return n.lift(new a(t,e))}}var a=function(){function t(t,e){this.predicate=t,this.thisArg=e}return t.prototype.call=function(t,e){return e.subscribe(new u(t,this.predicate,this.thisArg))},t}(),u=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.predicate=n,i.thisArg=r,i.count=0,i}return r.__extends(e,t),e.prototype._next=function(t){var e;try{e=this.predicate.call(this.thisArg,t,this.count++)}catch(t){return void this.destination.error(t)}e&&this.destination.next(t)},e}(i.L)},82727:(t,e,n)=>{"use strict";n.d(e,{T:()=>f,v:()=>s}),n(38490),n(34897),n(40737),n(10951),n(71806),n(5193);var r=n(61699),i=n(90782),o=n(75838),a=n(64074),u=n(99357);function s(t,e,n,r){return function(i){return i.lift(new c(t,e,n,r))}}var c=function(){function t(t,e,n,r){this.keySelector=t,this.elementSelector=e,this.durationSelector=n,this.subjectSelector=r}return t.prototype.call=function(t,e){return e.subscribe(new d(t,this.keySelector,this.elementSelector,this.durationSelector,this.subjectSelector))},t}(),d=function(t){function e(e,n,r,i,o){var a=t.call(this,e)||this;return a.keySelector=n,a.elementSelector=r,a.durationSelector=i,a.subjectSelector=o,a.groups=null,a.attemptedToUnsubscribe=!1,a.count=0,a}return r.__extends(e,t),e.prototype._next=function(t){var e;try{e=this.keySelector(t)}catch(t){return void this.error(t)}this._group(t,e)},e.prototype._group=function(t,e){var n=this.groups;n||(n=this.groups=new Map);var r,i=n.get(e);if(this.elementSelector)try{r=this.elementSelector(t)}catch(t){this.error(t)}else r=t;if(!i){i=this.subjectSelector?this.subjectSelector():new u.xQ,n.set(e,i);var o=new f(e,i,this);if(this.destination.next(o),this.durationSelector){var a=void 0;try{a=this.durationSelector(new f(e,i))}catch(t){return void this.error(t)}this.add(a.subscribe(new l(e,i,this)))}}i.closed||i.next(r)},e.prototype._error=function(t){var e=this.groups;e&&(e.forEach((function(e,n){e.error(t)})),e.clear()),this.destination.error(t)},e.prototype._complete=function(){var t=this.groups;t&&(t.forEach((function(t,e){t.complete()})),t.clear()),this.destination.complete()},e.prototype.removeGroup=function(t){this.groups.delete(t)},e.prototype.unsubscribe=function(){this.closed||(this.attemptedToUnsubscribe=!0,0===this.count&&t.prototype.unsubscribe.call(this))},e}(i.L),l=function(t){function e(e,n,r){var i=t.call(this,n)||this;return i.key=e,i.group=n,i.parent=r,i}return r.__extends(e,t),e.prototype._next=function(t){this.complete()},e.prototype._unsubscribe=function(){var t=this.parent,e=this.key;this.key=this.parent=null,t&&t.removeGroup(e)},e}(i.L),f=function(t){function e(e,n,r){var i=t.call(this)||this;return i.key=e,i.groupSubject=n,i.refCountSubscription=r,i}return r.__extends(e,t),e.prototype._subscribe=function(t){var e=new o.w,n=this.refCountSubscription,r=this.groupSubject;return n&&!n.closed&&e.add(new p(n)),e.add(r.subscribe(t)),e},e}(a.y),p=function(t){function e(e){var n=t.call(this)||this;return n.parent=e,e.count++,n}return r.__extends(e,t),e.prototype.unsubscribe=function(){var e=this.parent;e.closed||this.closed||(t.prototype.unsubscribe.call(this),e.count-=1,0===e.count&&e.attemptedToUnsubscribe&&e.unsubscribe())},e}(o.w)},92160:(t,e,n)=>{"use strict";n.d(e,{U:()=>o});var r=n(61699),i=n(90782);function o(t,e){return function(n){if("function"!=typeof t)throw new TypeError("argument is not a function. Are you looking for `mapTo()`?");return n.lift(new a(t,e))}}var a=function(){function t(t,e){this.project=t,this.thisArg=e}return t.prototype.call=function(t,e){return e.subscribe(new u(t,this.project,this.thisArg))},t}(),u=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.project=n,i.count=0,i.thisArg=r||i,i}return r.__extends(e,t),e.prototype._next=function(t){var e;try{e=this.project.call(this.thisArg,t,this.count++)}catch(t){return void this.destination.error(t)}this.destination.next(e)},e}(i.L)},64688:(t,e,n)=>{"use strict";n.d(e,{J:()=>o}),n(99023);var r=n(61693),i=n(16726);function o(t){return void 0===t&&(t=Number.POSITIVE_INFINITY),(0,r.zg)(i.y,t)}},61693:(t,e,n)=>{"use strict";n.d(e,{VS:()=>d,zg:()=>u}),n(99023);var r=n(61699),i=n(92160),o=n(73531),a=n(56431);function u(t,e,n){return void 0===n&&(n=Number.POSITIVE_INFINITY),"function"==typeof e?function(r){return r.pipe(u((function(n,r){return(0,o.D)(t(n,r)).pipe((0,i.U)((function(t,i){return e(n,t,r,i)})))}),n))}:("number"==typeof e&&(n=e),function(e){return e.lift(new s(t,n))})}var s=function(){function t(t,e){void 0===e&&(e=Number.POSITIVE_INFINITY),this.project=t,this.concurrent=e}return t.prototype.call=function(t,e){return e.subscribe(new c(t,this.project,this.concurrent))},t}(),c=function(t){function e(e,n,r){void 0===r&&(r=Number.POSITIVE_INFINITY);var i=t.call(this,e)||this;return i.project=n,i.concurrent=r,i.hasCompleted=!1,i.buffer=[],i.active=0,i.index=0,i}return r.__extends(e,t),e.prototype._next=function(t){this.active0?this._next(t.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()},e}(a.Ds),d=u},9202:(t,e,n)=>{"use strict";n.d(e,{QV:()=>a,ht:()=>s});var r=n(61699),i=n(90782),o=n(48811);function a(t,e){return void 0===e&&(e=0),function(n){return n.lift(new u(t,e))}}var u=function(){function t(t,e){void 0===e&&(e=0),this.scheduler=t,this.delay=e}return t.prototype.call=function(t,e){return e.subscribe(new s(t,this.scheduler,this.delay))},t}(),s=function(t){function e(e,n,r){void 0===r&&(r=0);var i=t.call(this,e)||this;return i.scheduler=n,i.delay=r,i}return r.__extends(e,t),e.dispatch=function(t){var e=t.notification,n=t.destination;e.observe(n),this.unsubscribe()},e.prototype.scheduleMessage=function(t){this.destination.add(this.scheduler.schedule(e.dispatch,this.delay,new c(t,this.destination)))},e.prototype._next=function(t){this.scheduleMessage(o.P.createNext(t))},e.prototype._error=function(t){this.scheduleMessage(o.P.createError(t)),this.unsubscribe()},e.prototype._complete=function(){this.scheduleMessage(o.P.createComplete()),this.unsubscribe()},e}(i.L),c=function(){return function(t,e){this.notification=t,this.destination=e}}()},16807:(t,e,n)=>{"use strict";n.d(e,{x:()=>o});var r=n(61699),i=n(90782);function o(){return function(t){return t.lift(new a(t))}}var a=function(){function t(t){this.connectable=t}return t.prototype.call=function(t,e){var n=this.connectable;n._refCount++;var r=new u(t,n),i=e.subscribe(r);return r.closed||(r.connection=n.connect()),i},t}(),u=function(t){function e(e,n){var r=t.call(this,e)||this;return r.connectable=n,r}return r.__extends(e,t),e.prototype._unsubscribe=function(){var t=this.connectable;if(t){this.connectable=null;var e=t._refCount;if(e<=0)this.connection=null;else if(t._refCount=e-1,e>1)this.connection=null;else{var n=this.connection,r=t._connection;this.connection=null,!r||n&&r!==n||r.unsubscribe()}}else this.connection=null},e}(i.L)},62156:(t,e,n)=>{"use strict";n.d(e,{a:()=>a});var r=n(61699),i=n(99357),o=n(56431);function a(t){return function(e){return e.lift(new u(t,e))}}var u=function(){function t(t,e){this.notifier=t,this.source=e}return t.prototype.call=function(t,e){return e.subscribe(new s(t,this.notifier,this.source))},t}(),s=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.notifier=n,i.source=r,i}return r.__extends(e,t),e.prototype.error=function(e){if(!this.isStopped){var n=this.errors,r=this.retries,a=this.retriesSubscription;if(r)this.errors=void 0,this.retriesSubscription=void 0;else{n=new i.xQ;try{r=(0,this.notifier)(n)}catch(e){return t.prototype.error.call(this,e)}a=(0,o.ft)(r,new o.IY(this))}this._unsubscribeAndRecycle(),this.errors=n,this.retries=r,this.retriesSubscription=a,n.next(e)}},e.prototype._unsubscribe=function(){var t=this.errors,e=this.retriesSubscription;t&&(t.unsubscribe(),this.errors=void 0),e&&(e.unsubscribe(),this.retriesSubscription=void 0),this.retries=void 0},e.prototype.notifyNext=function(){var t=this._unsubscribe;this._unsubscribe=null,this._unsubscribeAndRecycle(),this._unsubscribe=t,this.source.subscribe(this)},e}(o.Ds)},7263:(t,e,n)=>{"use strict";n.d(e,{d:()=>o}),n(93942),n(70472),n(93270),n(38490),n(99023),n(40737),n(10951),n(5193);var r=n(28646);function i(t){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i(t)}function o(t,e,n){var o;return o=t&&"object"===i(t)?t:{bufferSize:t,windowTime:e,refCount:!1,scheduler:n},function(t){return t.lift(function(t){var e,n,i=t.bufferSize,o=void 0===i?Number.POSITIVE_INFINITY:i,a=t.windowTime,u=void 0===a?Number.POSITIVE_INFINITY:a,s=t.refCount,c=t.scheduler,d=0,l=!1,f=!1;return function(t){var i;d++,!e||l?(l=!1,e=new r.t(o,u,c),i=e.subscribe(this),n=t.subscribe({next:function(t){e.next(t)},error:function(t){l=!0,e.error(t)},complete:function(){f=!0,n=void 0,e.complete()}}),f&&(n=void 0)):i=e.subscribe(this),this.add((function(){d--,i.unsubscribe(),i=void 0,n&&!f&&s&&0===d&&(n.unsubscribe(),n=void 0,e=void 0)}))}}(o))}}},64440:(t,e,n)=>{"use strict";n.d(e,{w:()=>u});var r=n(61699),i=n(92160),o=n(73531),a=n(56431);function u(t,e){return"function"==typeof e?function(n){return n.pipe(u((function(n,r){return(0,o.D)(t(n,r)).pipe((0,i.U)((function(t,i){return e(n,t,r,i)})))})))}:function(e){return e.lift(new s(t))}}var s=function(){function t(t){this.project=t}return t.prototype.call=function(t,e){return e.subscribe(new c(t,this.project))},t}(),c=function(t){function e(e,n){var r=t.call(this,e)||this;return r.project=n,r.index=0,r}return r.__extends(e,t),e.prototype._next=function(t){var e,n=this.index++;try{e=this.project(t,n)}catch(t){return void this.destination.error(t)}this._innerSub(e)},e.prototype._innerSub=function(t){var e=this.innerSubscription;e&&e.unsubscribe();var n=new a.IY(this),r=this.destination;r.add(n),this.innerSubscription=(0,a.ft)(t,n),this.innerSubscription!==n&&r.add(this.innerSubscription)},e.prototype._complete=function(){var e=this.innerSubscription;e&&!e.closed||t.prototype._complete.call(this),this.unsubscribe()},e.prototype._unsubscribe=function(){this.innerSubscription=void 0},e.prototype.notifyComplete=function(){this.innerSubscription=void 0,this.isStopped&&t.prototype._complete.call(this)},e.prototype.notifyNext=function(t){this.destination.next(t)},e}(a.Ds)},31407:(t,e,n)=>{"use strict";n.d(e,{q:()=>u});var r=n(61699),i=n(90782),o=n(4069),a=n(14585);function u(t){return function(e){return 0===t?(0,a.c)():e.lift(new s(t))}}var s=function(){function t(t){if(this.total=t,this.total<0)throw new o.W}return t.prototype.call=function(t,e){return e.subscribe(new c(t,this.total))},t}(),c=function(t){function e(e,n){var r=t.call(this,e)||this;return r.total=n,r.count=0,r}return r.__extends(e,t),e.prototype._next=function(t){var e=this.total,n=++this.count;n<=e&&(this.destination.next(t),n===e&&(this.destination.complete(),this.unsubscribe()))},e}(i.L)},75077:(t,e,n)=>{"use strict";n.d(e,{r:()=>o});var r=n(64074),i=n(75838);function o(t,e){return new r.y((function(n){var r=new i.w,o=0;return r.add(e.schedule((function(){o!==t.length?(n.next(t[o++]),n.closed||r.add(this.schedule())):n.complete()}))),r}))}},77488:(t,e,n)=>{"use strict";n.d(e,{x:()=>l}),n(93942),n(70472),n(93270),n(38490),n(40737),n(10951),n(5193);var r=n(64074),i=n(75838),o=n(86916),a=n(75077),u=n(42e3),s=n(18316),c=n(56554);function d(t){return d="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},d(t)}function l(t,e){if(null!=t){if(function(t){return t&&"function"==typeof t[o.L]}(t))return function(t,e){return new r.y((function(n){var r=new i.w;return r.add(e.schedule((function(){var i=t[o.L]();r.add(i.subscribe({next:function(t){r.add(e.schedule((function(){return n.next(t)})))},error:function(t){r.add(e.schedule((function(){return n.error(t)})))},complete:function(){r.add(e.schedule((function(){return n.complete()})))}}))}))),r}))}(t,e);if((0,s.t)(t))return function(t,e){return new r.y((function(n){var r=new i.w;return r.add(e.schedule((function(){return t.then((function(t){r.add(e.schedule((function(){n.next(t),r.add(e.schedule((function(){return n.complete()})))})))}),(function(t){r.add(e.schedule((function(){return n.error(t)})))}))}))),r}))}(t,e);if((0,c.z)(t))return(0,a.r)(t,e);if(function(t){return t&&"function"==typeof t[u.hZ]}(t)||"string"==typeof t)return function(t,e){if(!t)throw new Error("Iterable cannot be null");return new r.y((function(n){var r,o=new i.w;return o.add((function(){r&&"function"==typeof r.return&&r.return()})),o.add(e.schedule((function(){r=t[u.hZ](),o.add(e.schedule((function(){if(!n.closed){var t,e;try{var i=r.next();t=i.value,e=i.done}catch(t){return void n.error(t)}e?n.complete():(n.next(t),this.schedule())}})))}))),o}))}(t,e)}throw new TypeError((null!==t&&d(t)||t)+" is not observable")}},674:(t,e,n)=>{"use strict";n.d(e,{o:()=>i}),n(6550),n(32345);var r=n(61699),i=function(t){function e(e,n){var r=t.call(this,e,n)||this;return r.scheduler=e,r.work=n,r.pending=!1,r}return r.__extends(e,t),e.prototype.schedule=function(t,e){if(void 0===e&&(e=0),this.closed)return this;this.state=t;var n=this.id,r=this.scheduler;return null!=n&&(this.id=this.recycleAsyncId(r,n,e)),this.pending=!0,this.delay=e,this.id=this.id||this.requestAsyncId(r,this.id,e),this},e.prototype.requestAsyncId=function(t,e,n){return void 0===n&&(n=0),setInterval(t.flush.bind(t,this),n)},e.prototype.recycleAsyncId=function(t,e,n){if(void 0===n&&(n=0),null!==n&&this.delay===n&&!1===this.pending)return e;clearInterval(e)},e.prototype.execute=function(t,e){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var n=this._execute(t,e);if(n)return n;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,e){var n=!1,r=void 0;try{this.work(t)}catch(t){n=!0,r=!!t&&t||new Error(t)}if(n)return this.unsubscribe(),r},e.prototype._unsubscribe=function(){var t=this.id,e=this.scheduler,n=e.actions,r=n.indexOf(this);this.work=null,this.state=null,this.pending=!1,this.scheduler=null,-1!==r&&n.splice(r,1),null!=t&&(this.id=this.recycleAsyncId(e,t,null)),this.delay=null},e}(function(t){function e(e,n){return t.call(this)||this}return r.__extends(e,t),e.prototype.schedule=function(t,e){return void 0===e&&(e=0),this},e}(n(75838).w))},41978:(t,e,n)=>{"use strict";n.d(e,{v:()=>o});var r=n(61699),i=n(78379),o=function(t){function e(n,r){void 0===r&&(r=i.b.now);var o=t.call(this,n,(function(){return e.delegate&&e.delegate!==o?e.delegate.now():r()}))||this;return o.actions=[],o.active=!1,o.scheduled=void 0,o}return r.__extends(e,t),e.prototype.schedule=function(n,r,i){return void 0===r&&(r=0),e.delegate&&e.delegate!==this?e.delegate.schedule(n,r,i):t.prototype.schedule.call(this,n,r,i)},e.prototype.flush=function(t){var e=this.actions;if(this.active)e.push(t);else{var n;this.active=!0;do{if(n=t.execute(t.state,t.delay))break}while(t=e.shift());if(this.active=!1,n){for(;t=e.shift();)t.unsubscribe();throw n}}},e}(i.b)},18420:(t,e,n)=>{"use strict";n.d(e,{e:()=>d,E:()=>c});var r=n(61699),i=(n(13722),n(40737),n(83823),1),o=function(){return Promise.resolve()}(),a={};function u(t){return t in a&&(delete a[t],!0)}var s=function(t){function e(e,n){var r=t.call(this,e,n)||this;return r.scheduler=e,r.work=n,r}return r.__extends(e,t),e.prototype.requestAsyncId=function(e,n,r){return void 0===r&&(r=0),null!==r&&r>0?t.prototype.requestAsyncId.call(this,e,n,r):(e.actions.push(this),e.scheduled||(e.scheduled=(s=e.flush.bind(e,null),c=i++,a[c]=!0,o.then((function(){return u(c)&&s()})),c)));var s,c},e.prototype.recycleAsyncId=function(e,n,r){if(void 0===r&&(r=0),null!==r&&r>0||null===r&&this.delay>0)return t.prototype.recycleAsyncId.call(this,e,n,r);0===e.actions.length&&(u(n),e.scheduled=void 0)},e}(n(674).o),c=new(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return r.__extends(e,t),e.prototype.flush=function(t){this.active=!0,this.scheduled=void 0;var e,n=this.actions,r=-1,i=n.length;t=t||n.shift();do{if(e=t.execute(t.state,t.delay))break}while(++r{"use strict";n.d(e,{P:()=>o,z:()=>i});var r=n(674),i=new(n(41978).v)(r.o),o=i},30396:(t,e,n)=>{"use strict";n.d(e,{c:()=>a,N:()=>o});var r=n(61699),i=function(t){function e(e,n){var r=t.call(this,e,n)||this;return r.scheduler=e,r.work=n,r}return r.__extends(e,t),e.prototype.schedule=function(e,n){return void 0===n&&(n=0),n>0?t.prototype.schedule.call(this,e,n):(this.delay=n,this.state=e,this.scheduler.flush(this),this)},e.prototype.execute=function(e,n){return n>0||this.closed?t.prototype.execute.call(this,e,n):this._execute(e,n)},e.prototype.requestAsyncId=function(e,n,r){return void 0===r&&(r=0),null!==r&&r>0||null===r&&this.delay>0?t.prototype.requestAsyncId.call(this,e,n,r):e.flush(this)},e}(n(674).o),o=new(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return r.__extends(e,t),e}(n(41978).v))(i),a=o},42e3:(t,e,n)=>{"use strict";function r(){return"function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator"}n.d(e,{hZ:()=>i}),n(93942),n(70472),n(93270),n(38490),n(40737),n(10951),n(5193);var i=r()},86916:(t,e,n)=>{"use strict";n.d(e,{L:()=>r}),n(93942),n(70472),n(40737);var r=function(){return"function"==typeof Symbol&&Symbol.observable||"@@observable"}()},70239:(t,e,n)=>{"use strict";n.d(e,{b:()=>r}),n(93942),n(70472),n(40737);var r=function(){return"function"==typeof Symbol?Symbol("rxSubscriber"):"@@rxSubscriber_"+Math.random()}()},4069:(t,e,n)=>{"use strict";n.d(e,{W:()=>r}),n(34745);var r=function(){function t(){return Error.call(this),this.message="argument out of range",this.name="ArgumentOutOfRangeError",this}return t.prototype=Object.create(Error.prototype),t}()},2246:(t,e,n)=>{"use strict";n.d(e,{K:()=>r}),n(34745);var r=function(){function t(){return Error.call(this),this.message="no elements in sequence",this.name="EmptyError",this}return t.prototype=Object.create(Error.prototype),t}()},42046:(t,e,n)=>{"use strict";n.d(e,{N:()=>r}),n(34745);var r=function(){function t(){return Error.call(this),this.message="object unsubscribed",this.name="ObjectUnsubscribedError",this}return t.prototype=Object.create(Error.prototype),t}()},76960:(t,e,n)=>{"use strict";n.d(e,{W:()=>r}),n(34745);var r=function(){function t(){return Error.call(this),this.message="Timeout has occurred",this.name="TimeoutError",this}return t.prototype=Object.create(Error.prototype),t}()},42135:(t,e,n)=>{"use strict";n.d(e,{B:()=>r}),n(64668),n(95412),n(34745),n(40737),n(26667);var r=function(){function t(t){return Error.call(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(t,e){return e+1+") "+t.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t,this}return t.prototype=Object.create(Error.prototype),t}()},12411:(t,e,n)=>{"use strict";n.d(e,{_:()=>i});var r=n(90782);function i(t){for(;t;){var e=t,n=e.closed,i=e.destination,o=e.isStopped;if(n||o)return!1;t=i&&i instanceof r.L?i:null}return!0}},61554:(t,e,n)=>{"use strict";function r(t){setTimeout((function(){throw t}),0)}n.d(e,{z:()=>r})},16726:(t,e,n)=>{"use strict";function r(t){return t}n.d(e,{y:()=>r})},24937:(t,e,n)=>{"use strict";n.d(e,{k:()=>r});var r=function(){return Array.isArray||function(t){return t&&"number"==typeof t.length}}()},56554:(t,e,n)=>{"use strict";n.d(e,{z:()=>r});var r=function(t){return t&&"number"==typeof t.length&&"function"!=typeof t}},79903:(t,e,n)=>{"use strict";function r(t){return t instanceof Date&&!isNaN(+t)}n.d(e,{J:()=>r})},11169:(t,e,n)=>{"use strict";function r(t){return"function"==typeof t}n.d(e,{m:()=>r})},13491:(t,e,n)=>{"use strict";n.d(e,{k:()=>i}),n(83681);var r=n(24937);function i(t){return!(0,r.k)(t)&&t-parseFloat(t)+1>=0}},46308:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function i(t){return null!==t&&"object"===r(t)}n.d(e,{K:()=>i}),n(93942),n(70472),n(93270),n(38490),n(40737),n(10951),n(5193)},18316:(t,e,n)=>{"use strict";function r(t){return!!t&&"function"!=typeof t.subscribe&&"function"==typeof t.then}n.d(e,{t:()=>r})},79917:(t,e,n)=>{"use strict";function r(t){return t&&"function"==typeof t.schedule}n.d(e,{K:()=>r})},38375:(t,e,n)=>{"use strict";function r(){}n.d(e,{Z:()=>r})},70696:(t,e,n)=>{"use strict";function r(t,e){function n(){return!n.pred.apply(n.thisArg,arguments)}return n.pred=t,n.thisArg=e,n}n.d(e,{f:()=>r})},76252:(t,e,n)=>{"use strict";n.d(e,{U:()=>o,z:()=>i});var r=n(16726);function i(){for(var t=[],e=0;e{"use strict";n.d(e,{s:()=>d});var r=n(97327),i=n(61554),o=n(42e3),a=n(86916),u=n(56554),s=n(18316),c=n(46308),d=function(t){if(t&&"function"==typeof t[a.L])return d=t,function(t){var e=d[a.L]();if("function"!=typeof e.subscribe)throw new TypeError("Provided object does not correctly implement Symbol.observable");return e.subscribe(t)};if((0,u.z)(t))return(0,r.V)(t);if((0,s.t)(t))return n=t,function(t){return n.then((function(e){t.closed||(t.next(e),t.complete())}),(function(e){return t.error(e)})).then(null,i.z),t};if(t&&"function"==typeof t[o.hZ])return e=t,function(t){for(var n=e[o.hZ]();;){var r=void 0;try{r=n.next()}catch(e){return t.error(e),t}if(r.done){t.complete();break}if(t.next(r.value),t.closed)break}return"function"==typeof n.return&&t.add((function(){n.return&&n.return()})),t};var e,n,d,l=(0,c.K)(t)?"an invalid object":"'"+t+"'";throw new TypeError("You provided "+l+" where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.")}},97327:(t,e,n)=>{"use strict";n.d(e,{V:()=>r});var r=function(t){return function(e){for(var n=0,r=t.length;n{"use strict";n.d(e,{D:()=>u});var r=n(61699),i=function(t){function e(e,n,r){var i=t.call(this)||this;return i.parent=e,i.outerValue=n,i.outerIndex=r,i.index=0,i}return r.__extends(e,t),e.prototype._next=function(t){this.parent.notifyNext(this.outerValue,t,this.outerIndex,this.index++,this)},e.prototype._error=function(t){this.parent.notifyError(t,this),this.unsubscribe()},e.prototype._complete=function(){this.parent.notifyComplete(this),this.unsubscribe()},e}(n(90782).L),o=n(28817),a=n(64074);function u(t,e,n,r,u){if(void 0===u&&(u=new i(t,n,r)),!u.closed)return e instanceof a.y?e.subscribe(u):(0,o.s)(e)(u)}},54752:(t,e,n)=>{"use strict";n.d(e,{Y:()=>a});var r=n(90782),i=n(70239),o=n(43610);function a(t,e,n){if(t){if(t instanceof r.L)return t;if(t[i.b])return t[i.b]()}return t||e||n?new r.L(t,e,n):new r.L(o.c)}},11065:(t,e,n)=>{"use strict";n.r(e),n.d(e,{audit:()=>o,auditTime:()=>d,buffer:()=>l,bufferCount:()=>y,bufferTime:()=>b,bufferToggle:()=>x,bufferWhen:()=>M,catchError:()=>L.K,combineAll:()=>j,combineLatest:()=>q,concat:()=>G,concatAll:()=>V.u,concatMap:()=>H,concatMapTo:()=>W,count:()=>K,debounce:()=>J,debounceTime:()=>tt,defaultIfEmpty:()=>it,delay:()=>ut.g,delayWhen:()=>ct,dematerialize:()=>ht,distinct:()=>vt,distinctUntilChanged:()=>bt.x,distinctUntilKeyChanged:()=>St,elementAt:()=>xt,endWith:()=>kt,every:()=>Mt,exhaust:()=>Lt,exhaustMap:()=>Ft,expand:()=>Gt,filter:()=>Ct.h,finalize:()=>Ht,find:()=>Zt,findIndex:()=>Qt,first:()=>te,flatMap:()=>Y.VS,groupBy:()=>ee.v,ignoreElements:()=>ne,isEmpty:()=>oe,last:()=>fe,map:()=>Ut.U,mapTo:()=>pe,materialize:()=>ve,max:()=>Ie,merge:()=>Ae,mergeAll:()=>Oe.J,mergeMap:()=>Y.zg,mergeMapTo:()=>Te,mergeScan:()=>xe,min:()=>Me,multicast:()=>De,observeOn:()=>ze.QV,onErrorResumeNext:()=>je,pairwise:()=>qe,partition:()=>Ye,pluck:()=>He,publish:()=>Ke,publishBehavior:()=>$e,publishLast:()=>Qe,publishReplay:()=>tn,race:()=>nn,reduce:()=>Ee,refCount:()=>hn.x,repeat:()=>rn,repeatWhen:()=>un,retry:()=>dn,retryWhen:()=>pn.a,sample:()=>yn,sampleTime:()=>gn,scan:()=>be,sequenceEqual:()=>wn,share:()=>An,shareReplay:()=>On.d,single:()=>Tn,skip:()=>kn,skipLast:()=>Dn,skipUntil:()=>jn,skipWhile:()=>qn,startWith:()=>Vn,subscribeOn:()=>Kn,switchAll:()=>Jn,switchMap:()=>$n.w,switchMapTo:()=>Qn,take:()=>Tt.q,takeLast:()=>ce,takeUntil:()=>Xn,takeWhile:()=>nr,tap:()=>ur,throttle:()=>lr,throttleTime:()=>hr,throwIfEmpty:()=>It,timeInterval:()=>_r,timeout:()=>Ar,timeoutWith:()=>Cr,timestamp:()=>Or,toArray:()=>Rr,window:()=>kr,windowCount:()=>Dr,windowTime:()=>jr,windowToggle:()=>Yr,windowWhen:()=>Kr,withLatestFrom:()=>Jr,zip:()=>ei,zipAll:()=>ni});var r=n(61699),i=n(56431);function o(t){return function(e){return e.lift(new a(t))}}var a=function(){function t(t){this.durationSelector=t}return t.prototype.call=function(t,e){return e.subscribe(new u(t,this.durationSelector))},t}(),u=function(t){function e(e,n){var r=t.call(this,e)||this;return r.durationSelector=n,r.hasValue=!1,r}return r.__extends(e,t),e.prototype._next=function(t){if(this.value=t,this.hasValue=!0,!this.throttled){var e=void 0;try{e=(0,this.durationSelector)(t)}catch(t){return this.destination.error(t)}var n=(0,i.ft)(e,new i.IY(this));!n||n.closed?this.clearThrottle():this.add(this.throttled=n)}},e.prototype.clearThrottle=function(){var t=this,e=t.value,n=t.hasValue,r=t.throttled;r&&(this.remove(r),this.throttled=void 0,r.unsubscribe()),n&&(this.value=void 0,this.hasValue=!1,this.destination.next(e))},e.prototype.notifyNext=function(){this.clearThrottle()},e.prototype.notifyComplete=function(){this.clearThrottle()},e}(i.Ds),s=n(26858),c=n(12670);function d(t,e){return void 0===e&&(e=s.P),o((function(){return(0,c.H)(t,e)}))}function l(t){return function(e){return e.lift(new f(t))}}var f=function(){function t(t){this.closingNotifier=t}return t.prototype.call=function(t,e){return e.subscribe(new p(t,this.closingNotifier))},t}(),p=function(t){function e(e,n){var r=t.call(this,e)||this;return r.buffer=[],r.add((0,i.ft)(n,new i.IY(r))),r}return r.__extends(e,t),e.prototype._next=function(t){this.buffer.push(t)},e.prototype.notifyNext=function(){var t=this.buffer;this.buffer=[],this.destination.next(t)},e}(i.Ds),h=(n(32345),n(90782));function y(t,e){return void 0===e&&(e=null),function(n){return n.lift(new m(t,e))}}var m=function(){function t(t,e){this.bufferSize=t,this.startBufferEvery=e,this.subscriberClass=e&&t!==e?g:v}return t.prototype.call=function(t,e){return e.subscribe(new this.subscriberClass(t,this.bufferSize,this.startBufferEvery))},t}(),v=function(t){function e(e,n){var r=t.call(this,e)||this;return r.bufferSize=n,r.buffer=[],r}return r.__extends(e,t),e.prototype._next=function(t){var e=this.buffer;e.push(t),e.length==this.bufferSize&&(this.destination.next(e),this.buffer=[])},e.prototype._complete=function(){var e=this.buffer;e.length>0&&this.destination.next(e),t.prototype._complete.call(this)},e}(h.L),g=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.bufferSize=n,i.startBufferEvery=r,i.buffers=[],i.count=0,i}return r.__extends(e,t),e.prototype._next=function(t){var e=this,n=e.bufferSize,r=e.startBufferEvery,i=e.buffers,o=e.count;this.count++,o%r==0&&i.push([]);for(var a=i.length;a--;){var u=i[a];u.push(t),u.length===n&&(i.splice(a,1),this.destination.next(u))}},e.prototype._complete=function(){for(var e=this.buffers,n=this.destination;e.length>0;){var r=e.shift();r.length>0&&n.next(r)}t.prototype._complete.call(this)},e}(h.L),_=(n(6550),n(99023),n(79917));function b(t){var e=arguments.length,n=s.P;(0,_.K)(arguments[arguments.length-1])&&(n=arguments[arguments.length-1],e--);var r=null;e>=2&&(r=arguments[1]);var i=Number.POSITIVE_INFINITY;return e>=3&&(i=arguments[2]),function(e){return e.lift(new S(t,r,i,n))}}var S=function(){function t(t,e,n,r){this.bufferTimeSpan=t,this.bufferCreationInterval=e,this.maxBufferSize=n,this.scheduler=r}return t.prototype.call=function(t,e){return e.subscribe(new C(t,this.bufferTimeSpan,this.bufferCreationInterval,this.maxBufferSize,this.scheduler))},t}(),w=function(){return function(){this.buffer=[]}}(),C=function(t){function e(e,n,r,i,o){var a=t.call(this,e)||this;a.bufferTimeSpan=n,a.bufferCreationInterval=r,a.maxBufferSize=i,a.scheduler=o,a.contexts=[];var u=a.openContext();if(a.timespanOnly=null==r||r<0,a.timespanOnly){var s={subscriber:a,context:u,bufferTimeSpan:n};a.add(u.closeAction=o.schedule(E,n,s))}else{var c={subscriber:a,context:u},d={bufferTimeSpan:n,bufferCreationInterval:r,subscriber:a,scheduler:o};a.add(u.closeAction=o.schedule(P,n,c)),a.add(o.schedule(I,r,d))}return a}return r.__extends(e,t),e.prototype._next=function(t){for(var e,n=this.contexts,r=n.length,i=0;i0;){var r=e.shift();n.next(r.buffer)}t.prototype._complete.call(this)},e.prototype._unsubscribe=function(){this.contexts=null},e.prototype.onBufferFull=function(t){this.closeContext(t);var e=t.closeAction;if(e.unsubscribe(),this.remove(e),!this.closed&&this.timespanOnly){t=this.openContext();var n=this.bufferTimeSpan,r={subscriber:this,context:t,bufferTimeSpan:n};this.add(t.closeAction=this.scheduler.schedule(E,n,r))}},e.prototype.openContext=function(){var t=new w;return this.contexts.push(t),t},e.prototype.closeContext=function(t){this.destination.next(t.buffer);var e=this.contexts;(e?e.indexOf(t):-1)>=0&&e.splice(e.indexOf(t),1)},e}(h.L);function E(t){var e=t.subscriber,n=t.context;n&&e.closeContext(n),e.closed||(t.context=e.openContext(),t.context.closeAction=this.schedule(t,t.bufferTimeSpan))}function I(t){var e=t.bufferCreationInterval,n=t.bufferTimeSpan,r=t.subscriber,i=t.scheduler,o=r.openContext();r.closed||(r.add(o.closeAction=i.schedule(P,n,{subscriber:r,context:o})),this.schedule(t,e))}function P(t){var e=t.subscriber,n=t.context;e.closeContext(n)}var A=n(75838),O=n(30121),T=n(64809);function x(t,e){return function(n){return n.lift(new R(t,e))}}var R=function(){function t(t,e){this.openings=t,this.closingSelector=e}return t.prototype.call=function(t,e){return e.subscribe(new k(t,this.openings,this.closingSelector))},t}(),k=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.closingSelector=r,i.contexts=[],i.add((0,O.D)(i,n)),i}return r.__extends(e,t),e.prototype._next=function(t){for(var e=this.contexts,n=e.length,r=0;r0;){var r=n.shift();r.subscription.unsubscribe(),r.buffer=null,r.subscription=null}this.contexts=null,t.prototype._error.call(this,e)},e.prototype._complete=function(){for(var e=this.contexts;e.length>0;){var n=e.shift();this.destination.next(n.buffer),n.subscription.unsubscribe(),n.buffer=null,n.subscription=null}this.contexts=null,t.prototype._complete.call(this)},e.prototype.notifyNext=function(t,e){t?this.closeBuffer(t):this.openBuffer(e)},e.prototype.notifyComplete=function(t){this.closeBuffer(t.context)},e.prototype.openBuffer=function(t){try{var e=this.closingSelector.call(this,t);e&&this.trySubscribe(e)}catch(t){this._error(t)}},e.prototype.closeBuffer=function(t){var e=this.contexts;if(e&&t){var n=t.buffer,r=t.subscription;this.destination.next(n),e.splice(e.indexOf(t),1),this.remove(r),r.unsubscribe()}},e.prototype.trySubscribe=function(t){var e=this.contexts,n=new A.w,r={buffer:[],subscription:n};e.push(r);var i=(0,O.D)(this,t,r);!i||i.closed?this.closeBuffer(r):(i.context=r,this.add(i),n.add(i))},e}(T.L);function M(t){return function(e){return e.lift(new N(t))}}var N=function(){function t(t){this.closingSelector=t}return t.prototype.call=function(t,e){return e.subscribe(new D(t,this.closingSelector))},t}(),D=function(t){function e(e,n){var r=t.call(this,e)||this;return r.closingSelector=n,r.subscribing=!1,r.openBuffer(),r}return r.__extends(e,t),e.prototype._next=function(t){this.buffer.push(t)},e.prototype._complete=function(){var e=this.buffer;e&&this.destination.next(e),t.prototype._complete.call(this)},e.prototype._unsubscribe=function(){this.buffer=void 0,this.subscribing=!1},e.prototype.notifyNext=function(){this.openBuffer()},e.prototype.notifyComplete=function(){this.subscribing?this.complete():this.openBuffer()},e.prototype.openBuffer=function(){var t=this.closingSubscription;t&&(this.remove(t),t.unsubscribe());var e,n=this.buffer;this.buffer&&this.destination.next(n),this.buffer=[];try{e=(0,this.closingSelector)()}catch(t){return this.error(t)}t=new A.w,this.closingSubscription=t,this.add(t),this.subscribing=!0,t.add((0,i.ft)(e,new i.IY(this))),this.subscribing=!1},e}(i.Ds),L=n(63660),z=n(12206);function j(t){return function(e){return e.lift(new z.Ms(t))}}n(88033),n(16516);var U=n(24937),F=n(73531);function q(){for(var t=[],e=0;e=2;return function(r){return r.pipe((0,Ct.h)((function(e,n){return n===t})),(0,Tt.q)(1),n?it(e):It((function(){return new wt.W})))}}var Rt=n(12309);function kt(){for(var t=[],e=0;e0&&this._next(t.shift()),this.hasCompleted&&0===this.active&&this.destination.complete()},e}(i.Ds);function Ht(t){return function(e){return e.lift(new Wt(t))}}var Wt=function(){function t(t){this.callback=t}return t.prototype.call=function(t,e){return e.subscribe(new Kt(t,this.callback))},t}(),Kt=function(t){function e(e,n){var r=t.call(this,e)||this;return r.add(new A.w(n)),r}return r.__extends(e,t),e}(h.L);function Zt(t,e){if("function"!=typeof t)throw new TypeError("predicate is not a function");return function(n){return n.lift(new $t(t,n,!1,e))}}var $t=function(){function t(t,e,n,r){this.predicate=t,this.source=e,this.yieldIndex=n,this.thisArg=r}return t.prototype.call=function(t,e){return e.subscribe(new Jt(t,this.predicate,this.source,this.yieldIndex,this.thisArg))},t}(),Jt=function(t){function e(e,n,r,i,o){var a=t.call(this,e)||this;return a.predicate=n,a.source=r,a.yieldIndex=i,a.thisArg=o,a.index=0,a}return r.__extends(e,t),e.prototype.notifyComplete=function(t){var e=this.destination;e.next(t),e.complete(),this.unsubscribe()},e.prototype._next=function(t){var e=this.predicate,n=this.thisArg,r=this.index++;try{e.call(n||this,t,r,this.source)&&this.notifyComplete(this.yieldIndex?r:t)}catch(t){this.destination.error(t)}},e.prototype._complete=function(){this.notifyComplete(this.yieldIndex?-1:void 0)},e}(h.L);function Qt(t,e){return function(n){return n.lift(new $t(t,n,!0,e))}}var Xt=n(16726);function te(t,e){var n=arguments.length>=2;return function(r){return r.pipe(t?(0,Ct.h)((function(e,n){return t(e,n,r)})):Xt.y,(0,Tt.q)(1),n?it(e):It((function(){return new Et.K})))}}var ee=n(82727);function ne(){return function(t){return t.lift(new re)}}var re=function(){function t(){}return t.prototype.call=function(t,e){return e.subscribe(new ie(t))},t}(),ie=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return r.__extends(e,t),e.prototype._next=function(t){},e}(h.L);function oe(){return function(t){return t.lift(new ae)}}var ae=function(){function t(){}return t.prototype.call=function(t,e){return e.subscribe(new ue(t))},t}(),ue=function(t){function e(e){return t.call(this,e)||this}return r.__extends(e,t),e.prototype.notifyComplete=function(t){var e=this.destination;e.next(t),e.complete()},e.prototype._next=function(t){this.notifyComplete(!1)},e.prototype._complete=function(){this.notifyComplete(!0)},e}(h.L),se=n(14585);function ce(t){return function(e){return 0===t?(0,se.c)():e.lift(new de(t))}}var de=function(){function t(t){if(this.total=t,this.total<0)throw new wt.W}return t.prototype.call=function(t,e){return e.subscribe(new le(t,this.total))},t}(),le=function(t){function e(e,n){var r=t.call(this,e)||this;return r.total=n,r.ring=new Array,r.count=0,r}return r.__extends(e,t),e.prototype._next=function(t){var e=this.ring,n=this.total,r=this.count++;e.length0)for(var n=this.count>=this.total?this.total:this.count,r=this.ring,i=0;i=2;return function(r){return r.pipe(t?(0,Ct.h)((function(e,n){return t(e,n,r)})):Xt.y,ce(1),n?it(e):It((function(){return new Et.K})))}}function pe(t){return function(e){return e.lift(new he(t))}}var he=function(){function t(t){this.value=t}return t.prototype.call=function(t,e){return e.subscribe(new ye(t,this.value))},t}(),ye=function(t){function e(e,n){var r=t.call(this,e)||this;return r.value=n,r}return r.__extends(e,t),e.prototype._next=function(t){this.destination.next(this.value)},e}(h.L),me=n(48811);function ve(){return function(t){return t.lift(new ge)}}var ge=function(){function t(){}return t.prototype.call=function(t,e){return e.subscribe(new _e(t))},t}(),_e=function(t){function e(e){return t.call(this,e)||this}return r.__extends(e,t),e.prototype._next=function(t){this.destination.next(me.P.createNext(t))},e.prototype._error=function(t){var e=this.destination;e.next(me.P.createError(t)),e.complete()},e.prototype._complete=function(){var t=this.destination;t.next(me.P.createComplete()),t.complete()},e}(h.L);function be(t,e){var n=!1;return arguments.length>=2&&(n=!0),function(r){return r.lift(new Se(t,e,n))}}var Se=function(){function t(t,e,n){void 0===n&&(n=!1),this.accumulator=t,this.seed=e,this.hasSeed=n}return t.prototype.call=function(t,e){return e.subscribe(new we(t,this.accumulator,this.seed,this.hasSeed))},t}(),we=function(t){function e(e,n,r,i){var o=t.call(this,e)||this;return o.accumulator=n,o._seed=r,o.hasSeed=i,o.index=0,o}return r.__extends(e,t),Object.defineProperty(e.prototype,"seed",{get:function(){return this._seed},set:function(t){this.hasSeed=!0,this._seed=t},enumerable:!0,configurable:!0}),e.prototype._next=function(t){if(this.hasSeed)return this._tryNext(t);this.seed=t,this.destination.next(t)},e.prototype._tryNext=function(t){var e,n=this.index++;try{e=this.accumulator(this.seed,t,n)}catch(t){this.destination.error(t)}this.seed=e,this.destination.next(e)},e}(h.L),Ce=n(76252);function Ee(t,e){return arguments.length>=2?function(n){return(0,Ce.z)(be(t,e),ce(1),it(e))(n)}:function(e){return(0,Ce.z)(be((function(e,n,r){return t(e,n,r+1)})),ce(1))(e)}}function Ie(t){return Ee("function"==typeof t?function(e,n){return t(e,n)>0?e:n}:function(t,e){return t>e?t:e})}var Pe=n(48864);function Ae(){for(var t=[],e=0;e0?this._next(t.shift()):0===this.active&&this.hasCompleted&&(!1===this.hasValue&&this.destination.next(this.acc),this.destination.complete())},e}(i.Ds);function Me(t){return Ee("function"==typeof t?function(e,n){return t(e,n)<0?e:n}:function(t,e){return t-1&&(this.count=n-1),e.subscribe(this._unsubscribeAndRecycle())}},e}(h.L);function un(t){return function(e){return e.lift(new sn(t))}}var sn=function(){function t(t){this.notifier=t}return t.prototype.call=function(t,e){return e.subscribe(new cn(t,this.notifier,e))},t}(),cn=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.notifier=n,i.source=r,i.sourceIsBeingSubscribedTo=!0,i}return r.__extends(e,t),e.prototype.notifyNext=function(){this.sourceIsBeingSubscribedTo=!0,this.source.subscribe(this)},e.prototype.notifyComplete=function(){if(!1===this.sourceIsBeingSubscribedTo)return t.prototype.complete.call(this)},e.prototype.complete=function(){if(this.sourceIsBeingSubscribedTo=!1,!this.isStopped){if(this.retries||this.subscribeToRetries(),!this.retriesSubscription||this.retriesSubscription.closed)return t.prototype.complete.call(this);this._unsubscribeAndRecycle(),this.notifications.next(void 0)}},e.prototype._unsubscribe=function(){var t=this.notifications,e=this.retriesSubscription;t&&(t.unsubscribe(),this.notifications=void 0),e&&(e.unsubscribe(),this.retriesSubscription=void 0),this.retries=void 0},e.prototype._unsubscribeAndRecycle=function(){var e=this._unsubscribe;return this._unsubscribe=null,t.prototype._unsubscribeAndRecycle.call(this),this._unsubscribe=e,this},e.prototype.subscribeToRetries=function(){var e;this.notifications=new We.xQ;try{e=(0,this.notifier)(this.notifications)}catch(e){return t.prototype.complete.call(this)}this.retries=e,this.retriesSubscription=(0,i.ft)(e,new i.IY(this))},e}(i.Ds);function dn(t){return void 0===t&&(t=-1),function(e){return e.lift(new ln(t,e))}}var ln=function(){function t(t,e){this.count=t,this.source=e}return t.prototype.call=function(t,e){return e.subscribe(new fn(t,this.count,this.source))},t}(),fn=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.count=n,i.source=r,i}return r.__extends(e,t),e.prototype.error=function(e){if(!this.isStopped){var n=this.source,r=this.count;if(0===r)return t.prototype.error.call(this,e);r>-1&&(this.count=r-1),n.subscribe(this._unsubscribeAndRecycle())}},e}(h.L),pn=n(62156),hn=n(16807);function yn(t){return function(e){return e.lift(new mn(t))}}var mn=function(){function t(t){this.notifier=t}return t.prototype.call=function(t,e){var n=new vn(t),r=e.subscribe(n);return r.add((0,i.ft)(this.notifier,new i.IY(n))),r},t}(),vn=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.hasValue=!1,e}return r.__extends(e,t),e.prototype._next=function(t){this.value=t,this.hasValue=!0},e.prototype.notifyNext=function(){this.emitValue()},e.prototype.notifyComplete=function(){this.emitValue()},e.prototype.emitValue=function(){this.hasValue&&(this.hasValue=!1,this.destination.next(this.value))},e}(i.Ds);function gn(t,e){return void 0===e&&(e=s.P),function(n){return n.lift(new _n(t,e))}}var _n=function(){function t(t,e){this.period=t,this.scheduler=e}return t.prototype.call=function(t,e){return e.subscribe(new bn(t,this.period,this.scheduler))},t}(),bn=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.period=n,i.scheduler=r,i.hasValue=!1,i.add(r.schedule(Sn,n,{subscriber:i,period:n})),i}return r.__extends(e,t),e.prototype._next=function(t){this.lastValue=t,this.hasValue=!0},e.prototype.notifyNext=function(){this.hasValue&&(this.hasValue=!1,this.destination.next(this.lastValue))},e}(h.L);function Sn(t){var e=t.subscriber,n=t.period;e.notifyNext(),this.schedule(t,n)}function wn(t,e){return function(n){return n.lift(new Cn(t,e))}}var Cn=function(){function t(t,e){this.compareTo=t,this.comparator=e}return t.prototype.call=function(t,e){return e.subscribe(new En(t,this.compareTo,this.comparator))},t}(),En=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.compareTo=n,i.comparator=r,i._a=[],i._b=[],i._oneComplete=!1,i.destination.add(n.subscribe(new In(e,i))),i}return r.__extends(e,t),e.prototype._next=function(t){this._oneComplete&&0===this._b.length?this.emit(!1):(this._a.push(t),this.checkValues())},e.prototype._complete=function(){this._oneComplete?this.emit(0===this._a.length&&0===this._b.length):this._oneComplete=!0,this.unsubscribe()},e.prototype.checkValues=function(){for(var t=this,e=t._a,n=t._b,r=t.comparator;e.length>0&&n.length>0;){var i=e.shift(),o=n.shift(),a=!1;try{a=r?r(i,o):i===o}catch(t){this.destination.error(t)}a||this.emit(!1)}},e.prototype.emit=function(t){var e=this.destination;e.next(t),e.complete()},e.prototype.nextB=function(t){this._oneComplete&&0===this._a.length?this.emit(!1):(this._b.push(t),this.checkValues())},e.prototype.completeB=function(){this._oneComplete?this.emit(0===this._a.length&&0===this._b.length):this._oneComplete=!0},e}(h.L),In=function(t){function e(e,n){var r=t.call(this,e)||this;return r.parent=n,r}return r.__extends(e,t),e.prototype._next=function(t){this.parent.nextB(t)},e.prototype._error=function(t){this.parent.error(t),this.unsubscribe()},e.prototype._complete=function(){this.parent.completeB(),this.unsubscribe()},e}(h.L);function Pn(){return new We.xQ}function An(){return function(t){return(0,hn.x)()(De(Pn)(t))}}var On=n(7263);function Tn(t){return function(e){return e.lift(new xn(t,e))}}var xn=function(){function t(t,e){this.predicate=t,this.source=e}return t.prototype.call=function(t,e){return e.subscribe(new Rn(t,this.predicate,this.source))},t}(),Rn=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.predicate=n,i.source=r,i.seenValue=!1,i.index=0,i}return r.__extends(e,t),e.prototype.applySingleValue=function(t){this.seenValue?this.destination.error("Sequence contains more than one element"):(this.seenValue=!0,this.singleValue=t)},e.prototype._next=function(t){var e=this.index++;this.predicate?this.tryNext(t,e):this.applySingleValue(t)},e.prototype.tryNext=function(t,e){try{this.predicate(t,e,this.source)&&this.applySingleValue(t)}catch(t){this.destination.error(t)}},e.prototype._complete=function(){var t=this.destination;this.index>0?(t.next(this.seenValue?this.singleValue:void 0),t.complete()):t.error(new Et.K)},e}(h.L);function kn(t){return function(e){return e.lift(new Mn(t))}}var Mn=function(){function t(t){this.total=t}return t.prototype.call=function(t,e){return e.subscribe(new Nn(t,this.total))},t}(),Nn=function(t){function e(e,n){var r=t.call(this,e)||this;return r.total=n,r.count=0,r}return r.__extends(e,t),e.prototype._next=function(t){++this.count>this.total&&this.destination.next(t)},e}(h.L);function Dn(t){return function(e){return e.lift(new Ln(t))}}var Ln=function(){function t(t){if(this._skipCount=t,this._skipCount<0)throw new wt.W}return t.prototype.call=function(t,e){return 0===this._skipCount?e.subscribe(new h.L(t)):e.subscribe(new zn(t,this._skipCount))},t}(),zn=function(t){function e(e,n){var r=t.call(this,e)||this;return r._skipCount=n,r._count=0,r._ring=new Array(n),r}return r.__extends(e,t),e.prototype._next=function(t){var e=this._skipCount,n=this._count++;if(n0?this.startWindowEvery:this.windowSize,n=this.destination,r=this.windowSize,i=this.windows,o=i.length,a=0;a=0&&u%e==0&&!this.closed&&i.shift().complete(),++this.count%e==0&&!this.closed){var s=new We.xQ;i.push(s),n.next(s)}},e.prototype._error=function(t){var e=this.windows;if(e)for(;e.length>0&&!this.closed;)e.shift().error(t);this.destination.error(t)},e.prototype._complete=function(){var t=this.windows;if(t)for(;t.length>0&&!this.closed;)t.shift().complete();this.destination.complete()},e.prototype._unsubscribe=function(){this.count=0,this.windows=null},e}(h.L);function jr(t){var e=s.P,n=null,r=Number.POSITIVE_INFINITY;return(0,_.K)(arguments[3])&&(e=arguments[3]),(0,_.K)(arguments[2])?e=arguments[2]:(0,Hn.k)(arguments[2])&&(r=Number(arguments[2])),(0,_.K)(arguments[1])?e=arguments[1]:(0,Hn.k)(arguments[1])&&(n=Number(arguments[1])),function(i){return i.lift(new Ur(t,n,r,e))}}var Ur=function(){function t(t,e,n,r){this.windowTimeSpan=t,this.windowCreationInterval=e,this.maxWindowSize=n,this.scheduler=r}return t.prototype.call=function(t,e){return e.subscribe(new qr(t,this.windowTimeSpan,this.windowCreationInterval,this.maxWindowSize,this.scheduler))},t}(),Fr=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._numberOfNextedValues=0,e}return r.__extends(e,t),e.prototype.next=function(e){this._numberOfNextedValues++,t.prototype.next.call(this,e)},Object.defineProperty(e.prototype,"numberOfNextedValues",{get:function(){return this._numberOfNextedValues},enumerable:!0,configurable:!0}),e}(We.xQ),qr=function(t){function e(e,n,r,i,o){var a=t.call(this,e)||this;a.destination=e,a.windowTimeSpan=n,a.windowCreationInterval=r,a.maxWindowSize=i,a.scheduler=o,a.windows=[];var u=a.openWindow();if(null!==r&&r>=0){var s={subscriber:a,window:u,context:null},c={windowTimeSpan:n,windowCreationInterval:r,subscriber:a,scheduler:o};a.add(o.schedule(Vr,n,s)),a.add(o.schedule(Gr,r,c))}else{var d={subscriber:a,window:u,windowTimeSpan:n};a.add(o.schedule(Br,n,d))}return a}return r.__extends(e,t),e.prototype._next=function(t){for(var e=this.windows,n=e.length,r=0;r=this.maxWindowSize&&this.closeWindow(i))}},e.prototype._error=function(t){for(var e=this.windows;e.length>0;)e.shift().error(t);this.destination.error(t)},e.prototype._complete=function(){for(var t=this.windows;t.length>0;){var e=t.shift();e.closed||e.complete()}this.destination.complete()},e.prototype.openWindow=function(){var t=new Fr;return this.windows.push(t),this.destination.next(t),t},e.prototype.closeWindow=function(t){t.complete();var e=this.windows;e.splice(e.indexOf(t),1)},e}(h.L);function Br(t){var e=t.subscriber,n=t.windowTimeSpan,r=t.window;r&&e.closeWindow(r),t.window=e.openWindow(),this.schedule(t,n)}function Gr(t){var e=t.windowTimeSpan,n=t.subscriber,r=t.scheduler,i=t.windowCreationInterval,o=n.openWindow(),a=this,u={action:a,subscription:null},s={subscriber:n,window:o,context:u};u.subscription=r.schedule(Vr,e,s),a.add(u.subscription),a.schedule(t,i)}function Vr(t){var e=t.subscriber,n=t.window,r=t.context;r&&r.action&&r.subscription&&r.action.remove(r.subscription),e.closeWindow(n)}function Yr(t,e){return function(n){return n.lift(new Hr(t,e))}}var Hr=function(){function t(t,e){this.openings=t,this.closingSelector=e}return t.prototype.call=function(t,e){return e.subscribe(new Wr(t,this.openings,this.closingSelector))},t}(),Wr=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.openings=n,i.closingSelector=r,i.contexts=[],i.add(i.openSubscription=(0,O.D)(i,n,n)),i}return r.__extends(e,t),e.prototype._next=function(t){var e=this.contexts;if(e)for(var n=e.length,r=0;r0){var i=r.indexOf(n);-1!==i&&r.splice(i,1)}},e.prototype.notifyComplete=function(){},e.prototype._next=function(t){if(0===this.toRespond.length){var e=[t].concat(this.values);this.project?this._tryProject(e):this.destination.next(e)}},e.prototype._tryProject=function(t){var e;try{e=this.project.apply(this,t)}catch(t){return void this.destination.error(t)}this.destination.next(e)},e}(T.L),ti=n(66436);function ei(){for(var t=[],e=0;e{function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(38490),n(13722),n(40737),n(10951),n(5193),t.exports=function(t,e,n,i){var o=n?n.call(i,t,e):void 0;if(void 0!==o)return!!o;if(t===e)return!0;if("object"!==r(t)||!t||"object"!==r(e)||!e)return!1;var a=Object.keys(t),u=Object.keys(e);if(a.length!==u.length)return!1;for(var s=Object.prototype.hasOwnProperty.bind(e),c=0;c{"use strict";n(6550),n(16516),t.exports=function(t,e){if("string"!=typeof t||"string"!=typeof e)throw new TypeError("Expected the arguments to be of type `string`");if(""===e)return[t];var n=t.indexOf(e);return-1===n?[t]:[t.slice(0,n),t.slice(n+e.length)]}},29590:(t,e,n)=>{"use strict";n(40737),n(26667),n(58443),t.exports=function(t){return encodeURIComponent(t).replace(/[!'()*]/g,(function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()}))}},61699:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n.r(e),n.d(e,{__assign:()=>a,__asyncDelegator:()=>S,__asyncGenerator:()=>b,__asyncValues:()=>w,__await:()=>_,__awaiter:()=>l,__classPrivateFieldGet:()=>P,__classPrivateFieldSet:()=>A,__createBinding:()=>p,__decorate:()=>s,__exportStar:()=>h,__extends:()=>o,__generator:()=>f,__importDefault:()=>I,__importStar:()=>E,__makeTemplateObject:()=>C,__metadata:()=>d,__param:()=>c,__read:()=>m,__rest:()=>u,__spread:()=>v,__spreadArrays:()=>g,__values:()=>y}),n(93942),n(70472),n(9190),n(93270),n(88033),n(6550),n(38490),n(27835),n(19926),n(28101),n(40737),n(83823),n(10951),n(5193);var i=function(t,e){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])},i(t,e)};function o(t,e){function n(){this.constructor=t}i(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var a=function(){return a=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=0;s--)(o=t[s])&&(u=(a<3?o(u):a>3?o(e,n,u):o(e,n))||u);return a>3&&u&&Object.defineProperty(e,n,u),u}function c(t,e){return function(n,r){e(n,r,t)}}function d(t,e){if("object"===("undefined"==typeof Reflect?"undefined":r(Reflect))&&"function"==typeof Reflect.metadata)return Reflect.metadata(t,e)}function l(t,e,n,r){return new(n||(n=Promise))((function(i,o){function a(t){try{s(r.next(t))}catch(t){o(t)}}function u(t){try{s(r.throw(t))}catch(t){o(t)}}function s(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,u)}s((r=r.apply(t,e||[])).next())}))}function f(t,e){var n,r,i,o,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function m(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,i,o=n.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(r=o.next()).done;)a.push(r.value)}catch(t){i={error:t}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return a}function v(){for(var t=[],e=0;e1||u(t,e)}))})}function u(t,e){try{(n=i[t](e)).value instanceof _?Promise.resolve(n.value.v).then(s,c):d(o[0][2],n)}catch(t){d(o[0][3],t)}var n}function s(t){u("next",t)}function c(t){u("throw",t)}function d(t,e){t(e),o.shift(),o.length&&u(o[0][0],o[0][1])}}function S(t){var e,n;return e={},r("next"),r("throw",(function(t){throw t})),r("return"),e[Symbol.iterator]=function(){return this},e;function r(r,i){e[r]=t[r]?function(e){return(n=!n)?{value:_(t[r](e)),done:"return"===r}:i?i(e):e}:i}}function w(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,n=t[Symbol.asyncIterator];return n?n.call(t):(t=y(t),e={},r("next"),r("throw"),r("return"),e[Symbol.asyncIterator]=function(){return this},e);function r(n){e[n]=t[n]&&function(e){return new Promise((function(r,i){!function(t,e,n,r){Promise.resolve(r).then((function(e){t({value:e,done:n})}),e)}(r,i,(e=t[n](e)).done,e.value)}))}}}function C(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function E(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function I(t){return t&&t.__esModule?t:{default:t}}function P(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function A(t,e,n){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,n),n}},86173:(t,e,n)=>{var r=n(34028),i=n(84160),o=TypeError;t.exports=function(t){if(r(t))return t;throw o(i(t)+" is not a function")}},52023:(t,e,n)=>{var r=n(78449),i=n(84160),o=TypeError;t.exports=function(t){if(r(t))return t;throw o(i(t)+" is not a constructor")}},41684:(t,e,n)=>{var r=n(34028),i=String,o=TypeError;t.exports=function(t){if("object"==typeof t||r(t))return t;throw o("Can't set "+i(t)+" as a prototype")}},47512:(t,e,n)=>{var r=n(30191),i=n(13250),o=n(43087).f,a=r("unscopables"),u=Array.prototype;null==u[a]&&o(u,a,{configurable:!0,value:i(null)}),t.exports=function(t){u[a][t]=!0}},75527:(t,e,n)=>{"use strict";var r=n(58402).charAt;t.exports=function(t,e,n){return e+(n?r(t,e).length:1)}},39837:(t,e,n)=>{var r=n(27357),i=TypeError;t.exports=function(t,e){if(r(e,t))return t;throw i("Incorrect invocation")}},52546:(t,e,n)=>{var r=n(51355),i=String,o=TypeError;t.exports=function(t){if(r(t))return t;throw o(i(t)+" is not an object")}},68096:t=>{t.exports="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView},1743:(t,e,n)=>{var r=n(38986);t.exports=r((function(){if("function"==typeof ArrayBuffer){var t=new ArrayBuffer(8);Object.isExtensible(t)&&Object.defineProperty(t,"a",{value:8})}}))},65140:(t,e,n)=>{"use strict";var r=n(32022),i=n(59913),o=n(12115),a=n(68096),u=n(27765),s=n(22775),c=n(3193),d=n(38986),l=n(39837),f=n(75982),p=n(9375),h=n(91173),y=n(38108),m=n(75783),v=n(25466),g=n(92775).f,_=n(43087).f,b=n(13750),S=n(42893),w=n(27747),C=n(78045),E=u.PROPER,I=u.CONFIGURABLE,P=C.get,A=C.set,O="ArrayBuffer",T="DataView",x="prototype",R="Wrong index",k=r[O],M=k,N=M&&M[x],D=r[T],L=D&&D[x],z=Object.prototype,j=r.Array,U=r.RangeError,F=i(b),q=i([].reverse),B=y.pack,G=y.unpack,V=function(t){return[255&t]},Y=function(t){return[255&t,t>>8&255]},H=function(t){return[255&t,t>>8&255,t>>16&255,t>>24&255]},W=function(t){return t[3]<<24|t[2]<<16|t[1]<<8|t[0]},K=function(t){return B(t,23,4)},Z=function(t){return B(t,52,8)},$=function(t,e){_(t[x],e,{get:function(){return P(this)[e]}})},J=function(t,e,n,r){var i=h(n),o=P(t);if(i+e>o.byteLength)throw U(R);var a=P(o.buffer).bytes,u=i+o.byteOffset,s=S(a,u,u+e);return r?s:q(s)},Q=function(t,e,n,r,i,o){var a=h(n),u=P(t);if(a+e>u.byteLength)throw U(R);for(var s=P(u.buffer).bytes,c=a+u.byteOffset,d=r(+i),l=0;lnt;)(tt=et[nt++])in M||s(M,tt,k[tt]);N.constructor=M}v&&m(L)!==z&&v(L,z);var rt=new D(new M(2)),it=i(L.setInt8);rt.setInt8(0,2147483648),rt.setInt8(1,2147483649),!rt.getInt8(0)&&rt.getInt8(1)||c(L,{setInt8:function(t,e){it(this,t,e<<24>>24)},setUint8:function(t,e){it(this,t,e<<24>>24)}},{unsafe:!0})}else N=(M=function(t){l(this,N);var e=h(t);A(this,{bytes:F(j(e),0),byteLength:e}),o||(this.byteLength=e)})[x],L=(D=function(t,e,n){l(this,L),l(t,N);var r=P(t).byteLength,i=f(e);if(i<0||i>r)throw U("Wrong offset");if(i+(n=void 0===n?r-i:p(n))>r)throw U("Wrong length");A(this,{buffer:t,byteLength:n,byteOffset:i}),o||(this.buffer=t,this.byteLength=n,this.byteOffset=i)})[x],o&&($(M,"byteLength"),$(D,"buffer"),$(D,"byteLength"),$(D,"byteOffset")),c(L,{getInt8:function(t){return J(this,1,t)[0]<<24>>24},getUint8:function(t){return J(this,1,t)[0]},getInt16:function(t){var e=J(this,2,t,arguments.length>1?arguments[1]:void 0);return(e[1]<<8|e[0])<<16>>16},getUint16:function(t){var e=J(this,2,t,arguments.length>1?arguments[1]:void 0);return e[1]<<8|e[0]},getInt32:function(t){return W(J(this,4,t,arguments.length>1?arguments[1]:void 0))},getUint32:function(t){return W(J(this,4,t,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(t){return G(J(this,4,t,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(t){return G(J(this,8,t,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(t,e){Q(this,1,t,V,e)},setUint8:function(t,e){Q(this,1,t,V,e)},setInt16:function(t,e){Q(this,2,t,Y,e,arguments.length>2?arguments[2]:void 0)},setUint16:function(t,e){Q(this,2,t,Y,e,arguments.length>2?arguments[2]:void 0)},setInt32:function(t,e){Q(this,4,t,H,e,arguments.length>2?arguments[2]:void 0)},setUint32:function(t,e){Q(this,4,t,H,e,arguments.length>2?arguments[2]:void 0)},setFloat32:function(t,e){Q(this,4,t,K,e,arguments.length>2?arguments[2]:void 0)},setFloat64:function(t,e){Q(this,8,t,Z,e,arguments.length>2?arguments[2]:void 0)}});w(M,O),w(D,T),t.exports={ArrayBuffer:M,DataView:D}},13750:(t,e,n)=>{"use strict";var r=n(47137),i=n(86593),o=n(84117);t.exports=function(t){for(var e=r(this),n=o(e),a=arguments.length,u=i(a>1?arguments[1]:void 0,n),s=a>2?arguments[2]:void 0,c=void 0===s?n:i(s,n);c>u;)e[u++]=t;return e}},33609:(t,e,n)=>{"use strict";var r=n(55883).forEach,i=n(94694)("forEach");t.exports=i?[].forEach:function(t){return r(this,t,arguments.length>1?arguments[1]:void 0)}},65375:(t,e,n)=>{"use strict";var r=n(80391),i=n(49425),o=n(47137),a=n(7701),u=n(92882),s=n(78449),c=n(84117),d=n(19402),l=n(32057),f=n(6897),p=Array;t.exports=function(t){var e=o(t),n=s(this),h=arguments.length,y=h>1?arguments[1]:void 0,m=void 0!==y;m&&(y=r(y,h>2?arguments[2]:void 0));var v,g,_,b,S,w,C=f(e),E=0;if(!C||this===p&&u(C))for(v=c(e),g=n?new this(v):p(v);v>E;E++)w=m?y(e[E],E):e[E],d(g,E,w);else for(S=(b=l(e,C)).next,g=n?new this:[];!(_=i(S,b)).done;E++)w=m?a(b,y,[_.value,E],!0):_.value,d(g,E,w);return g.length=E,g}},78035:(t,e,n)=>{var r=n(58326),i=n(86593),o=n(84117),a=function(t){return function(e,n,a){var u,s=r(e),c=o(s),d=i(a,c);if(t&&n!=n){for(;c>d;)if((u=s[d++])!=u)return!0}else for(;c>d;d++)if((t||d in s)&&s[d]===n)return t||d||0;return!t&&-1}};t.exports={includes:a(!0),indexOf:a(!1)}},55883:(t,e,n)=>{var r=n(80391),i=n(59913),o=n(94032),a=n(47137),u=n(84117),s=n(74842),c=i([].push),d=function(t){var e=1==t,n=2==t,i=3==t,d=4==t,l=6==t,f=7==t,p=5==t||l;return function(h,y,m,v){for(var g,_,b=a(h),S=o(b),w=r(y,m),C=u(S),E=0,I=v||s,P=e?I(h,C):n||f?I(h,0):void 0;C>E;E++)if((p||E in S)&&(_=w(g=S[E],E,b),t))if(e)P[E]=_;else if(_)switch(t){case 3:return!0;case 5:return g;case 6:return E;case 2:c(P,g)}else switch(t){case 4:return!1;case 7:c(P,g)}return l?-1:i||d?d:P}};t.exports={forEach:d(0),map:d(1),filter:d(2),some:d(3),every:d(4),find:d(5),findIndex:d(6),filterReject:d(7)}},44687:(t,e,n)=>{"use strict";var r=n(10584),i=n(58326),o=n(75982),a=n(84117),u=n(94694),s=Math.min,c=[].lastIndexOf,d=!!c&&1/[1].lastIndexOf(1,-0)<0,l=u("lastIndexOf"),f=d||!l;t.exports=f?function(t){if(d)return r(c,this,arguments)||0;var e=i(this),n=a(e),u=n-1;for(arguments.length>1&&(u=s(u,o(arguments[1]))),u<0&&(u=n+u);u>=0;u--)if(u in e&&e[u]===t)return u||0;return-1}:c},41665:(t,e,n)=>{var r=n(38986),i=n(30191),o=n(80714),a=i("species");t.exports=function(t){return o>=51||!r((function(){var e=[];return(e.constructor={})[a]=function(){return{foo:1}},1!==e[t](Boolean).foo}))}},94694:(t,e,n)=>{"use strict";var r=n(38986);t.exports=function(t,e){var n=[][t];return!!n&&r((function(){n.call(null,e||function(){return 1},1)}))}},17761:(t,e,n)=>{"use strict";var r=n(12115),i=n(65351),o=TypeError,a=Object.getOwnPropertyDescriptor,u=r&&!function(){if(void 0!==this)return!0;try{Object.defineProperty([],"length",{writable:!1}).length=1}catch(t){return t instanceof TypeError}}();t.exports=u?function(t,e){if(i(t)&&!a(t,"length").writable)throw o("Cannot set read only .length");return t.length=e}:function(t,e){return t.length=e}},42893:(t,e,n)=>{var r=n(86593),i=n(84117),o=n(19402),a=Array,u=Math.max;t.exports=function(t,e,n){for(var s=i(t),c=r(e,s),d=r(void 0===n?s:n,s),l=a(u(d-c,0)),f=0;c{var r=n(59913);t.exports=r([].slice)},71929:(t,e,n)=>{var r=n(42893),i=Math.floor,o=function(t,e){var n=t.length,s=i(n/2);return n<8?a(t,e):u(t,o(r(t,0,s),e),o(r(t,s),e),e)},a=function(t,e){for(var n,r,i=t.length,o=1;o0;)t[r]=t[--r];r!==o++&&(t[r]=n)}return t},u=function(t,e,n,r){for(var i=e.length,o=n.length,a=0,u=0;a{var r=n(65351),i=n(78449),o=n(51355),a=n(30191)("species"),u=Array;t.exports=function(t){var e;return r(t)&&(e=t.constructor,(i(e)&&(e===u||r(e.prototype))||o(e)&&null===(e=e[a]))&&(e=void 0)),void 0===e?u:e}},74842:(t,e,n)=>{var r=n(78502);t.exports=function(t,e){return new(r(t))(0===e?0:e)}},7701:(t,e,n)=>{var r=n(52546),i=n(94681);t.exports=function(t,e,n,o){try{return o?e(r(n)[0],n[1]):e(n)}catch(e){i(t,"throw",e)}}},41269:(t,e,n)=>{var r=n(30191)("iterator"),i=!1;try{var o=0,a={next:function(){return{done:!!o++}},return:function(){i=!0}};a[r]=function(){return this},Array.from(a,(function(){throw 2}))}catch(t){}t.exports=function(t,e){if(!e&&!i)return!1;var n=!1;try{var o={};o[r]=function(){return{next:function(){return{done:n=!0}}}},t(o)}catch(t){}return n}},39523:(t,e,n)=>{var r=n(59913),i=r({}.toString),o=r("".slice);t.exports=function(t){return o(i(t),8,-1)}},82814:(t,e,n)=>{var r=n(77568),i=n(34028),o=n(39523),a=n(30191)("toStringTag"),u=Object,s="Arguments"==o(function(){return arguments}());t.exports=r?o:function(t){var e,n,r;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(n=function(t,e){try{return t[e]}catch(t){}}(e=u(t),a))?n:s?o(e):"Object"==(r=o(e))&&i(e.callee)?"Arguments":r}},61961:(t,e,n)=>{"use strict";var r=n(43087).f,i=n(13250),o=n(3193),a=n(80391),u=n(39837),s=n(87126),c=n(38640),d=n(53338),l=n(80251),f=n(42343),p=n(12115),h=n(67023).fastKey,y=n(78045),m=y.set,v=y.getterFor;t.exports={getConstructor:function(t,e,n,d){var l=t((function(t,r){u(t,f),m(t,{type:e,index:i(null),first:void 0,last:void 0,size:0}),p||(t.size=0),s(r)||c(r,t[d],{that:t,AS_ENTRIES:n})})),f=l.prototype,y=v(e),g=function(t,e,n){var r,i,o=y(t),a=_(t,e);return a?a.value=n:(o.last=a={index:i=h(e,!0),key:e,value:n,previous:r=o.last,next:void 0,removed:!1},o.first||(o.first=a),r&&(r.next=a),p?o.size++:t.size++,"F"!==i&&(o.index[i]=a)),t},_=function(t,e){var n,r=y(t),i=h(e);if("F"!==i)return r.index[i];for(n=r.first;n;n=n.next)if(n.key==e)return n};return o(f,{clear:function(){for(var t=y(this),e=t.index,n=t.first;n;)n.removed=!0,n.previous&&(n.previous=n.previous.next=void 0),delete e[n.index],n=n.next;t.first=t.last=void 0,p?t.size=0:this.size=0},delete:function(t){var e=this,n=y(e),r=_(e,t);if(r){var i=r.next,o=r.previous;delete n.index[r.index],r.removed=!0,o&&(o.next=i),i&&(i.previous=o),n.first==r&&(n.first=i),n.last==r&&(n.last=o),p?n.size--:e.size--}return!!r},forEach:function(t){for(var e,n=y(this),r=a(t,arguments.length>1?arguments[1]:void 0);e=e?e.next:n.first;)for(r(e.value,e.key,this);e&&e.removed;)e=e.previous},has:function(t){return!!_(this,t)}}),o(f,n?{get:function(t){var e=_(this,t);return e&&e.value},set:function(t,e){return g(this,0===t?0:t,e)}}:{add:function(t){return g(this,t=0===t?0:t,t)}}),p&&r(f,"size",{get:function(){return y(this).size}}),l},setStrong:function(t,e,n){var r=e+" Iterator",i=v(e),o=v(r);d(t,e,(function(t,e){m(this,{type:r,target:t,state:i(t),kind:e,last:void 0})}),(function(){for(var t=o(this),e=t.kind,n=t.last;n&&n.removed;)n=n.previous;return t.target&&(t.last=n=n?n.next:t.state.first)?l("keys"==e?n.key:"values"==e?n.value:[n.key,n.value],!1):(t.target=void 0,l(void 0,!0))}),n?"entries":"values",!n,!0),f(e)}}},31858:(t,e,n)=>{"use strict";var r=n(59913),i=n(3193),o=n(67023).getWeakData,a=n(39837),u=n(52546),s=n(87126),c=n(51355),d=n(38640),l=n(55883),f=n(98511),p=n(78045),h=p.set,y=p.getterFor,m=l.find,v=l.findIndex,g=r([].splice),_=0,b=function(t){return t.frozen||(t.frozen=new S)},S=function(){this.entries=[]},w=function(t,e){return m(t.entries,(function(t){return t[0]===e}))};S.prototype={get:function(t){var e=w(this,t);if(e)return e[1]},has:function(t){return!!w(this,t)},set:function(t,e){var n=w(this,t);n?n[1]=e:this.entries.push([t,e])},delete:function(t){var e=v(this.entries,(function(e){return e[0]===t}));return~e&&g(this.entries,e,1),!!~e}},t.exports={getConstructor:function(t,e,n,r){var l=t((function(t,i){a(t,p),h(t,{type:e,id:_++,frozen:void 0}),s(i)||d(i,t[r],{that:t,AS_ENTRIES:n})})),p=l.prototype,m=y(e),v=function(t,e,n){var r=m(t),i=o(u(e),!0);return!0===i?b(r).set(e,n):i[r.id]=n,t};return i(p,{delete:function(t){var e=m(this);if(!c(t))return!1;var n=o(t);return!0===n?b(e).delete(t):n&&f(n,e.id)&&delete n[e.id]},has:function(t){var e=m(this);if(!c(t))return!1;var n=o(t);return!0===n?b(e).has(t):n&&f(n,e.id)}}),i(p,n?{get:function(t){var e=m(this);if(c(t)){var n=o(t);return!0===n?b(e).get(t):n?n[e.id]:void 0}},set:function(t,e){return v(this,t,e)}}:{add:function(t){return v(this,t,!0)}}),l}}},69866:(t,e,n)=>{"use strict";var r=n(54635),i=n(32022),o=n(59913),a=n(77987),u=n(43068),s=n(67023),c=n(38640),d=n(39837),l=n(34028),f=n(87126),p=n(51355),h=n(38986),y=n(41269),m=n(27747),v=n(99618);t.exports=function(t,e,n){var g=-1!==t.indexOf("Map"),_=-1!==t.indexOf("Weak"),b=g?"set":"add",S=i[t],w=S&&S.prototype,C=S,E={},I=function(t){var e=o(w[t]);u(w,t,"add"==t?function(t){return e(this,0===t?0:t),this}:"delete"==t?function(t){return!(_&&!p(t))&&e(this,0===t?0:t)}:"get"==t?function(t){return _&&!p(t)?void 0:e(this,0===t?0:t)}:"has"==t?function(t){return!(_&&!p(t))&&e(this,0===t?0:t)}:function(t,n){return e(this,0===t?0:t,n),this})};if(a(t,!l(S)||!(_||w.forEach&&!h((function(){(new S).entries().next()})))))C=n.getConstructor(e,t,g,b),s.enable();else if(a(t,!0)){var P=new C,A=P[b](_?{}:-0,1)!=P,O=h((function(){P.has(1)})),T=y((function(t){new S(t)})),x=!_&&h((function(){for(var t=new S,e=5;e--;)t[b](e,e);return!t.has(-0)}));T||((C=e((function(t,e){d(t,w);var n=v(new S,t,C);return f(e)||c(e,n[b],{that:n,AS_ENTRIES:g}),n}))).prototype=w,w.constructor=C),(O||x)&&(I("delete"),I("has"),g&&I("get")),(x||A)&&I(b),_&&w.clear&&delete w.clear}return E[t]=C,r({global:!0,constructor:!0,forced:C!=S},E),m(C,t),_||n.setStrong(C,t,g),C}},74953:(t,e,n)=>{var r=n(98511),i=n(91537),o=n(66213),a=n(43087);t.exports=function(t,e,n){for(var u=i(e),s=a.f,c=o.f,d=0;d{var r=n(30191)("match");t.exports=function(t){var e=/./;try{"/./"[t](e)}catch(n){try{return e[r]=!1,"/./"[t](e)}catch(t){}}return!1}},88538:(t,e,n)=>{var r=n(38986);t.exports=!r((function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype}))},89444:(t,e,n)=>{var r=n(59913),i=n(31591),o=n(74170),a=/"/g,u=r("".replace);t.exports=function(t,e,n,r){var s=o(i(t)),c="<"+e;return""!==n&&(c+=" "+n+'="'+u(o(r),a,""")+'"'),c+">"+s+""}},80251:t=>{t.exports=function(t,e){return{value:t,done:e}}},22775:(t,e,n)=>{var r=n(12115),i=n(43087),o=n(71111);t.exports=r?function(t,e,n){return i.f(t,e,o(1,n))}:function(t,e,n){return t[e]=n,t}},71111:t=>{t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},19402:(t,e,n)=>{"use strict";var r=n(79127),i=n(43087),o=n(71111);t.exports=function(t,e,n){var a=r(e);a in t?i.f(t,a,o(0,n)):t[a]=n}},68959:(t,e,n)=>{"use strict";var r=n(52546),i=n(93126),o=TypeError;t.exports=function(t){if(r(this),"string"===t||"default"===t)t="string";else if("number"!==t)throw o("Incorrect hint");return i(this,t)}},43068:(t,e,n)=>{var r=n(34028),i=n(43087),o=n(43608),a=n(97210);t.exports=function(t,e,n,u){u||(u={});var s=u.enumerable,c=void 0!==u.name?u.name:e;if(r(n)&&o(n,c,u),u.global)s?t[e]=n:a(e,n);else{try{u.unsafe?t[e]&&(s=!0):delete t[e]}catch(t){}s?t[e]=n:i.f(t,e,{value:n,enumerable:!1,configurable:!u.nonConfigurable,writable:!u.nonWritable})}return t}},3193:(t,e,n)=>{var r=n(43068);t.exports=function(t,e,n){for(var i in e)r(t,i,e[i],n);return t}},97210:(t,e,n)=>{var r=n(32022),i=Object.defineProperty;t.exports=function(t,e){try{i(r,t,{value:e,configurable:!0,writable:!0})}catch(n){r[t]=e}return e}},39850:(t,e,n)=>{"use strict";var r=n(84160),i=TypeError;t.exports=function(t,e){if(!delete t[e])throw i("Cannot delete property "+r(e)+" of "+r(t))}},12115:(t,e,n)=>{var r=n(38986);t.exports=!r((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]}))},30805:t=>{var e="object"==typeof document&&document.all,n=void 0===e&&void 0!==e;t.exports={all:e,IS_HTMLDDA:n}},82985:(t,e,n)=>{var r=n(32022),i=n(51355),o=r.document,a=i(o)&&i(o.createElement);t.exports=function(t){return a?o.createElement(t):{}}},81912:t=>{var e=TypeError;t.exports=function(t){if(t>9007199254740991)throw e("Maximum allowed index exceeded");return t}},66910:t=>{t.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}},73391:(t,e,n)=>{var r=n(82985)("span").classList,i=r&&r.constructor&&r.constructor.prototype;t.exports=i===Object.prototype?void 0:i},93454:(t,e,n)=>{var r=n(30727).match(/firefox\/(\d+)/i);t.exports=!!r&&+r[1]},85048:(t,e,n)=>{var r=n(5835),i=n(79456);t.exports=!r&&!i&&"object"==typeof window&&"object"==typeof document},5835:t=>{t.exports="object"==typeof Deno&&Deno&&"object"==typeof Deno.version},88633:(t,e,n)=>{var r=n(30727);t.exports=/MSIE|Trident/.test(r)},88525:(t,e,n)=>{var r=n(30727),i=n(32022);t.exports=/ipad|iphone|ipod/i.test(r)&&void 0!==i.Pebble},649:(t,e,n)=>{var r=n(30727);t.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(r)},79456:(t,e,n)=>{var r=n(39523),i=n(32022);t.exports="process"==r(i.process)},52054:(t,e,n)=>{var r=n(30727);t.exports=/web0s(?!.*chrome)/i.test(r)},30727:(t,e,n)=>{var r=n(83155);t.exports=r("navigator","userAgent")||""},80714:(t,e,n)=>{var r,i,o=n(32022),a=n(30727),u=o.process,s=o.Deno,c=u&&u.versions||s&&s.version,d=c&&c.v8;d&&(i=(r=d.split("."))[0]>0&&r[0]<4?1:+(r[0]+r[1])),!i&&a&&(!(r=a.match(/Edge\/(\d+)/))||r[1]>=74)&&(r=a.match(/Chrome\/(\d+)/))&&(i=+r[1]),t.exports=i},10720:(t,e,n)=>{var r=n(30727).match(/AppleWebKit\/(\d+)\./);t.exports=!!r&&+r[1]},26100:t=>{t.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},54635:(t,e,n)=>{var r=n(32022),i=n(66213).f,o=n(22775),a=n(43068),u=n(97210),s=n(74953),c=n(77987);t.exports=function(t,e){var n,d,l,f,p,h=t.target,y=t.global,m=t.stat;if(n=y?r:m?r[h]||u(h,{}):(r[h]||{}).prototype)for(d in e){if(f=e[d],l=t.dontCallGetSet?(p=i(n,d))&&p.value:n[d],!c(y?d:h+(m?".":"#")+d,t.forced)&&void 0!==l){if(typeof f==typeof l)continue;s(f,l)}(t.sham||l&&l.sham)&&o(f,"sham",!0),a(n,d,f,t)}}},38986:t=>{t.exports=function(t){try{return!!t()}catch(t){return!0}}},26210:(t,e,n)=>{"use strict";n(49636);var r=n(59913),i=n(43068),o=n(83046),a=n(38986),u=n(30191),s=n(22775),c=u("species"),d=RegExp.prototype;t.exports=function(t,e,n,l){var f=u(t),p=!a((function(){var e={};return e[f]=function(){return 7},7!=""[t](e)})),h=p&&!a((function(){var e=!1,n=/a/;return"split"===t&&((n={}).constructor={},n.constructor[c]=function(){return n},n.flags="",n[f]=/./[f]),n.exec=function(){return e=!0,null},n[f](""),!e}));if(!p||!h||n){var y=r(/./[f]),m=e(f,""[t],(function(t,e,n,i,a){var u=r(t),s=e.exec;return s===o||s===d.exec?p&&!a?{done:!0,value:y(e,n,i)}:{done:!0,value:u(n,e,i)}:{done:!1}}));i(String.prototype,t,m[0]),i(d,f,m[1])}l&&s(d[f],"sham",!0)}},47484:(t,e,n)=>{"use strict";var r=n(65351),i=n(84117),o=n(81912),a=n(80391),u=function(t,e,n,s,c,d,l,f){for(var p,h,y=c,m=0,v=!!l&&a(l,f);m0&&r(p)?(h=i(p),y=u(t,e,p,h,y,d-1)-1):(o(y+1),t[y]=p),y++),m++;return y};t.exports=u},6769:(t,e,n)=>{var r=n(38986);t.exports=!r((function(){return Object.isExtensible(Object.preventExtensions({}))}))},10584:(t,e,n)=>{var r=n(74959),i=Function.prototype,o=i.apply,a=i.call;t.exports="object"==typeof Reflect&&Reflect.apply||(r?a.bind(o):function(){return a.apply(o,arguments)})},80391:(t,e,n)=>{var r=n(59913),i=n(86173),o=n(74959),a=r(r.bind);t.exports=function(t,e){return i(t),void 0===e?t:o?a(t,e):function(){return t.apply(e,arguments)}}},74959:(t,e,n)=>{var r=n(38986);t.exports=!r((function(){var t=function(){}.bind();return"function"!=typeof t||t.hasOwnProperty("prototype")}))},49425:(t,e,n)=>{var r=n(74959),i=Function.prototype.call;t.exports=r?i.bind(i):function(){return i.apply(i,arguments)}},27765:(t,e,n)=>{var r=n(12115),i=n(98511),o=Function.prototype,a=r&&Object.getOwnPropertyDescriptor,u=i(o,"name"),s=u&&"something"===function(){}.name,c=u&&(!r||r&&a(o,"name").configurable);t.exports={EXISTS:u,PROPER:s,CONFIGURABLE:c}},59913:(t,e,n)=>{var r=n(74959),i=Function.prototype,o=i.bind,a=i.call,u=r&&o.bind(a,a);t.exports=r?function(t){return t&&u(t)}:function(t){return t&&function(){return a.apply(t,arguments)}}},83155:(t,e,n)=>{var r=n(32022),i=n(34028);t.exports=function(t,e){return arguments.length<2?(n=r[t],i(n)?n:void 0):r[t]&&r[t][e];var n}},6897:(t,e,n)=>{var r=n(82814),i=n(34040),o=n(87126),a=n(13766),u=n(30191)("iterator");t.exports=function(t){if(!o(t))return i(t,u)||i(t,"@@iterator")||a[r(t)]}},32057:(t,e,n)=>{var r=n(49425),i=n(86173),o=n(52546),a=n(84160),u=n(6897),s=TypeError;t.exports=function(t,e){var n=arguments.length<2?u(t):e;if(i(n))return o(r(n,t));throw s(a(t)+" is not iterable")}},34040:(t,e,n)=>{var r=n(86173),i=n(87126);t.exports=function(t,e){var n=t[e];return i(n)?void 0:r(n)}},82319:(t,e,n)=>{var r=n(59913),i=n(47137),o=Math.floor,a=r("".charAt),u=r("".replace),s=r("".slice),c=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,d=/\$([$&'`]|\d{1,2})/g;t.exports=function(t,e,n,r,l,f){var p=n+t.length,h=r.length,y=d;return void 0!==l&&(l=i(l),y=c),u(f,y,(function(i,u){var c;switch(a(u,0)){case"$":return"$";case"&":return t;case"`":return s(e,0,n);case"'":return s(e,p);case"<":c=l[s(u,1,-1)];break;default:var d=+u;if(0===d)return i;if(d>h){var f=o(d/10);return 0===f?i:f<=h?void 0===r[f-1]?a(u,1):r[f-1]+a(u,1):i}c=r[d-1]}return void 0===c?"":c}))}},32022:(t,e,n)=>{var r=function(t){return t&&t.Math==Math&&t};t.exports=r("object"==typeof globalThis&&globalThis)||r("object"==typeof window&&window)||r("object"==typeof self&&self)||r("object"==typeof n.g&&n.g)||function(){return this}()||Function("return this")()},98511:(t,e,n)=>{var r=n(59913),i=n(47137),o=r({}.hasOwnProperty);t.exports=Object.hasOwn||function(t,e){return o(i(t),e)}},17307:t=>{t.exports={}},39361:(t,e,n)=>{var r=n(32022);t.exports=function(t,e){var n=r.console;n&&n.error&&(1==arguments.length?n.error(t):n.error(t,e))}},86419:(t,e,n)=>{var r=n(83155);t.exports=r("document","documentElement")},2159:(t,e,n)=>{var r=n(12115),i=n(38986),o=n(82985);t.exports=!r&&!i((function(){return 7!=Object.defineProperty(o("div"),"a",{get:function(){return 7}}).a}))},38108:t=>{var e=Array,n=Math.abs,r=Math.pow,i=Math.floor,o=Math.log,a=Math.LN2;t.exports={pack:function(t,u,s){var c,d,l,f=e(s),p=8*s-u-1,h=(1<>1,m=23===u?r(2,-24)-r(2,-77):0,v=t<0||0===t&&1/t<0?1:0,g=0;for((t=n(t))!=t||t===1/0?(d=t!=t?1:0,c=h):(c=i(o(t)/a),t*(l=r(2,-c))<1&&(c--,l*=2),(t+=c+y>=1?m/l:m*r(2,1-y))*l>=2&&(c++,l/=2),c+y>=h?(d=0,c=h):c+y>=1?(d=(t*l-1)*r(2,u),c+=y):(d=t*r(2,y-1)*r(2,u),c=0));u>=8;)f[g++]=255&d,d/=256,u-=8;for(c=c<0;)f[g++]=255&c,c/=256,p-=8;return f[--g]|=128*v,f},unpack:function(t,e){var n,i=t.length,o=8*i-e-1,a=(1<>1,s=o-7,c=i-1,d=t[c--],l=127&d;for(d>>=7;s>0;)l=256*l+t[c--],s-=8;for(n=l&(1<<-s)-1,l>>=-s,s+=e;s>0;)n=256*n+t[c--],s-=8;if(0===l)l=1-u;else{if(l===a)return n?NaN:d?-1/0:1/0;n+=r(2,e),l-=u}return(d?-1:1)*n*r(2,l-e)}}},94032:(t,e,n)=>{var r=n(59913),i=n(38986),o=n(39523),a=Object,u=r("".split);t.exports=i((function(){return!a("z").propertyIsEnumerable(0)}))?function(t){return"String"==o(t)?u(t,""):a(t)}:a},99618:(t,e,n)=>{var r=n(34028),i=n(51355),o=n(25466);t.exports=function(t,e,n){var a,u;return o&&r(a=e.constructor)&&a!==n&&i(u=a.prototype)&&u!==n.prototype&&o(t,u),t}},46169:(t,e,n)=>{var r=n(59913),i=n(34028),o=n(43349),a=r(Function.toString);i(o.inspectSource)||(o.inspectSource=function(t){return a(t)}),t.exports=o.inspectSource},67023:(t,e,n)=>{var r=n(54635),i=n(59913),o=n(17307),a=n(51355),u=n(98511),s=n(43087).f,c=n(92775),d=n(12098),l=n(62713),f=n(60232),p=n(6769),h=!1,y=f("meta"),m=0,v=function(t){s(t,y,{value:{objectID:"O"+m++,weakData:{}}})},g=t.exports={enable:function(){g.enable=function(){},h=!0;var t=c.f,e=i([].splice),n={};n[y]=1,t(n).length&&(c.f=function(n){for(var r=t(n),i=0,o=r.length;i{var r,i,o,a=n(74112),u=n(32022),s=n(59913),c=n(51355),d=n(22775),l=n(98511),f=n(43349),p=n(57186),h=n(17307),y="Object already initialized",m=u.TypeError,v=u.WeakMap;if(a||f.state){var g=f.state||(f.state=new v),_=s(g.get),b=s(g.has),S=s(g.set);r=function(t,e){if(b(g,t))throw m(y);return e.facade=t,S(g,t,e),e},i=function(t){return _(g,t)||{}},o=function(t){return b(g,t)}}else{var w=p("state");h[w]=!0,r=function(t,e){if(l(t,w))throw m(y);return e.facade=t,d(t,w,e),e},i=function(t){return l(t,w)?t[w]:{}},o=function(t){return l(t,w)}}t.exports={set:r,get:i,has:o,enforce:function(t){return o(t)?i(t):r(t,{})},getterFor:function(t){return function(e){var n;if(!c(e)||(n=i(e)).type!==t)throw m("Incompatible receiver, "+t+" required");return n}}}},92882:(t,e,n)=>{var r=n(30191),i=n(13766),o=r("iterator"),a=Array.prototype;t.exports=function(t){return void 0!==t&&(i.Array===t||a[o]===t)}},65351:(t,e,n)=>{var r=n(39523);t.exports=Array.isArray||function(t){return"Array"==r(t)}},34028:(t,e,n)=>{var r=n(30805),i=r.all;t.exports=r.IS_HTMLDDA?function(t){return"function"==typeof t||t===i}:function(t){return"function"==typeof t}},78449:(t,e,n)=>{var r=n(59913),i=n(38986),o=n(34028),a=n(82814),u=n(83155),s=n(46169),c=function(){},d=[],l=u("Reflect","construct"),f=/^\s*(?:class|function)\b/,p=r(f.exec),h=!f.exec(c),y=function(t){if(!o(t))return!1;try{return l(c,d,t),!0}catch(t){return!1}},m=function(t){if(!o(t))return!1;switch(a(t)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return h||!!p(f,s(t))}catch(t){return!0}};m.sham=!0,t.exports=!l||i((function(){var t;return y(y.call)||!y(Object)||!y((function(){t=!0}))||t}))?m:y},77987:(t,e,n)=>{var r=n(38986),i=n(34028),o=/#|\.prototype\./,a=function(t,e){var n=s[u(t)];return n==d||n!=c&&(i(e)?r(e):!!e)},u=a.normalize=function(t){return String(t).replace(o,".").toLowerCase()},s=a.data={},c=a.NATIVE="N",d=a.POLYFILL="P";t.exports=a},87126:t=>{t.exports=function(t){return null==t}},51355:(t,e,n)=>{var r=n(34028),i=n(30805),o=i.all;t.exports=i.IS_HTMLDDA?function(t){return"object"==typeof t?null!==t:r(t)||t===o}:function(t){return"object"==typeof t?null!==t:r(t)}},68546:t=>{t.exports=!1},91035:(t,e,n)=>{var r=n(51355),i=n(39523),o=n(30191)("match");t.exports=function(t){var e;return r(t)&&(void 0!==(e=t[o])?!!e:"RegExp"==i(t))}},24505:(t,e,n)=>{var r=n(83155),i=n(34028),o=n(27357),a=n(78590),u=Object;t.exports=a?function(t){return"symbol"==typeof t}:function(t){var e=r("Symbol");return i(e)&&o(e.prototype,u(t))}},38640:(t,e,n)=>{var r=n(80391),i=n(49425),o=n(52546),a=n(84160),u=n(92882),s=n(84117),c=n(27357),d=n(32057),l=n(6897),f=n(94681),p=TypeError,h=function(t,e){this.stopped=t,this.result=e},y=h.prototype;t.exports=function(t,e,n){var m,v,g,_,b,S,w,C=n&&n.that,E=!(!n||!n.AS_ENTRIES),I=!(!n||!n.IS_RECORD),P=!(!n||!n.IS_ITERATOR),A=!(!n||!n.INTERRUPTED),O=r(e,C),T=function(t){return m&&f(m,"normal",t),new h(!0,t)},x=function(t){return E?(o(t),A?O(t[0],t[1],T):O(t[0],t[1])):A?O(t,T):O(t)};if(I)m=t.iterator;else if(P)m=t;else{if(!(v=l(t)))throw p(a(t)+" is not iterable");if(u(v)){for(g=0,_=s(t);_>g;g++)if((b=x(t[g]))&&c(y,b))return b;return new h(!1)}m=d(t,v)}for(S=I?t.next:m.next;!(w=i(S,m)).done;){try{b=x(w.value)}catch(t){f(m,"throw",t)}if("object"==typeof b&&b&&c(y,b))return b}return new h(!1)}},94681:(t,e,n)=>{var r=n(49425),i=n(52546),o=n(34040);t.exports=function(t,e,n){var a,u;i(t);try{if(!(a=o(t,"return"))){if("throw"===e)throw n;return n}a=r(a,t)}catch(t){u=!0,a=t}if("throw"===e)throw n;if(u)throw a;return i(a),n}},92480:(t,e,n)=>{"use strict";var r=n(10798).IteratorPrototype,i=n(13250),o=n(71111),a=n(27747),u=n(13766),s=function(){return this};t.exports=function(t,e,n,c){var d=e+" Iterator";return t.prototype=i(r,{next:o(+!c,n)}),a(t,d,!1,!0),u[d]=s,t}},53338:(t,e,n)=>{"use strict";var r=n(54635),i=n(49425),o=n(68546),a=n(27765),u=n(34028),s=n(92480),c=n(75783),d=n(25466),l=n(27747),f=n(22775),p=n(43068),h=n(30191),y=n(13766),m=n(10798),v=a.PROPER,g=a.CONFIGURABLE,_=m.IteratorPrototype,b=m.BUGGY_SAFARI_ITERATORS,S=h("iterator"),w="keys",C="values",E="entries",I=function(){return this};t.exports=function(t,e,n,a,h,m,P){s(n,e,a);var A,O,T,x=function(t){if(t===h&&D)return D;if(!b&&t in M)return M[t];switch(t){case w:case C:case E:return function(){return new n(this,t)}}return function(){return new n(this)}},R=e+" Iterator",k=!1,M=t.prototype,N=M[S]||M["@@iterator"]||h&&M[h],D=!b&&N||x(h),L="Array"==e&&M.entries||N;if(L&&(A=c(L.call(new t)))!==Object.prototype&&A.next&&(o||c(A)===_||(d?d(A,_):u(A[S])||p(A,S,I)),l(A,R,!0,!0),o&&(y[R]=I)),v&&h==C&&N&&N.name!==C&&(!o&&g?f(M,"name",C):(k=!0,D=function(){return i(N,this)})),h)if(O={values:x(C),keys:m?D:x(w),entries:x(E)},P)for(T in O)(b||k||!(T in M))&&p(M,T,O[T]);else r({target:e,proto:!0,forced:b||k},O);return o&&!P||M[S]===D||p(M,S,D,{name:h}),y[e]=D,O}},10798:(t,e,n)=>{"use strict";var r,i,o,a=n(38986),u=n(34028),s=n(51355),c=n(13250),d=n(75783),l=n(43068),f=n(30191),p=n(68546),h=f("iterator"),y=!1;[].keys&&("next"in(o=[].keys())?(i=d(d(o)))!==Object.prototype&&(r=i):y=!0),!s(r)||a((function(){var t={};return r[h].call(t)!==t}))?r={}:p&&(r=c(r)),u(r[h])||l(r,h,(function(){return this})),t.exports={IteratorPrototype:r,BUGGY_SAFARI_ITERATORS:y}},13766:t=>{t.exports={}},84117:(t,e,n)=>{var r=n(9375);t.exports=function(t){return r(t.length)}},43608:(t,e,n)=>{var r=n(38986),i=n(34028),o=n(98511),a=n(12115),u=n(27765).CONFIGURABLE,s=n(46169),c=n(78045),d=c.enforce,l=c.get,f=Object.defineProperty,p=a&&!r((function(){return 8!==f((function(){}),"length",{value:8}).length})),h=String(String).split("String"),y=t.exports=function(t,e,n){"Symbol("===String(e).slice(0,7)&&(e="["+String(e).replace(/^Symbol\(([^)]*)\)/,"$1")+"]"),n&&n.getter&&(e="get "+e),n&&n.setter&&(e="set "+e),(!o(t,"name")||u&&t.name!==e)&&(a?f(t,"name",{value:e,configurable:!0}):t.name=e),p&&n&&o(n,"arity")&&t.length!==n.arity&&f(t,"length",{value:n.arity});try{n&&o(n,"constructor")&&n.constructor?a&&f(t,"prototype",{writable:!1}):t.prototype&&(t.prototype=void 0)}catch(t){}var r=d(t);return o(r,"source")||(r.source=h.join("string"==typeof e?e:"")),t};Function.prototype.toString=y((function(){return i(this)&&l(this).source||s(this)}),"toString")},39309:t=>{var e=Math.ceil,n=Math.floor;t.exports=Math.trunc||function(t){var r=+t;return(r>0?n:e)(r)}},76173:(t,e,n)=>{var r,i,o,a,u,s,c,d,l=n(32022),f=n(80391),p=n(66213).f,h=n(16416).set,y=n(649),m=n(88525),v=n(52054),g=n(79456),_=l.MutationObserver||l.WebKitMutationObserver,b=l.document,S=l.process,w=l.Promise,C=p(l,"queueMicrotask"),E=C&&C.value;E||(r=function(){var t,e;for(g&&(t=S.domain)&&t.exit();i;){e=i.fn,i=i.next;try{e()}catch(t){throw i?a():o=void 0,t}}o=void 0,t&&t.enter()},y||g||v||!_||!b?!m&&w&&w.resolve?((c=w.resolve(void 0)).constructor=w,d=f(c.then,c),a=function(){d(r)}):g?a=function(){S.nextTick(r)}:(h=f(h,l),a=function(){h(r)}):(u=!0,s=b.createTextNode(""),new _(r).observe(s,{characterData:!0}),a=function(){s.data=u=!u})),t.exports=E||function(t){var e={fn:t,next:void 0};o&&(o.next=e),i||(i=e,a()),o=e}},67892:(t,e,n)=>{"use strict";var r=n(86173),i=TypeError,o=function(t){var e,n;this.promise=new t((function(t,r){if(void 0!==e||void 0!==n)throw i("Bad Promise constructor");e=t,n=r})),this.resolve=r(e),this.reject=r(n)};t.exports.f=function(t){return new o(t)}},17911:(t,e,n)=>{var r=n(91035),i=TypeError;t.exports=function(t){if(r(t))throw i("The method doesn't accept regular expressions");return t}},57017:(t,e,n)=>{var r=n(32022),i=n(38986),o=n(59913),a=n(74170),u=n(76109).trim,s=n(60812),c=o("".charAt),d=r.parseFloat,l=r.Symbol,f=l&&l.iterator,p=1/d(s+"-0")!=-1/0||f&&!i((function(){d(Object(f))}));t.exports=p?function(t){var e=u(a(t)),n=d(e);return 0===n&&"-"==c(e,0)?-0:n}:d},84475:(t,e,n)=>{var r=n(32022),i=n(38986),o=n(59913),a=n(74170),u=n(76109).trim,s=n(60812),c=r.parseInt,d=r.Symbol,l=d&&d.iterator,f=/^[+-]?0x/i,p=o(f.exec),h=8!==c(s+"08")||22!==c(s+"0x16")||l&&!i((function(){c(Object(l))}));t.exports=h?function(t,e){var n=u(a(t));return c(n,e>>>0||(p(f,n)?16:10))}:c},86851:(t,e,n)=>{"use strict";var r=n(12115),i=n(59913),o=n(49425),a=n(38986),u=n(95932),s=n(31711),c=n(23659),d=n(47137),l=n(94032),f=Object.assign,p=Object.defineProperty,h=i([].concat);t.exports=!f||a((function(){if(r&&1!==f({b:1},f(p({},"a",{enumerable:!0,get:function(){p(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var t={},e={},n=Symbol(),i="abcdefghijklmnopqrst";return t[n]=7,i.split("").forEach((function(t){e[t]=t})),7!=f({},t)[n]||u(f({},e)).join("")!=i}))?function(t,e){for(var n=d(t),i=arguments.length,a=1,f=s.f,p=c.f;i>a;)for(var y,m=l(arguments[a++]),v=f?h(u(m),f(m)):u(m),g=v.length,_=0;g>_;)y=v[_++],r&&!o(p,m,y)||(n[y]=m[y]);return n}:f},13250:(t,e,n)=>{var r,i=n(52546),o=n(13330),a=n(26100),u=n(17307),s=n(86419),c=n(82985),d=n(57186),l="prototype",f="script",p=d("IE_PROTO"),h=function(){},y=function(t){return"<"+f+">"+t+""},m=function(t){t.write(y("")),t.close();var e=t.parentWindow.Object;return t=null,e},v=function(){try{r=new ActiveXObject("htmlfile")}catch(t){}var t,e,n;v="undefined"!=typeof document?document.domain&&r?m(r):(e=c("iframe"),n="java"+f+":",e.style.display="none",s.appendChild(e),e.src=String(n),(t=e.contentWindow.document).open(),t.write(y("document.F=Object")),t.close(),t.F):m(r);for(var i=a.length;i--;)delete v[l][a[i]];return v()};u[p]=!0,t.exports=Object.create||function(t,e){var n;return null!==t?(h[l]=i(t),n=new h,h[l]=null,n[p]=t):n=v(),void 0===e?n:o.f(n,e)}},13330:(t,e,n)=>{var r=n(12115),i=n(71330),o=n(43087),a=n(52546),u=n(58326),s=n(95932);e.f=r&&!i?Object.defineProperties:function(t,e){a(t);for(var n,r=u(e),i=s(e),c=i.length,d=0;c>d;)o.f(t,n=i[d++],r[n]);return t}},43087:(t,e,n)=>{var r=n(12115),i=n(2159),o=n(71330),a=n(52546),u=n(79127),s=TypeError,c=Object.defineProperty,d=Object.getOwnPropertyDescriptor,l="enumerable",f="configurable",p="writable";e.f=r?o?function(t,e,n){if(a(t),e=u(e),a(n),"function"==typeof t&&"prototype"===e&&"value"in n&&p in n&&!n[p]){var r=d(t,e);r&&r[p]&&(t[e]=n.value,n={configurable:f in n?n[f]:r[f],enumerable:l in n?n[l]:r[l],writable:!1})}return c(t,e,n)}:c:function(t,e,n){if(a(t),e=u(e),a(n),i)try{return c(t,e,n)}catch(t){}if("get"in n||"set"in n)throw s("Accessors not supported");return"value"in n&&(t[e]=n.value),t}},66213:(t,e,n)=>{var r=n(12115),i=n(49425),o=n(23659),a=n(71111),u=n(58326),s=n(79127),c=n(98511),d=n(2159),l=Object.getOwnPropertyDescriptor;e.f=r?l:function(t,e){if(t=u(t),e=s(e),d)try{return l(t,e)}catch(t){}if(c(t,e))return a(!i(o.f,t,e),t[e])}},12098:(t,e,n)=>{var r=n(39523),i=n(58326),o=n(92775).f,a=n(42893),u="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];t.exports.f=function(t){return u&&"Window"==r(t)?function(t){try{return o(t)}catch(t){return a(u)}}(t):o(i(t))}},92775:(t,e,n)=>{var r=n(7282),i=n(26100).concat("length","prototype");e.f=Object.getOwnPropertyNames||function(t){return r(t,i)}},31711:(t,e)=>{e.f=Object.getOwnPropertySymbols},75783:(t,e,n)=>{var r=n(98511),i=n(34028),o=n(47137),a=n(57186),u=n(88538),s=a("IE_PROTO"),c=Object,d=c.prototype;t.exports=u?c.getPrototypeOf:function(t){var e=o(t);if(r(e,s))return e[s];var n=e.constructor;return i(n)&&e instanceof n?n.prototype:e instanceof c?d:null}},62713:(t,e,n)=>{var r=n(38986),i=n(51355),o=n(39523),a=n(1743),u=Object.isExtensible,s=r((function(){u(1)}));t.exports=s||a?function(t){return!!i(t)&&(!a||"ArrayBuffer"!=o(t))&&(!u||u(t))}:u},27357:(t,e,n)=>{var r=n(59913);t.exports=r({}.isPrototypeOf)},7282:(t,e,n)=>{var r=n(59913),i=n(98511),o=n(58326),a=n(78035).indexOf,u=n(17307),s=r([].push);t.exports=function(t,e){var n,r=o(t),c=0,d=[];for(n in r)!i(u,n)&&i(r,n)&&s(d,n);for(;e.length>c;)i(r,n=e[c++])&&(~a(d,n)||s(d,n));return d}},95932:(t,e,n)=>{var r=n(7282),i=n(26100);t.exports=Object.keys||function(t){return r(t,i)}},23659:(t,e)=>{"use strict";var n={}.propertyIsEnumerable,r=Object.getOwnPropertyDescriptor,i=r&&!n.call({1:2},1);e.f=i?function(t){var e=r(this,t);return!!e&&e.enumerable}:n},25466:(t,e,n)=>{var r=n(59913),i=n(52546),o=n(41684);t.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var t,e=!1,n={};try{(t=r(Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set))(n,[]),e=n instanceof Array}catch(t){}return function(n,r){return i(n),o(r),e?t(n,r):n.__proto__=r,n}}():void 0)},76389:(t,e,n)=>{var r=n(12115),i=n(59913),o=n(95932),a=n(58326),u=i(n(23659).f),s=i([].push),c=function(t){return function(e){for(var n,i=a(e),c=o(i),d=c.length,l=0,f=[];d>l;)n=c[l++],r&&!u(i,n)||s(f,t?[n,i[n]]:i[n]);return f}};t.exports={entries:c(!0),values:c(!1)}},75954:(t,e,n)=>{"use strict";var r=n(77568),i=n(82814);t.exports=r?{}.toString:function(){return"[object "+i(this)+"]"}},93126:(t,e,n)=>{var r=n(49425),i=n(34028),o=n(51355),a=TypeError;t.exports=function(t,e){var n,u;if("string"===e&&i(n=t.toString)&&!o(u=r(n,t)))return u;if(i(n=t.valueOf)&&!o(u=r(n,t)))return u;if("string"!==e&&i(n=t.toString)&&!o(u=r(n,t)))return u;throw a("Can't convert object to primitive value")}},91537:(t,e,n)=>{var r=n(83155),i=n(59913),o=n(92775),a=n(31711),u=n(52546),s=i([].concat);t.exports=r("Reflect","ownKeys")||function(t){var e=o.f(u(t)),n=a.f;return n?s(e,n(t)):e}},23034:(t,e,n)=>{var r=n(32022);t.exports=r},25786:t=>{t.exports=function(t){try{return{error:!1,value:t()}}catch(t){return{error:!0,value:t}}}},93494:(t,e,n)=>{var r=n(32022),i=n(33183),o=n(34028),a=n(77987),u=n(46169),s=n(30191),c=n(85048),d=n(5835),l=n(68546),f=n(80714),p=i&&i.prototype,h=s("species"),y=!1,m=o(r.PromiseRejectionEvent),v=a("Promise",(function(){var t=u(i),e=t!==String(i);if(!e&&66===f)return!0;if(l&&(!p.catch||!p.finally))return!0;if(!f||f<51||!/native code/.test(t)){var n=new i((function(t){t(1)})),r=function(t){t((function(){}),(function(){}))};if((n.constructor={})[h]=r,!(y=n.then((function(){}))instanceof r))return!0}return!e&&(c||d)&&!m}));t.exports={CONSTRUCTOR:v,REJECTION_EVENT:m,SUBCLASSING:y}},33183:(t,e,n)=>{var r=n(32022);t.exports=r.Promise},39062:(t,e,n)=>{var r=n(52546),i=n(51355),o=n(67892);t.exports=function(t,e){if(r(t),i(e)&&e.constructor===t)return e;var n=o.f(t);return(0,n.resolve)(e),n.promise}},22208:(t,e,n)=>{var r=n(33183),i=n(41269),o=n(93494).CONSTRUCTOR;t.exports=o||!i((function(t){r.all(t).then(void 0,(function(){}))}))},83623:(t,e,n)=>{var r=n(43087).f;t.exports=function(t,e,n){n in t||r(t,n,{configurable:!0,get:function(){return e[n]},set:function(t){e[n]=t}})}},97278:t=>{var e=function(){this.head=null,this.tail=null};e.prototype={add:function(t){var e={item:t,next:null};this.head?this.tail.next=e:this.head=e,this.tail=e},get:function(){var t=this.head;if(t)return this.head=t.next,this.tail===t&&(this.tail=null),t.item}},t.exports=e},70468:(t,e,n)=>{var r=n(49425),i=n(52546),o=n(34028),a=n(39523),u=n(83046),s=TypeError;t.exports=function(t,e){var n=t.exec;if(o(n)){var c=r(n,t,e);return null!==c&&i(c),c}if("RegExp"===a(t))return r(u,t,e);throw s("RegExp#exec called on incompatible receiver")}},83046:(t,e,n)=>{"use strict";var r,i,o=n(49425),a=n(59913),u=n(74170),s=n(60333),c=n(13917),d=n(27905),l=n(13250),f=n(78045).get,p=n(45969),h=n(25404),y=d("native-string-replace",String.prototype.replace),m=RegExp.prototype.exec,v=m,g=a("".charAt),_=a("".indexOf),b=a("".replace),S=a("".slice),w=(i=/b*/g,o(m,r=/a/,"a"),o(m,i,"a"),0!==r.lastIndex||0!==i.lastIndex),C=c.BROKEN_CARET,E=void 0!==/()??/.exec("")[1];(w||E||C||p||h)&&(v=function(t){var e,n,r,i,a,c,d,p=this,h=f(p),I=u(t),P=h.raw;if(P)return P.lastIndex=p.lastIndex,e=o(v,P,I),p.lastIndex=P.lastIndex,e;var A=h.groups,O=C&&p.sticky,T=o(s,p),x=p.source,R=0,k=I;if(O&&(T=b(T,"y",""),-1===_(T,"g")&&(T+="g"),k=S(I,p.lastIndex),p.lastIndex>0&&(!p.multiline||p.multiline&&"\n"!==g(I,p.lastIndex-1))&&(x="(?: "+x+")",k=" "+k,R++),n=new RegExp("^(?:"+x+")",T)),E&&(n=new RegExp("^"+x+"$(?!\\s)",T)),w&&(r=p.lastIndex),i=o(m,O?n:p,k),O?i?(i.input=S(i.input,R),i[0]=S(i[0],R),i.index=p.lastIndex,p.lastIndex+=i[0].length):p.lastIndex=0:w&&i&&(p.lastIndex=p.global?i.index+i[0].length:r),E&&i&&i.length>1&&o(y,i[0],n,(function(){for(a=1;a{"use strict";var r=n(52546);t.exports=function(){var t=r(this),e="";return t.hasIndices&&(e+="d"),t.global&&(e+="g"),t.ignoreCase&&(e+="i"),t.multiline&&(e+="m"),t.dotAll&&(e+="s"),t.unicode&&(e+="u"),t.unicodeSets&&(e+="v"),t.sticky&&(e+="y"),e}},79517:(t,e,n)=>{var r=n(49425),i=n(98511),o=n(27357),a=n(60333),u=RegExp.prototype;t.exports=function(t){var e=t.flags;return void 0!==e||"flags"in u||i(t,"flags")||!o(u,t)?e:r(a,t)}},13917:(t,e,n)=>{var r=n(38986),i=n(32022).RegExp,o=r((function(){var t=i("a","y");return t.lastIndex=2,null!=t.exec("abcd")})),a=o||r((function(){return!i("a","y").sticky})),u=o||r((function(){var t=i("^r","gy");return t.lastIndex=2,null!=t.exec("str")}));t.exports={BROKEN_CARET:u,MISSED_STICKY:a,UNSUPPORTED_Y:o}},45969:(t,e,n)=>{var r=n(38986),i=n(32022).RegExp;t.exports=r((function(){var t=i(".","s");return!(t.dotAll&&t.exec("\n")&&"s"===t.flags)}))},25404:(t,e,n)=>{var r=n(38986),i=n(32022).RegExp;t.exports=r((function(){var t=i("(?b)","g");return"b"!==t.exec("b").groups.a||"bc"!=="b".replace(t,"$c")}))},31591:(t,e,n)=>{var r=n(87126),i=TypeError;t.exports=function(t){if(r(t))throw i("Can't call method on "+t);return t}},60528:t=>{t.exports=Object.is||function(t,e){return t===e?0!==t||1/t==1/e:t!=t&&e!=e}},42343:(t,e,n)=>{"use strict";var r=n(83155),i=n(43087),o=n(30191),a=n(12115),u=o("species");t.exports=function(t){var e=r(t),n=i.f;a&&e&&!e[u]&&n(e,u,{configurable:!0,get:function(){return this}})}},27747:(t,e,n)=>{var r=n(43087).f,i=n(98511),o=n(30191)("toStringTag");t.exports=function(t,e,n){t&&!n&&(t=t.prototype),t&&!i(t,o)&&r(t,o,{configurable:!0,value:e})}},57186:(t,e,n)=>{var r=n(27905),i=n(60232),o=r("keys");t.exports=function(t){return o[t]||(o[t]=i(t))}},43349:(t,e,n)=>{var r=n(32022),i=n(97210),o="__core-js_shared__",a=r[o]||i(o,{});t.exports=a},27905:(t,e,n)=>{var r=n(68546),i=n(43349);(t.exports=function(t,e){return i[t]||(i[t]=void 0!==e?e:{})})("versions",[]).push({version:"3.25.2",mode:r?"pure":"global",copyright:"© 2014-2022 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.25.2/LICENSE",source:"https://github.com/zloirock/core-js"})},33820:(t,e,n)=>{var r=n(52546),i=n(52023),o=n(87126),a=n(30191)("species");t.exports=function(t,e){var n,u=r(t).constructor;return void 0===u||o(n=r(u)[a])?e:i(n)}},9120:(t,e,n)=>{var r=n(38986);t.exports=function(t){return r((function(){var e=""[t]('"');return e!==e.toLowerCase()||e.split('"').length>3}))}},58402:(t,e,n)=>{var r=n(59913),i=n(75982),o=n(74170),a=n(31591),u=r("".charAt),s=r("".charCodeAt),c=r("".slice),d=function(t){return function(e,n){var r,d,l=o(a(e)),f=i(n),p=l.length;return f<0||f>=p?t?"":void 0:(r=s(l,f))<55296||r>56319||f+1===p||(d=s(l,f+1))<56320||d>57343?t?u(l,f):r:t?c(l,f,f+2):d-56320+(r-55296<<10)+65536}};t.exports={codeAt:d(!1),charAt:d(!0)}},4465:(t,e,n)=>{var r=n(30727);t.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(r)},59015:(t,e,n)=>{var r=n(59913),i=n(9375),o=n(74170),a=n(48126),u=n(31591),s=r(a),c=r("".slice),d=Math.ceil,l=function(t){return function(e,n,r){var a,l,f=o(u(e)),p=i(n),h=f.length,y=void 0===r?" ":o(r);return p<=h||""==y?f:((l=s(y,d((a=p-h)/y.length))).length>a&&(l=c(l,0,a)),t?f+l:l+f)}};t.exports={start:l(!1),end:l(!0)}},48126:(t,e,n)=>{"use strict";var r=n(75982),i=n(74170),o=n(31591),a=RangeError;t.exports=function(t){var e=i(o(this)),n="",u=r(t);if(u<0||u==1/0)throw a("Wrong number of repetitions");for(;u>0;(u>>>=1)&&(e+=e))1&u&&(n+=e);return n}},9334:(t,e,n)=>{"use strict";var r=n(76109).end,i=n(41017);t.exports=i("trimEnd")?function(){return r(this)}:"".trimEnd},41017:(t,e,n)=>{var r=n(27765).PROPER,i=n(38986),o=n(60812);t.exports=function(t){return i((function(){return!!o[t]()||"​…᠎"!=="​…᠎"[t]()||r&&o[t].name!==t}))}},97746:(t,e,n)=>{"use strict";var r=n(76109).start,i=n(41017);t.exports=i("trimStart")?function(){return r(this)}:"".trimStart},76109:(t,e,n)=>{var r=n(59913),i=n(31591),o=n(74170),a=n(60812),u=r("".replace),s="["+a+"]",c=RegExp("^"+s+s+"*"),d=RegExp(s+s+"*$"),l=function(t){return function(e){var n=o(i(e));return 1&t&&(n=u(n,c,"")),2&t&&(n=u(n,d,"")),n}};t.exports={start:l(1),end:l(2),trim:l(3)}},86263:(t,e,n)=>{var r=n(80714),i=n(38986);t.exports=!!Object.getOwnPropertySymbols&&!i((function(){var t=Symbol();return!String(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&r&&r<41}))},47498:(t,e,n)=>{var r=n(49425),i=n(83155),o=n(30191),a=n(43068);t.exports=function(){var t=i("Symbol"),e=t&&t.prototype,n=e&&e.valueOf,u=o("toPrimitive");e&&!e[u]&&a(e,u,(function(t){return r(n,this)}),{arity:1})}},55666:(t,e,n)=>{var r=n(86263);t.exports=r&&!!Symbol.for&&!!Symbol.keyFor},16416:(t,e,n)=>{var r,i,o,a,u=n(32022),s=n(10584),c=n(80391),d=n(34028),l=n(98511),f=n(38986),p=n(86419),h=n(23141),y=n(82985),m=n(24246),v=n(649),g=n(79456),_=u.setImmediate,b=u.clearImmediate,S=u.process,w=u.Dispatch,C=u.Function,E=u.MessageChannel,I=u.String,P=0,A={},O="onreadystatechange";try{r=u.location}catch(t){}var T=function(t){if(l(A,t)){var e=A[t];delete A[t],e()}},x=function(t){return function(){T(t)}},R=function(t){T(t.data)},k=function(t){u.postMessage(I(t),r.protocol+"//"+r.host)};_&&b||(_=function(t){m(arguments.length,1);var e=d(t)?t:C(t),n=h(arguments,1);return A[++P]=function(){s(e,void 0,n)},i(P),P},b=function(t){delete A[t]},g?i=function(t){S.nextTick(x(t))}:w&&w.now?i=function(t){w.now(x(t))}:E&&!v?(a=(o=new E).port2,o.port1.onmessage=R,i=c(a.postMessage,a)):u.addEventListener&&d(u.postMessage)&&!u.importScripts&&r&&"file:"!==r.protocol&&!f(k)?(i=k,u.addEventListener("message",R,!1)):i=O in y("script")?function(t){p.appendChild(y("script"))[O]=function(){p.removeChild(this),T(t)}}:function(t){setTimeout(x(t),0)}),t.exports={set:_,clear:b}},10829:(t,e,n)=>{var r=n(59913);t.exports=r(1..valueOf)},86593:(t,e,n)=>{var r=n(75982),i=Math.max,o=Math.min;t.exports=function(t,e){var n=r(t);return n<0?i(n+e,0):o(n,e)}},91173:(t,e,n)=>{var r=n(75982),i=n(9375),o=RangeError;t.exports=function(t){if(void 0===t)return 0;var e=r(t),n=i(e);if(e!==n)throw o("Wrong length or index");return n}},58326:(t,e,n)=>{var r=n(94032),i=n(31591);t.exports=function(t){return r(i(t))}},75982:(t,e,n)=>{var r=n(39309);t.exports=function(t){var e=+t;return e!=e||0===e?0:r(e)}},9375:(t,e,n)=>{var r=n(75982),i=Math.min;t.exports=function(t){return t>0?i(r(t),9007199254740991):0}},47137:(t,e,n)=>{var r=n(31591),i=Object;t.exports=function(t){return i(r(t))}},99127:(t,e,n)=>{var r=n(49425),i=n(51355),o=n(24505),a=n(34040),u=n(93126),s=n(30191),c=TypeError,d=s("toPrimitive");t.exports=function(t,e){if(!i(t)||o(t))return t;var n,s=a(t,d);if(s){if(void 0===e&&(e="default"),n=r(s,t,e),!i(n)||o(n))return n;throw c("Can't convert object to primitive value")}return void 0===e&&(e="number"),u(t,e)}},79127:(t,e,n)=>{var r=n(99127),i=n(24505);t.exports=function(t){var e=r(t,"string");return i(e)?e:e+""}},77568:(t,e,n)=>{var r={};r[n(30191)("toStringTag")]="z",t.exports="[object z]"===String(r)},74170:(t,e,n)=>{var r=n(82814),i=String;t.exports=function(t){if("Symbol"===r(t))throw TypeError("Cannot convert a Symbol value to a string");return i(t)}},84160:t=>{var e=String;t.exports=function(t){try{return e(t)}catch(t){return"Object"}}},60232:(t,e,n)=>{var r=n(59913),i=0,o=Math.random(),a=r(1..toString);t.exports=function(t){return"Symbol("+(void 0===t?"":t)+")_"+a(++i+o,36)}},78590:(t,e,n)=>{var r=n(86263);t.exports=r&&!Symbol.sham&&"symbol"==typeof Symbol.iterator},71330:(t,e,n)=>{var r=n(12115),i=n(38986);t.exports=r&&i((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype}))},24246:t=>{var e=TypeError;t.exports=function(t,n){if(t{var r=n(32022),i=n(34028),o=r.WeakMap;t.exports=i(o)&&/native code/.test(String(o))},91165:(t,e,n)=>{var r=n(23034),i=n(98511),o=n(58855),a=n(43087).f;t.exports=function(t){var e=r.Symbol||(r.Symbol={});i(e,t)||a(e,t,{value:o.f(t)})}},58855:(t,e,n)=>{var r=n(30191);e.f=r},30191:(t,e,n)=>{var r=n(32022),i=n(27905),o=n(98511),a=n(60232),u=n(86263),s=n(78590),c=i("wks"),d=r.Symbol,l=d&&d.for,f=s?d:d&&d.withoutSetter||a;t.exports=function(t){if(!o(c,t)||!u&&"string"!=typeof c[t]){var e="Symbol."+t;u&&o(d,t)?c[t]=d[t]:c[t]=s&&l?l(e):f(e)}return c[t]}},60812:t=>{t.exports="\t\n\v\f\r                 \u2028\u2029\ufeff"},14459:(t,e,n)=>{"use strict";var r=n(54635),i=n(32022),o=n(65140),a=n(42343),u="ArrayBuffer",s=o[u];r({global:!0,constructor:!0,forced:i[u]!==s},{ArrayBuffer:s}),a(u)},75894:(t,e,n)=>{"use strict";var r=n(54635),i=n(59913),o=n(38986),a=n(65140),u=n(52546),s=n(86593),c=n(9375),d=n(33820),l=a.ArrayBuffer,f=a.DataView,p=f.prototype,h=i(l.prototype.slice),y=i(p.getUint8),m=i(p.setUint8);r({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:o((function(){return!new l(2).slice(1,void 0).byteLength}))},{slice:function(t,e){if(h&&void 0===e)return h(u(this),t);for(var n=u(this).byteLength,r=s(t,n),i=s(void 0===e?n:e,n),o=new(d(this,l))(c(i-r)),a=new f(this),p=new f(o),v=0;r{"use strict";var r=n(54635),i=n(38986),o=n(65351),a=n(51355),u=n(47137),s=n(84117),c=n(81912),d=n(19402),l=n(74842),f=n(41665),p=n(30191),h=n(80714),y=p("isConcatSpreadable"),m=h>=51||!i((function(){var t=[];return t[y]=!1,t.concat()[0]!==t})),v=f("concat"),g=function(t){if(!a(t))return!1;var e=t[y];return void 0!==e?!!e:o(t)};r({target:"Array",proto:!0,arity:1,forced:!m||!v},{concat:function(t){var e,n,r,i,o,a=u(this),f=l(a,0),p=0;for(e=-1,r=arguments.length;e{var r=n(54635),i=n(13750),o=n(47512);r({target:"Array",proto:!0},{fill:i}),o("fill")},51725:(t,e,n)=>{"use strict";var r=n(54635),i=n(55883).filter;r({target:"Array",proto:!0,forced:!n(41665)("filter")},{filter:function(t){return i(this,t,arguments.length>1?arguments[1]:void 0)}})},23143:(t,e,n)=>{"use strict";var r=n(54635),i=n(55883).findIndex,o=n(47512),a="findIndex",u=!0;a in[]&&Array(1)[a]((function(){u=!1})),r({target:"Array",proto:!0,forced:u},{findIndex:function(t){return i(this,t,arguments.length>1?arguments[1]:void 0)}}),o(a)},88342:(t,e,n)=>{"use strict";var r=n(54635),i=n(55883).find,o=n(47512),a="find",u=!0;a in[]&&Array(1)[a]((function(){u=!1})),r({target:"Array",proto:!0,forced:u},{find:function(t){return i(this,t,arguments.length>1?arguments[1]:void 0)}}),o(a)},25036:(t,e,n)=>{"use strict";var r=n(54635),i=n(47484),o=n(86173),a=n(47137),u=n(84117),s=n(74842);r({target:"Array",proto:!0},{flatMap:function(t){var e,n=a(this),r=u(n);return o(t),(e=s(n,0)).length=i(e,n,n,r,0,1,t,arguments.length>1?arguments[1]:void 0),e}})},95040:(t,e,n)=>{var r=n(54635),i=n(65375);r({target:"Array",stat:!0,forced:!n(41269)((function(t){Array.from(t)}))},{from:i})},5099:(t,e,n)=>{"use strict";var r=n(54635),i=n(78035).includes,o=n(38986),a=n(47512);r({target:"Array",proto:!0,forced:o((function(){return!Array(1).includes()}))},{includes:function(t){return i(this,t,arguments.length>1?arguments[1]:void 0)}}),a("includes")},6550:(t,e,n)=>{"use strict";var r=n(54635),i=n(59913),o=n(78035).indexOf,a=n(94694),u=i([].indexOf),s=!!u&&1/u([1],1,-0)<0,c=a("indexOf");r({target:"Array",proto:!0,forced:s||!c},{indexOf:function(t){var e=arguments.length>1?arguments[1]:void 0;return s?u(this,t,e)||0:o(this,t,e)}})},38490:(t,e,n)=>{"use strict";var r=n(58326),i=n(47512),o=n(13766),a=n(78045),u=n(43087).f,s=n(53338),c=n(80251),d=n(68546),l=n(12115),f="Array Iterator",p=a.set,h=a.getterFor(f);t.exports=s(Array,"Array",(function(t,e){p(this,{type:f,target:r(t),index:0,kind:e})}),(function(){var t=h(this),e=t.target,n=t.kind,r=t.index++;return!e||r>=e.length?(t.target=void 0,c(void 0,!0)):c("keys"==n?r:"values"==n?e[r]:[r,e[r]],!1)}),"values");var y=o.Arguments=o.Array;if(i("keys"),i("values"),i("entries"),!d&&l&&"values"!==y.name)try{u(y,"name",{value:"values"})}catch(t){}},64668:(t,e,n)=>{"use strict";var r=n(54635),i=n(59913),o=n(94032),a=n(58326),u=n(94694),s=i([].join),c=o!=Object,d=u("join",",");r({target:"Array",proto:!0,forced:c||!d},{join:function(t){return s(a(this),void 0===t?",":t)}})},74803:(t,e,n)=>{var r=n(54635),i=n(44687);r({target:"Array",proto:!0,forced:i!==[].lastIndexOf},{lastIndexOf:i})},95412:(t,e,n)=>{"use strict";var r=n(54635),i=n(55883).map;r({target:"Array",proto:!0,forced:!n(41665)("map")},{map:function(t){return i(this,t,arguments.length>1?arguments[1]:void 0)}})},72590:(t,e,n)=>{"use strict";var r=n(54635),i=n(59913),o=n(65351),a=i([].reverse),u=[1,2];r({target:"Array",proto:!0,forced:String(u)===String(u.reverse())},{reverse:function(){return o(this)&&(this.length=this.length),a(this)}})},16516:(t,e,n)=>{"use strict";var r=n(54635),i=n(65351),o=n(78449),a=n(51355),u=n(86593),s=n(84117),c=n(58326),d=n(19402),l=n(30191),f=n(41665),p=n(23141),h=f("slice"),y=l("species"),m=Array,v=Math.max;r({target:"Array",proto:!0,forced:!h},{slice:function(t,e){var n,r,l,f=c(this),h=s(f),g=u(t,h),_=u(void 0===e?h:e,h);if(i(f)&&(n=f.constructor,(o(n)&&(n===m||i(n.prototype))||a(n)&&null===(n=n[y]))&&(n=void 0),n===m||void 0===n))return p(f,g,_);for(r=new(void 0===n?m:n)(v(_-g,0)),l=0;g<_;g++,l++)g in f&&d(r,l,f[g]);return r.length=l,r}})},2934:(t,e,n)=>{"use strict";var r=n(54635),i=n(59913),o=n(86173),a=n(47137),u=n(84117),s=n(39850),c=n(74170),d=n(38986),l=n(71929),f=n(94694),p=n(93454),h=n(88633),y=n(80714),m=n(10720),v=[],g=i(v.sort),_=i(v.push),b=d((function(){v.sort(void 0)})),S=d((function(){v.sort(null)})),w=f("sort"),C=!d((function(){if(y)return y<70;if(!(p&&p>3)){if(h)return!0;if(m)return m<603;var t,e,n,r,i="";for(t=65;t<76;t++){switch(e=String.fromCharCode(t),t){case 66:case 69:case 70:case 72:n=3;break;case 68:case 71:n=4;break;default:n=2}for(r=0;r<47;r++)v.push({k:e+r,v:n})}for(v.sort((function(t,e){return e.v-t.v})),r=0;rc(n)?1:-1}}(t)),n=u(i),r=0;r{"use strict";var r=n(54635),i=n(47137),o=n(86593),a=n(75982),u=n(84117),s=n(17761),c=n(81912),d=n(74842),l=n(19402),f=n(39850),p=n(41665)("splice"),h=Math.max,y=Math.min;r({target:"Array",proto:!0,forced:!p},{splice:function(t,e){var n,r,p,m,v,g,_=i(this),b=u(_),S=o(t,b),w=arguments.length;for(0===w?n=r=0:1===w?(n=0,r=b-S):(n=w-2,r=y(h(a(e),0),b-S)),c(b+n-r),p=d(_,r),m=0;mb-r+n;m--)f(_,m-1)}else if(n>r)for(m=b-r;m>S;m--)g=m+n-1,(v=m+r-1)in _?_[g]=_[v]:f(_,g);for(m=0;m{n(47512)("flatMap")},16368:(t,e,n)=>{var r=n(98511),i=n(43068),o=n(68959),a=n(30191)("toPrimitive"),u=Date.prototype;r(u,a)||i(u,a,o)},34745:(t,e,n)=>{var r=n(12115),i=n(27765).EXISTS,o=n(59913),a=n(43087).f,u=Function.prototype,s=o(u.toString),c=/function\b(?:\s|\/\*[\S\s]*?\*\/|\/\/[^\n\r]*[\n\r]+)*([^\s(/]*)/,d=o(c.exec);r&&!i&&a(u,"name",{configurable:!0,get:function(){try{return d(c,s(this))[1]}catch(t){return""}}})},55205:(t,e,n)=>{var r=n(54635),i=n(83155),o=n(10584),a=n(49425),u=n(59913),s=n(38986),c=n(65351),d=n(34028),l=n(51355),f=n(24505),p=n(23141),h=n(86263),y=i("JSON","stringify"),m=u(/./.exec),v=u("".charAt),g=u("".charCodeAt),_=u("".replace),b=u(1..toString),S=/[\uD800-\uDFFF]/g,w=/^[\uD800-\uDBFF]$/,C=/^[\uDC00-\uDFFF]$/,E=!h||s((function(){var t=i("Symbol")();return"[null]"!=y([t])||"{}"!=y({a:t})||"{}"!=y(Object(t))})),I=s((function(){return'"\\udf06\\ud834"'!==y("\udf06\ud834")||'"\\udead"'!==y("\udead")})),P=function(t,e){var n=p(arguments),r=e;if((l(e)||void 0!==t)&&!f(t))return c(e)||(e=function(t,e){if(d(r)&&(e=a(r,this,t,e)),!f(e))return e}),n[1]=e,o(y,null,n)},A=function(t,e,n){var r=v(n,e-1),i=v(n,e+1);return m(w,t)&&!m(C,i)||m(C,t)&&!m(w,r)?"\\u"+b(g(t,0),16):t};y&&r({target:"JSON",stat:!0,arity:3,forced:E||I},{stringify:function(t,e,n){var r=p(arguments),i=o(E?P:y,null,r);return I&&"string"==typeof i?_(i,S,A):i}})},3635:(t,e,n)=>{"use strict";n(69866)("Map",(function(t){return function(){return t(this,arguments.length?arguments[0]:void 0)}}),n(61961))},34897:(t,e,n)=>{n(3635)},99023:(t,e,n)=>{"use strict";var r=n(12115),i=n(32022),o=n(59913),a=n(77987),u=n(43068),s=n(98511),c=n(99618),d=n(27357),l=n(24505),f=n(99127),p=n(38986),h=n(92775).f,y=n(66213).f,m=n(43087).f,v=n(10829),g=n(76109).trim,_="Number",b=i[_],S=b.prototype,w=i.TypeError,C=o("".slice),E=o("".charCodeAt);if(a(_,!b(" 0o1")||!b("0b1")||b("+0x1"))){for(var I,P=function(t){var e=arguments.length<1?0:b(function(t){var e=f(t,"number");return"bigint"==typeof e?e:function(t){var e,n,r,i,o,a,u,s,c=f(t,"number");if(l(c))throw w("Cannot convert a Symbol value to a number");if("string"==typeof c&&c.length>2)if(c=g(c),43===(e=E(c,0))||45===e){if(88===(n=E(c,2))||120===n)return NaN}else if(48===e){switch(E(c,1)){case 66:case 98:r=2,i=49;break;case 79:case 111:r=8,i=55;break;default:return+c}for(a=(o=C(c,2)).length,u=0;ui)return NaN;return parseInt(o,r)}return+c}(e)}(t)),n=this;return d(S,n)&&p((function(){v(n)}))?c(Object(e),n,P):e},A=r?h(b):"MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,isFinite,isInteger,isNaN,isSafeInteger,parseFloat,parseInt,fromString,range".split(","),O=0;A.length>O;O++)s(b,I=A[O])&&!s(P,I)&&m(P,I,y(b,I));P.prototype=S,S.constructor=P,u(i,_,P,{constructor:!0})}},80226:(t,e,n)=>{n(54635)({target:"Number",stat:!0},{isNaN:function(t){return t!=t}})},21212:(t,e,n)=>{"use strict";var r=n(54635),i=n(59913),o=n(75982),a=n(10829),u=n(48126),s=n(38986),c=RangeError,d=String,l=Math.floor,f=i(u),p=i("".slice),h=i(1..toFixed),y=function(t,e,n){return 0===e?n:e%2==1?y(t,e-1,n*t):y(t*t,e/2,n)},m=function(t,e,n){for(var r=-1,i=n;++r<6;)i+=e*t[r],t[r]=i%1e7,i=l(i/1e7)},v=function(t,e){for(var n=6,r=0;--n>=0;)r+=t[n],t[n]=l(r/e),r=r%e*1e7},g=function(t){for(var e=6,n="";--e>=0;)if(""!==n||0===e||0!==t[e]){var r=d(t[e]);n=""===n?r:n+f("0",7-r.length)+r}return n};r({target:"Number",proto:!0,forced:s((function(){return"0.000"!==h(8e-5,3)||"1"!==h(.9,0)||"1.25"!==h(1.255,2)||"1000000000000000128"!==h(0xde0b6b3a7640080,0)}))||!s((function(){h({})}))},{toFixed:function(t){var e,n,r,i,u=a(this),s=o(t),l=[0,0,0,0,0,0],h="",_="0";if(s<0||s>20)throw c("Incorrect fraction digits");if(u!=u)return"NaN";if(u<=-1e21||u>=1e21)return d(u);if(u<0&&(h="-",u=-u),u>1e-21)if(n=(e=function(t){for(var e=0,n=t;n>=4096;)e+=12,n/=4096;for(;n>=2;)e+=1,n/=2;return e}(u*y(2,69,1))-69)<0?u*y(2,-e,1):u/y(2,e,1),n*=4503599627370496,(e=52-e)>0){for(m(l,0,n),r=s;r>=7;)m(l,1e7,0),r-=7;for(m(l,y(10,r,1),0),r=e-1;r>=23;)v(l,1<<23),r-=23;v(l,1<0?h+((i=_.length)<=s?"0."+f("0",s-i)+_:p(_,0,i-s)+"."+p(_,i-s)):h+_}})},27835:(t,e,n)=>{var r=n(54635),i=n(86851);r({target:"Object",stat:!0,arity:2,forced:Object.assign!==i},{assign:i})},64701:(t,e,n)=>{var r=n(54635),i=n(76389).entries;r({target:"Object",stat:!0},{entries:function(t){return i(t)}})},33409:(t,e,n)=>{var r=n(54635),i=n(6769),o=n(38986),a=n(51355),u=n(67023).onFreeze,s=Object.freeze;r({target:"Object",stat:!0,forced:o((function(){s(1)})),sham:!i},{freeze:function(t){return s&&a(t)?s(u(t)):t}})},19926:(t,e,n)=>{var r=n(54635),i=n(38986),o=n(58326),a=n(66213).f,u=n(12115),s=i((function(){a(1)}));r({target:"Object",stat:!0,forced:!u||s,sham:!u},{getOwnPropertyDescriptor:function(t,e){return a(o(t),e)}})},60678:(t,e,n)=>{var r=n(54635),i=n(38986),o=n(12098).f;r({target:"Object",stat:!0,forced:i((function(){return!Object.getOwnPropertyNames(1)}))},{getOwnPropertyNames:o})},17524:(t,e,n)=>{var r=n(54635),i=n(86263),o=n(38986),a=n(31711),u=n(47137);r({target:"Object",stat:!0,forced:!i||o((function(){a.f(1)}))},{getOwnPropertySymbols:function(t){var e=a.f;return e?e(u(t)):[]}})},71582:(t,e,n)=>{var r=n(54635),i=n(38986),o=n(47137),a=n(75783),u=n(88538);r({target:"Object",stat:!0,forced:i((function(){a(1)})),sham:!u},{getPrototypeOf:function(t){return a(o(t))}})},97814:(t,e,n)=>{var r=n(54635),i=n(38986),o=n(51355),a=n(39523),u=n(1743),s=Object.isFrozen;r({target:"Object",stat:!0,forced:i((function(){s(1)}))||u},{isFrozen:function(t){return!o(t)||!(!u||"ArrayBuffer"!=a(t))||!!s&&s(t)}})},13722:(t,e,n)=>{var r=n(54635),i=n(47137),o=n(95932);r({target:"Object",stat:!0,forced:n(38986)((function(){o(1)}))},{keys:function(t){return o(i(t))}})},28101:(t,e,n)=>{n(54635)({target:"Object",stat:!0},{setPrototypeOf:n(25466)})},40737:(t,e,n)=>{var r=n(77568),i=n(43068),o=n(75954);r||i(Object.prototype,"toString",o,{unsafe:!0})},83681:(t,e,n)=>{var r=n(54635),i=n(57017);r({global:!0,forced:parseFloat!=i},{parseFloat:i})},50633:(t,e,n)=>{var r=n(54635),i=n(84475);r({global:!0,forced:parseInt!=i},{parseInt:i})},47197:(t,e,n)=>{"use strict";var r=n(54635),i=n(49425),o=n(86173),a=n(67892),u=n(25786),s=n(38640);r({target:"Promise",stat:!0,forced:n(22208)},{all:function(t){var e=this,n=a.f(e),r=n.resolve,c=n.reject,d=u((function(){var n=o(e.resolve),a=[],u=0,d=1;s(t,(function(t){var o=u++,s=!1;d++,i(n,e,t).then((function(t){s||(s=!0,a[o]=t,--d||r(a))}),c)})),--d||r(a)}));return d.error&&c(d.value),n.promise}})},41395:(t,e,n)=>{"use strict";var r=n(54635),i=n(68546),o=n(93494).CONSTRUCTOR,a=n(33183),u=n(83155),s=n(34028),c=n(43068),d=a&&a.prototype;if(r({target:"Promise",proto:!0,forced:o,real:!0},{catch:function(t){return this.then(void 0,t)}}),!i&&s(a)){var l=u("Promise").prototype.catch;d.catch!==l&&c(d,"catch",l,{unsafe:!0})}},59761:(t,e,n)=>{"use strict";var r,i,o,a=n(54635),u=n(68546),s=n(79456),c=n(32022),d=n(49425),l=n(43068),f=n(25466),p=n(27747),h=n(42343),y=n(86173),m=n(34028),v=n(51355),g=n(39837),_=n(33820),b=n(16416).set,S=n(76173),w=n(39361),C=n(25786),E=n(97278),I=n(78045),P=n(33183),A=n(93494),O=n(67892),T="Promise",x=A.CONSTRUCTOR,R=A.REJECTION_EVENT,k=A.SUBCLASSING,M=I.getterFor(T),N=I.set,D=P&&P.prototype,L=P,z=D,j=c.TypeError,U=c.document,F=c.process,q=O.f,B=q,G=!!(U&&U.createEvent&&c.dispatchEvent),V="unhandledrejection",Y=function(t){var e;return!(!v(t)||!m(e=t.then))&&e},H=function(t,e){var n,r,i,o=e.value,a=1==e.state,u=a?t.ok:t.fail,s=t.resolve,c=t.reject,l=t.domain;try{u?(a||(2===e.rejection&&J(e),e.rejection=1),!0===u?n=o:(l&&l.enter(),n=u(o),l&&(l.exit(),i=!0)),n===t.promise?c(j("Promise-chain cycle")):(r=Y(n))?d(r,n,s,c):s(n)):c(o)}catch(t){l&&!i&&l.exit(),c(t)}},W=function(t,e){t.notified||(t.notified=!0,S((function(){for(var n,r=t.reactions;n=r.get();)H(n,t);t.notified=!1,e&&!t.rejection&&Z(t)})))},K=function(t,e,n){var r,i;G?((r=U.createEvent("Event")).promise=e,r.reason=n,r.initEvent(t,!1,!0),c.dispatchEvent(r)):r={promise:e,reason:n},!R&&(i=c["on"+t])?i(r):t===V&&w("Unhandled promise rejection",n)},Z=function(t){d(b,c,(function(){var e,n=t.facade,r=t.value;if($(t)&&(e=C((function(){s?F.emit("unhandledRejection",r,n):K(V,n,r)})),t.rejection=s||$(t)?2:1,e.error))throw e.value}))},$=function(t){return 1!==t.rejection&&!t.parent},J=function(t){d(b,c,(function(){var e=t.facade;s?F.emit("rejectionHandled",e):K("rejectionhandled",e,t.value)}))},Q=function(t,e,n){return function(r){t(e,r,n)}},X=function(t,e,n){t.done||(t.done=!0,n&&(t=n),t.value=e,t.state=2,W(t,!0))},tt=function(t,e,n){if(!t.done){t.done=!0,n&&(t=n);try{if(t.facade===e)throw j("Promise can't be resolved itself");var r=Y(e);r?S((function(){var n={done:!1};try{d(r,e,Q(tt,n,t),Q(X,n,t))}catch(e){X(n,e,t)}})):(t.value=e,t.state=1,W(t,!1))}catch(e){X({done:!1},e,t)}}};if(x&&(z=(L=function(t){g(this,z),y(t),d(r,this);var e=M(this);try{t(Q(tt,e),Q(X,e))}catch(t){X(e,t)}}).prototype,(r=function(t){N(this,{type:T,done:!1,notified:!1,parent:!1,reactions:new E,rejection:!1,state:0,value:void 0})}).prototype=l(z,"then",(function(t,e){var n=M(this),r=q(_(this,L));return n.parent=!0,r.ok=!m(t)||t,r.fail=m(e)&&e,r.domain=s?F.domain:void 0,0==n.state?n.reactions.add(r):S((function(){H(r,n)})),r.promise})),i=function(){var t=new r,e=M(t);this.promise=t,this.resolve=Q(tt,e),this.reject=Q(X,e)},O.f=q=function(t){return t===L||void 0===t?new i(t):B(t)},!u&&m(P)&&D!==Object.prototype)){o=D.then,k||l(D,"then",(function(t,e){var n=this;return new L((function(t,e){d(o,n,t,e)})).then(t,e)}),{unsafe:!0});try{delete D.constructor}catch(t){}f&&f(D,z)}a({global:!0,constructor:!0,wrap:!0,forced:x},{Promise:L}),p(L,T,!1,!0),h(T)},83823:(t,e,n)=>{n(59761),n(47197),n(41395),n(99790),n(38777),n(79244)},99790:(t,e,n)=>{"use strict";var r=n(54635),i=n(49425),o=n(86173),a=n(67892),u=n(25786),s=n(38640);r({target:"Promise",stat:!0,forced:n(22208)},{race:function(t){var e=this,n=a.f(e),r=n.reject,c=u((function(){var a=o(e.resolve);s(t,(function(t){i(a,e,t).then(n.resolve,r)}))}));return c.error&&r(c.value),n.promise}})},38777:(t,e,n)=>{"use strict";var r=n(54635),i=n(49425),o=n(67892);r({target:"Promise",stat:!0,forced:n(93494).CONSTRUCTOR},{reject:function(t){var e=o.f(this);return i(e.reject,void 0,t),e.promise}})},79244:(t,e,n)=>{"use strict";var r=n(54635),i=n(83155),o=n(68546),a=n(33183),u=n(93494).CONSTRUCTOR,s=n(39062),c=i("Promise"),d=o&&!u;r({target:"Promise",stat:!0,forced:o||u},{resolve:function(t){return s(d&&this===c?a:this,t)}})},84868:(t,e,n)=>{var r=n(12115),i=n(32022),o=n(59913),a=n(77987),u=n(99618),s=n(22775),c=n(92775).f,d=n(27357),l=n(91035),f=n(74170),p=n(79517),h=n(13917),y=n(83623),m=n(43068),v=n(38986),g=n(98511),_=n(78045).enforce,b=n(42343),S=n(30191),w=n(45969),C=n(25404),E=S("match"),I=i.RegExp,P=I.prototype,A=i.SyntaxError,O=o(P.exec),T=o("".charAt),x=o("".replace),R=o("".indexOf),k=o("".slice),M=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,N=/a/g,D=/a/g,L=new I(N)!==N,z=h.MISSED_STICKY,j=h.UNSUPPORTED_Y;if(a("RegExp",r&&(!L||z||w||C||v((function(){return D[E]=!1,I(N)!=N||I(D)==D||"/a/i"!=I(N,"i")}))))){for(var U=function(t,e){var n,r,i,o,a,c,h=d(P,this),y=l(t),m=void 0===e,v=[],b=t;if(!h&&y&&m&&t.constructor===U)return t;if((y||d(P,t))&&(t=t.source,m&&(e=p(b))),t=void 0===t?"":f(t),e=void 0===e?"":f(e),b=t,w&&"dotAll"in N&&(r=!!e&&R(e,"s")>-1)&&(e=x(e,/s/g,"")),n=e,z&&"sticky"in N&&(i=!!e&&R(e,"y")>-1)&&j&&(e=x(e,/y/g,"")),C&&(o=function(t){for(var e,n=t.length,r=0,i="",o=[],a={},u=!1,s=!1,c=0,d="";r<=n;r++){if("\\"===(e=T(t,r)))e+=T(t,++r);else if("]"===e)u=!1;else if(!u)switch(!0){case"["===e:u=!0;break;case"("===e:O(M,k(t,r+1))&&(r+=2,s=!0),i+=e,c++;continue;case">"===e&&s:if(""===d||g(a,d))throw new A("Invalid capture group name");a[d]=!0,o[o.length]=[d,c],s=!1,d="";continue}s?d+=e:i+=e}return[i,o]}(t),t=o[0],v=o[1]),a=u(I(t,e),h?this:P,U),(r||i||v.length)&&(c=_(a),r&&(c.dotAll=!0,c.raw=U(function(t){for(var e,n=t.length,r=0,i="",o=!1;r<=n;r++)"\\"!==(e=T(t,r))?o||"."!==e?("["===e?o=!0:"]"===e&&(o=!1),i+=e):i+="[\\s\\S]":i+=e+T(t,++r);return i}(t),n)),i&&(c.sticky=!0),v.length&&(c.groups=v)),t!==b)try{s(a,"source",""===b?"(?:)":b)}catch(t){}return a},F=c(I),q=0;F.length>q;)y(U,I,F[q++]);P.constructor=U,U.prototype=P,m(i,"RegExp",U,{constructor:!0})}b("RegExp")},49636:(t,e,n)=>{"use strict";var r=n(54635),i=n(83046);r({target:"RegExp",proto:!0,forced:/./.exec!==i},{exec:i})},26667:(t,e,n)=>{"use strict";var r=n(27765).PROPER,i=n(43068),o=n(52546),a=n(74170),u=n(38986),s=n(79517),c="toString",d=RegExp.prototype[c],l=u((function(){return"/a/b"!=d.call({source:"a",flags:"b"})})),f=r&&d.name!=c;(l||f)&&i(RegExp.prototype,c,(function(){var t=o(this);return"/"+a(t.source)+"/"+a(s(t))}),{unsafe:!0})},1386:(t,e,n)=>{"use strict";n(69866)("Set",(function(t){return function(){return t(this,arguments.length?arguments[0]:void 0)}}),n(61961))},98351:(t,e,n)=>{n(1386)},51996:(t,e,n)=>{"use strict";var r,i=n(54635),o=n(59913),a=n(66213).f,u=n(9375),s=n(74170),c=n(17911),d=n(31591),l=n(41813),f=n(68546),p=o("".endsWith),h=o("".slice),y=Math.min,m=l("endsWith");i({target:"String",proto:!0,forced:!(!f&&!m&&(r=a(String.prototype,"endsWith"),r&&!r.writable)||m)},{endsWith:function(t){var e=s(d(this));c(t);var n=arguments.length>1?arguments[1]:void 0,r=e.length,i=void 0===n?r:y(u(n),r),o=s(t);return p?p(e,o,i):h(e,i-o.length,i)===o}})},74035:(t,e,n)=>{"use strict";var r=n(54635),i=n(59913),o=n(17911),a=n(31591),u=n(74170),s=n(41813),c=i("".indexOf);r({target:"String",proto:!0,forced:!s("includes")},{includes:function(t){return!!~c(u(a(this)),u(o(t)),arguments.length>1?arguments[1]:void 0)}})},10951:(t,e,n)=>{"use strict";var r=n(58402).charAt,i=n(74170),o=n(78045),a=n(53338),u=n(80251),s="String Iterator",c=o.set,d=o.getterFor(s);a(String,"String",(function(t){c(this,{type:s,string:i(t),index:0})}),(function(){var t,e=d(this),n=e.string,i=e.index;return i>=n.length?u(void 0,!0):(t=r(n,i),e.index+=t.length,u(t,!1))}))},88720:(t,e,n)=>{"use strict";var r=n(54635),i=n(89444);r({target:"String",proto:!0,forced:n(9120)("link")},{link:function(t){return i(this,"a","href",t)}})},15483:(t,e,n)=>{"use strict";var r=n(49425),i=n(26210),o=n(52546),a=n(87126),u=n(9375),s=n(74170),c=n(31591),d=n(34040),l=n(75527),f=n(70468);i("match",(function(t,e,n){return[function(e){var n=c(this),i=a(e)?void 0:d(e,t);return i?r(i,e,n):new RegExp(e)[t](s(n))},function(t){var r=o(this),i=s(t),a=n(e,r,i);if(a.done)return a.value;if(!r.global)return f(r,i);var c=r.unicode;r.lastIndex=0;for(var d,p=[],h=0;null!==(d=f(r,i));){var y=s(d[0]);p[h]=y,""===y&&(r.lastIndex=l(i,u(r.lastIndex),c)),h++}return 0===h?null:p}]}))},40550:(t,e,n)=>{"use strict";var r=n(54635),i=n(59015).end;r({target:"String",proto:!0,forced:n(4465)},{padEnd:function(t){return i(this,t,arguments.length>1?arguments[1]:void 0)}})},79963:(t,e,n)=>{"use strict";var r=n(54635),i=n(59015).start;r({target:"String",proto:!0,forced:n(4465)},{padStart:function(t){return i(this,t,arguments.length>1?arguments[1]:void 0)}})},41267:(t,e,n)=>{n(54635)({target:"String",proto:!0},{repeat:n(48126)})},58443:(t,e,n)=>{"use strict";var r=n(10584),i=n(49425),o=n(59913),a=n(26210),u=n(38986),s=n(52546),c=n(34028),d=n(87126),l=n(75982),f=n(9375),p=n(74170),h=n(31591),y=n(75527),m=n(34040),v=n(82319),g=n(70468),_=n(30191)("replace"),b=Math.max,S=Math.min,w=o([].concat),C=o([].push),E=o("".indexOf),I=o("".slice),P="$0"==="a".replace(/./,"$0"),A=!!/./[_]&&""===/./[_]("a","$0");a("replace",(function(t,e,n){var o=A?"$":"$0";return[function(t,n){var r=h(this),o=d(t)?void 0:m(t,_);return o?i(o,t,r,n):i(e,p(r),t,n)},function(t,i){var a=s(this),u=p(t);if("string"==typeof i&&-1===E(i,o)&&-1===E(i,"$<")){var d=n(e,a,u,i);if(d.done)return d.value}var h=c(i);h||(i=p(i));var m=a.global;if(m){var _=a.unicode;a.lastIndex=0}for(var P=[];;){var A=g(a,u);if(null===A)break;if(C(P,A),!m)break;""===p(A[0])&&(a.lastIndex=y(u,f(a.lastIndex),_))}for(var O,T="",x=0,R=0;R=x&&(T+=I(u,x,M)+j,x=M+k.length)}return T+I(u,x)}]}),!!u((function(){var t=/./;return t.exec=function(){var t=[];return t.groups={a:"7"},t},"7"!=="".replace(t,"$")}))||!P||A)},57347:(t,e,n)=>{"use strict";var r=n(49425),i=n(26210),o=n(52546),a=n(87126),u=n(31591),s=n(60528),c=n(74170),d=n(34040),l=n(70468);i("search",(function(t,e,n){return[function(e){var n=u(this),i=a(e)?void 0:d(e,t);return i?r(i,e,n):new RegExp(e)[t](c(n))},function(t){var r=o(this),i=c(t),a=n(e,r,i);if(a.done)return a.value;var u=r.lastIndex;s(u,0)||(r.lastIndex=0);var d=l(r,i);return s(r.lastIndex,u)||(r.lastIndex=u),null===d?-1:d.index}]}))},34500:(t,e,n)=>{"use strict";var r=n(10584),i=n(49425),o=n(59913),a=n(26210),u=n(52546),s=n(87126),c=n(91035),d=n(31591),l=n(33820),f=n(75527),p=n(9375),h=n(74170),y=n(34040),m=n(42893),v=n(70468),g=n(83046),_=n(13917),b=n(38986),S=_.UNSUPPORTED_Y,w=4294967295,C=Math.min,E=[].push,I=o(/./.exec),P=o(E),A=o("".slice);a("split",(function(t,e,n){var o;return o="c"=="abbc".split(/(b)*/)[1]||4!="test".split(/(?:)/,-1).length||2!="ab".split(/(?:ab)*/).length||4!=".".split(/(.?)(.?)/).length||".".split(/()()/).length>1||"".split(/.?/).length?function(t,n){var o=h(d(this)),a=void 0===n?w:n>>>0;if(0===a)return[];if(void 0===t)return[o];if(!c(t))return i(e,o,t,a);for(var u,s,l,f=[],p=(t.ignoreCase?"i":"")+(t.multiline?"m":"")+(t.unicode?"u":"")+(t.sticky?"y":""),y=0,v=new RegExp(t.source,p+"g");(u=i(g,v,o))&&!((s=v.lastIndex)>y&&(P(f,A(o,y,u.index)),u.length>1&&u.index=a));)v.lastIndex===u.index&&v.lastIndex++;return y===o.length?!l&&I(v,"")||P(f,""):P(f,A(o,y)),f.length>a?m(f,0,a):f}:"0".split(void 0,0).length?function(t,n){return void 0===t&&0===n?[]:i(e,this,t,n)}:e,[function(e,n){var r=d(this),a=s(e)?void 0:y(e,t);return a?i(a,e,r,n):i(o,h(r),e,n)},function(t,r){var i=u(this),a=h(t),s=n(o,i,a,r,o!==e);if(s.done)return s.value;var c=l(i,RegExp),d=i.unicode,y=(i.ignoreCase?"i":"")+(i.multiline?"m":"")+(i.unicode?"u":"")+(S?"g":"y"),m=new c(S?"^(?:"+i.source+")":i,y),g=void 0===r?w:r>>>0;if(0===g)return[];if(0===a.length)return null===v(m,a)?[a]:[];for(var _=0,b=0,E=[];b{"use strict";var r,i=n(54635),o=n(59913),a=n(66213).f,u=n(9375),s=n(74170),c=n(17911),d=n(31591),l=n(41813),f=n(68546),p=o("".startsWith),h=o("".slice),y=Math.min,m=l("startsWith");i({target:"String",proto:!0,forced:!(!f&&!m&&(r=a(String.prototype,"startsWith"),r&&!r.writable)||m)},{startsWith:function(t){var e=s(d(this));c(t);var n=u(y(arguments.length>1?arguments[1]:void 0,e.length)),r=s(t);return p?p(e,r,n):h(e,n,n+r.length)===r}})},91652:(t,e,n)=>{n(74962);var r=n(54635),i=n(9334);r({target:"String",proto:!0,name:"trimEnd",forced:"".trimEnd!==i},{trimEnd:i})},86630:(t,e,n)=>{var r=n(54635),i=n(97746);r({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==i},{trimLeft:i})},74962:(t,e,n)=>{var r=n(54635),i=n(9334);r({target:"String",proto:!0,name:"trimEnd",forced:"".trimRight!==i},{trimRight:i})},94064:(t,e,n)=>{n(86630);var r=n(54635),i=n(97746);r({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==i},{trimStart:i})},25959:(t,e,n)=>{"use strict";var r=n(54635),i=n(76109).trim;r({target:"String",proto:!0,forced:n(41017)("trim")},{trim:function(){return i(this)}})},9190:(t,e,n)=>{n(91165)("asyncIterator")},69106:(t,e,n)=>{"use strict";var r=n(54635),i=n(32022),o=n(49425),a=n(59913),u=n(68546),s=n(12115),c=n(86263),d=n(38986),l=n(98511),f=n(27357),p=n(52546),h=n(58326),y=n(79127),m=n(74170),v=n(71111),g=n(13250),_=n(95932),b=n(92775),S=n(12098),w=n(31711),C=n(66213),E=n(43087),I=n(13330),P=n(23659),A=n(43068),O=n(27905),T=n(57186),x=n(17307),R=n(60232),k=n(30191),M=n(58855),N=n(91165),D=n(47498),L=n(27747),z=n(78045),j=n(55883).forEach,U=T("hidden"),F="Symbol",q="prototype",B=z.set,G=z.getterFor(F),V=Object[q],Y=i.Symbol,H=Y&&Y[q],W=i.TypeError,K=i.QObject,Z=C.f,$=E.f,J=S.f,Q=P.f,X=a([].push),tt=O("symbols"),et=O("op-symbols"),nt=O("wks"),rt=!K||!K[q]||!K[q].findChild,it=s&&d((function(){return 7!=g($({},"a",{get:function(){return $(this,"a",{value:7}).a}})).a}))?function(t,e,n){var r=Z(V,e);r&&delete V[e],$(t,e,n),r&&t!==V&&$(V,e,r)}:$,ot=function(t,e){var n=tt[t]=g(H);return B(n,{type:F,tag:t,description:e}),s||(n.description=e),n},at=function(t,e,n){t===V&&at(et,e,n),p(t);var r=y(e);return p(n),l(tt,r)?(n.enumerable?(l(t,U)&&t[U][r]&&(t[U][r]=!1),n=g(n,{enumerable:v(0,!1)})):(l(t,U)||$(t,U,v(1,{})),t[U][r]=!0),it(t,r,n)):$(t,r,n)},ut=function(t,e){p(t);var n=h(e),r=_(n).concat(lt(n));return j(r,(function(e){s&&!o(st,n,e)||at(t,e,n[e])})),t},st=function(t){var e=y(t),n=o(Q,this,e);return!(this===V&&l(tt,e)&&!l(et,e))&&(!(n||!l(this,e)||!l(tt,e)||l(this,U)&&this[U][e])||n)},ct=function(t,e){var n=h(t),r=y(e);if(n!==V||!l(tt,r)||l(et,r)){var i=Z(n,r);return!i||!l(tt,r)||l(n,U)&&n[U][r]||(i.enumerable=!0),i}},dt=function(t){var e=J(h(t)),n=[];return j(e,(function(t){l(tt,t)||l(x,t)||X(n,t)})),n},lt=function(t){var e=t===V,n=J(e?et:h(t)),r=[];return j(n,(function(t){!l(tt,t)||e&&!l(V,t)||X(r,tt[t])})),r};c||(A(H=(Y=function(){if(f(H,this))throw W("Symbol is not a constructor");var t=arguments.length&&void 0!==arguments[0]?m(arguments[0]):void 0,e=R(t),n=function(t){this===V&&o(n,et,t),l(this,U)&&l(this[U],e)&&(this[U][e]=!1),it(this,e,v(1,t))};return s&&rt&&it(V,e,{configurable:!0,set:n}),ot(e,t)})[q],"toString",(function(){return G(this).tag})),A(Y,"withoutSetter",(function(t){return ot(R(t),t)})),P.f=st,E.f=at,I.f=ut,C.f=ct,b.f=S.f=dt,w.f=lt,M.f=function(t){return ot(k(t),t)},s&&($(H,"description",{configurable:!0,get:function(){return G(this).description}}),u||A(V,"propertyIsEnumerable",st,{unsafe:!0}))),r({global:!0,constructor:!0,wrap:!0,forced:!c,sham:!c},{Symbol:Y}),j(_(nt),(function(t){N(t)})),r({target:F,stat:!0,forced:!c},{useSetter:function(){rt=!0},useSimple:function(){rt=!1}}),r({target:"Object",stat:!0,forced:!c,sham:!s},{create:function(t,e){return void 0===e?g(t):ut(g(t),e)},defineProperty:at,defineProperties:ut,getOwnPropertyDescriptor:ct}),r({target:"Object",stat:!0,forced:!c},{getOwnPropertyNames:dt}),D(),L(Y,F),x[U]=!0},70472:(t,e,n)=>{"use strict";var r=n(54635),i=n(12115),o=n(32022),a=n(59913),u=n(98511),s=n(34028),c=n(27357),d=n(74170),l=n(43087).f,f=n(74953),p=o.Symbol,h=p&&p.prototype;if(i&&s(p)&&(!("description"in h)||void 0!==p().description)){var y={},m=function(){var t=arguments.length<1||void 0===arguments[0]?void 0:d(arguments[0]),e=c(h,this)?new p(t):void 0===t?p():p(t);return""===t&&(y[e]=!0),e};f(m,p),m.prototype=h,h.constructor=m;var v="Symbol(test)"==String(p("test")),g=a(h.valueOf),_=a(h.toString),b=/^Symbol\((.*)\)[^)]+$/,S=a("".replace),w=a("".slice);l(h,"description",{configurable:!0,get:function(){var t=g(this);if(u(y,t))return"";var e=_(t),n=v?w(e,7,-1):S(e,b,"$1");return""===n?void 0:n}}),r({global:!0,constructor:!0,forced:!0},{Symbol:m})}},83038:(t,e,n)=>{var r=n(54635),i=n(83155),o=n(98511),a=n(74170),u=n(27905),s=n(55666),c=u("string-to-symbol-registry"),d=u("symbol-to-string-registry");r({target:"Symbol",stat:!0,forced:!s},{for:function(t){var e=a(t);if(o(c,e))return c[e];var n=i("Symbol")(e);return c[e]=n,d[n]=e,n}})},93270:(t,e,n)=>{n(91165)("iterator")},93942:(t,e,n)=>{n(69106),n(83038),n(84272),n(55205),n(17524)},84272:(t,e,n)=>{var r=n(54635),i=n(98511),o=n(24505),a=n(84160),u=n(27905),s=n(55666),c=u("symbol-to-string-registry");r({target:"Symbol",stat:!0,forced:!s},{keyFor:function(t){if(!o(t))throw TypeError(a(t)+" is not a symbol");if(i(c,t))return c[t]}})},8962:(t,e,n)=>{var r=n(91165),i=n(47498);r("toPrimitive"),i()},56019:(t,e,n)=>{"use strict";var r,i=n(32022),o=n(59913),a=n(3193),u=n(67023),s=n(69866),c=n(31858),d=n(51355),l=n(62713),f=n(78045).enforce,p=n(74112),h=!i.ActiveXObject&&"ActiveXObject"in i,y=function(t){return function(){return t(this,arguments.length?arguments[0]:void 0)}},m=s("WeakMap",y,c);if(p&&h){r=c.getConstructor(y,"WeakMap",!0),u.enable();var v=m.prototype,g=o(v.delete),_=o(v.has),b=o(v.get),S=o(v.set);a(v,{delete:function(t){if(d(t)&&!l(t)){var e=f(this);return e.frozen||(e.frozen=new r),g(this,t)||e.frozen.delete(t)}return g(this,t)},has:function(t){if(d(t)&&!l(t)){var e=f(this);return e.frozen||(e.frozen=new r),_(this,t)||e.frozen.has(t)}return _(this,t)},get:function(t){if(d(t)&&!l(t)){var e=f(this);return e.frozen||(e.frozen=new r),_(this,t)?b(this,t):e.frozen.get(t)}return b(this,t)},set:function(t,e){if(d(t)&&!l(t)){var n=f(this);n.frozen||(n.frozen=new r),_(this,t)?S(this,t,e):n.frozen.set(t,e)}else S(this,t,e);return this}})}},5963:(t,e,n)=>{n(56019)},71806:(t,e,n)=>{var r=n(32022),i=n(66910),o=n(73391),a=n(33609),u=n(22775),s=function(t){if(t&&t.forEach!==a)try{u(t,"forEach",a)}catch(e){t.forEach=a}};for(var c in i)i[c]&&s(r[c]&&r[c].prototype);s(o)},5193:(t,e,n)=>{var r=n(32022),i=n(66910),o=n(73391),a=n(38490),u=n(22775),s=n(30191),c=s("iterator"),d=s("toStringTag"),l=a.values,f=function(t,e){if(t){if(t[c]!==l)try{u(t,c,l)}catch(e){t[c]=l}if(t[d]||u(t,d,e),i[e])for(var n in a)if(t[n]!==a[n])try{u(t,n,a[n])}catch(e){t[n]=a[n]}}};for(var p in i)f(r[p]&&r[p].prototype,p);f(o,"DOMTokenList")},72031:(t,e,n)=>{"use strict";var r=n(54635),i=n(49425);r({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return i(URL.prototype.toString,this)}})}},e={};function n(r){var i=e[r];if(void 0!==i)return i.exports;var o=e[r]={id:r,loaded:!1,exports:{}};return t[r].call(o.exports,o,o.exports,n),o.loaded=!0,o.exports}n.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var r in e)n.o(e,r)&&!n.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.nmd=t=>(t.paths=[],t.children||(t.children=[]),t);var r={};return(()=>{"use strict";n.r(r),n.d(r,{createCheckoutButtonInitializer:()=>Wu,createTimeout:()=>e.createTimeout});var t={};n.r(t),n.d(t,{createApplePayButtonStrategy:()=>au,createBoltButtonStrategy:()=>yu,createPayPalCommerceAlternativeMethodsButtonStrategy:()=>ju,createPayPalCommerceButtonStrategy:()=>ku,createPayPalCommerceCreditButtonStrategy:()=>Nu,createPayPalCommerceVenmoButtonStrategy:()=>Lu,createPaypalExpressButtonStrategy:()=>Hu});var e=n(14121),i=n(13751),o=n(61699),a=n(45346);const u=function(t){function e(e){var n,r,i=this.constructor,o=t.call(this,e||"An unexpected error has occurred.")||this;return o.name="StandardError",o.type="standard",n=o,r=i.prototype,Object.setPrototypeOf?Object.setPrototypeOf(n,r):n.__proto__=r,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(o,i):o.stack=new Error(o.message).stack,o}return(0,o.__extends)(e,t),e}(Error);var s={body:{},headers:{},status:0};const c=function(t){function e(e,n){var r=void 0===n?{}:n,i=r.message,o=r.errors,a=this,u=e||s,c=u.body,d=u.headers,l=u.status;return(a=t.call(this,i||"An unexpected error has occurred.")||this).name="RequestError",a.type="request",a.body=c,a.headers=d,a.status=l,a.errors=o||[],a}return(0,o.__extends)(e,t),e}(u),d=function(t){function e(e){var n=t.call(this,e,{message:"There is a problem processing your payment. Please try again later."})||this;return n.name="PaymentMethodInvalidError",n.type="payment_method_invalid",n}return(0,o.__extends)(e,t),e}(c);n(34745),n(28101);const l=function(t){function e(e){var n,r,i=this.constructor,o=t.call(this,e||"An unexpected error has occurred.")||this;return o.name="StandardError",o.type="standard",n=o,r=i.prototype,Object.setPrototypeOf?Object.setPrototypeOf(n,r):n.__proto__=r,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(o,i):o.stack=new Error(o.message).stack,o}return(0,o.__extends)(e,t),e}(Error);var f={body:{},headers:{},status:0};const p=function(t){function e(e,n){var r=void 0===n?{}:n,i=r.message,o=r.errors,a=this,u=e||f,s=u.body,c=u.headers,d=u.status;return(a=t.call(this,i||"An unexpected error has occurred.")||this).name="RequestError",a.type="request",a.body=s,a.headers=c,a.status=d,a.errors=o||[],a}return(0,o.__extends)(e,t),e}(l),h=function(t){function e(e,n){var r=t.call(this,e,{message:n||"An unexpected error has occurred. The checkout process cannot continue as a result."})||this;return r.name="UnrecoverableError",r.type="unrecoverable",r}return(0,o.__extends)(e,t),e}(p);n(93942),n(70472),n(93270),n(38490),n(40737),n(10951),n(34500),n(5193);var y=n(87275);function m(t){return t.reduce((function(t,e){return e?(0,o.__spreadArrays)(t,[e]):t}),[]).join(" ")}function v(t,e){var n=t.body.errors,r=void 0===n?[]:n;return new p(t,{message:g(r)||e,errors:r})}function g(t){if(Array.isArray(t))return t.reduce((function(t,e){return e&&e.message?(0,o.__spreadArrays)(t,[e.message]):t}),[]).join(" ")}n(64668),n(95412);const _=function(t){function e(e){var n=t.call(this,e,{message:"The request has timed out or aborted."})||this;return n.name="TimeoutError",n.type="timeout",n}return(0,o.__extends)(e,t),e}(p);function b(t){return b="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},b(t)}const S=function(){function t(){this._factoryMethods={},this.register("default",(function(t,e){return new p(t,{message:e})})),this.register("internal",(function(t,e){return function(t,e){var n=t.body,r=n.errors,i=void 0===r?[]:r;return new p(t,{message:m(i)||n.detail||n.title||e,errors:i.length?i.map((function(t){return{code:n.type,message:t}})):[{code:n.type,message:n.detail||n.title}]})}(t,e)})),this.register("storefront",(function(t,e){return function(t,e){var n=t.body;return new p(t,{message:e||n.detail||n.title,errors:[{code:n.code||n.type,message:n.detail||n.title}]})}(t,e)})),this.register("payment",(function(t,e){return v(t,e)})),this.register("timeout",(function(t){return new _(t)}))}return t.prototype.register=function(t,e){this._factoryMethods[t]=e},t.prototype.createError=function(t,e){return(this._factoryMethods[this._getType(t)]||this._factoryMethods.default)(t,e)},t.prototype._getType=function(t){if(0===t.status)return"timeout";if(this._isStorefrontErrorResponseBody(t.body))return"storefront";if(this._isInternalErrorResponseBody(t.body)){var e=(0,y.last)(t.body.type.split("/"));return e&&this._factoryMethods[e]?e:"internal"}var n=(0,y.last)(t.body&&t.body.errors);return n&&n.code&&this._factoryMethods[n.code]?n.code:"payment"},t.prototype._isStorefrontErrorResponseBody=function(t){var e=t;return!this._isInternalErrorResponseBody(t)&&"string"==typeof e.title&&"string"==typeof e.type&&"number"==typeof e.status&&"string"==typeof e.detail},t.prototype._isInternalErrorResponseBody=function(t){var e=t;return"object"===b(e.errors)&&"string"==typeof e.title&&"string"==typeof e.type&&"number"==typeof e.status},t}();var w,C,E,I,P=n(73531),A=n(63660);function O(t){return O="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},O(t)}function T(t,e){return Array.isArray(t)?t.map((function(t){return T(t,e)})):(0,y.isPlainObject)(t)?(0,y.transform)((0,y.omitBy)(t,e),(function(t,n,r){t[r]=T(n,e)}),{}):t}function x(t,e){return function(t){return t.type===C.ClearError}(e)?T(t,(function(t){return t===e.payload})):t}function R(t){return R="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},R(t)}function k(t,e,n){return t===e||(t&&e&&"object"===R(t)&&"object"===R(e)?Array.isArray(t)&&Array.isArray(e)?function(t,e,n){if(t.length!==e.length)return!1;for(var r=0,i=t.length;r-1){var i=n[r];return r>0&&(n.splice(r,1),n.unshift(i)),i.value}return Nn}return{get:r,put:function(e,i){r(e)===Nn&&(n.unshift({key:e,value:i}),n.length>t&&n.pop())},getEntries:function(){return n},clear:function(){n=[]}}}(s,d);function f(){var e=l.get(arguments);if(e===Nn){if(e=t.apply(null,arguments),c){var n=l.getEntries().find((function(t){return c(t.value,e)}));n&&(e=n.value)}l.put(arguments,e)}return e}return f.clearCache=function(){return l.clear()},f}function zn(t){return zn="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},zn(t)}function jn(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r0}})),H=Un(U,(function(t){return function(e){return!(!e||!e.nonce)||t()===Vn||t()===Yn}})),(0,Rn.qe)((function(t,e){return{getPaymentId:z({checkout:t,order:e}),getPaymentIdOrThrow:j({checkout:t,order:e}),getPaymentStatus:U({checkout:t,order:e}),getPaymentStatusOrThrow:F({checkout:t,order:e}),getPaymentToken:q({checkout:t,order:e}),getPaymentTokenOrThrow:B({checkout:t,order:e}),getPaymentRedirectUrl:G({checkout:t,order:e}),getPaymentRedirectUrlOrThrow:V({checkout:t,order:e}),isPaymentDataRequired:Y({checkout:t,order:e}),isPaymentDataSubmitted:H({checkout:t,order:e})}}))),Et=function(){var t=Un((function(t){return t.errors.applyError}),(function(t){return function(){return t}})),e=Un((function(t){return!!t.statuses.isApplying}),(function(t){return function(){return t}}));return(0,Rn.qe)((function(n){return void 0===n&&(n=Kn),{getApplyError:t(n),isApplying:e(n)}}))}(),Pt=function(){var t=Un((function(t){return t.errors.updateError}),(function(t){return function(){return t}})),e=Un((function(t){return!!t.statuses.isUpdating}),(function(t){return function(){return t}}));return(0,Rn.qe)((function(n){return void 0===n&&(n=Sn),{getUpdateError:t(n),isUpdating:e(n)}}))}(),At=(K=Un((function(t){return t.data}),(function(t){return function(){return t}})),Z=Un((function(t){return t.errors.sendError}),(function(t){return function(){return t}})),$=Un((function(t){return!!t.statuses.isSending}),(function(t){return function(){return t}})),(0,Rn.qe)((function(t){return void 0===t&&(t=ln),{getEmail:K(t),getSendError:Z(t),isSending:$(t)}}))),Ot=function(){var t=Un((function(t){return t.data}),(function(t){return function(){return t}})),e=Un((function(t){return t.data}),(function(t){return function(e){return null==t?void 0:t.find((function(t){return t.region===e}))}})),n=Un((function(t){return t.errors.loadError}),(function(t){return function(){return t}})),r=Un((function(t){return t.statuses.isLoading}),(function(t){return function(){return!!t}}));return(0,Rn.qe)((function(i){return void 0===i&&(i=zt),{getExtensions:t(i),getExtensionByRegion:e(i),getLoadError:n(i),isLoading:r(i)}}))}();return function(t,e){void 0===e&&(e={});var n=J(t.billingAddress),r=Q(t.cart),i=tt(t.checkoutButton),o=nt(t.countries),a=rt(t.coupons),u=it(t.customer),s=ot(t.customerStrategies),c=Ot(t.extensions),d=ct(t.formFields),l=at(t.giftCertificates),f=ut(t.instruments),p=wt(t.orderBillingAddress),h=dt(t.paymentMethods),y=lt(t.paymentStrategies),m=ft(t.pickupOptions),v=ht(t.remoteCheckout),g=yt(t.consignments),_=mt(t.shippingCountries),b=vt(t.shippingStrategies),S=Pt(t.subscriptions),w=Et(t.storeCredit),C=At(t.signInEmail),E=gt(t.consignments,r),I=bt(t.checkout,n,r,E,a,u,l),P=St(t.order,p,a),A=Ct(I,P),O={billingAddress:n,cart:r,checkout:I,checkoutButton:i,config:et(t.config,t.formFields),consignments:E,countries:o,coupons:a,customer:u,customerStrategies:s,extensions:c,form:d,giftCertificates:l,instruments:f,order:P,orderBillingAddress:p,payment:A,paymentMethods:h,paymentStrategies:y,pickupOptions:m,remoteCheckout:v,shippingAddress:g,shippingCountries:_,shippingStrategies:b,signInEmail:C,subscriptions:S,storeCredit:w};return e.shouldWarnMutation?function(t){return Object.keys(t).reduce((function(e,n){return e[n]=Bn(t[n]),e}),{})}(O):O}}function $n(t,e){void 0===t&&(t={});var n,r,i=(n=new S,["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((function(t){n.register(t,(function(t,e){return new h(t,e)}))})),n.register("invalid_payment_provider",(function(t){return new d(t)})),n.register("payment_config_not_found",(function(t){return new d(t)})),r=n,function(t){return(0,P.D)(t).pipe((0,A.K)((function(t){if(t instanceof Error||t.payload instanceof Error)throw t;if((n=t.payload)&&"object"===O(n)&&["body","headers","status","statusText"].every((function(t){return Object.prototype.hasOwnProperty.call(n,t)}))){var e=t.payload.body&&t.payload.body.detail;throw(0,o.__assign)((0,o.__assign)({},t),{payload:r.createError(t.payload,e)})}var n;throw t})))}),u=Zn();return(0,a.Mg)((0,a.UY)({billingAddress:L,cart:K,checkout:Pn,checkoutButton:rt,config:ct,consignments:je,countries:Zt,coupons:ht,customer:Pt,customerStrategies:kt,extensions:jt,formFields:Vt,giftCertificates:bt,instruments:Oe,orderBillingAddress:se,order:te,payment:de,paymentMethods:ye,paymentStrategies:we,pickupOptions:We,remoteCheckout:Ne,shippingCountries:Xe,shippingStrategies:an,signInEmail:fn,subscriptions:wn,storeCredit:vn}),t,(0,o.__assign)({actionTransformer:i,stateTransformer:function(t){return u(t)}},e))}var Jn=n(64074),Qn=(n(5963),n(7263));function Xn(t,e,n){var r=new WeakMap;function i(t){var n=this;return function(){for(var i,a=[],u=0;u=400&&t.status<500)throw new Cr(t);throw t}))},t.prototype.updateCheckout=function(t,e,n){var r=void 0===n?{}:n,i=r.params,a=(void 0===i?{}:i).include,u=r.timeout,s="/api/storefront/checkout/"+t,c=(0,o.__assign)({Accept:nr.JsonV1},ir);return this._requestSender.put(s,{params:{include:Sr(wr,a)},body:e,headers:c,timeout:u})},t}();n(16516);const Ir=function(){function t(){}return t.prototype.isEqual=function(t,e){return(0,y.isEqual)(this._normalize(t),this._normalize(e))},t.prototype._normalize=function(t){return{cartAmount:t.cartAmount,currency:t.currency,id:t.id,lineItems:{digitalItems:t.lineItems.digitalItems.slice().sort((function(t,e){return(""+t.productId+t.variantId).localeCompare(""+e.productId+e.variantId)})).map((function(t){return{extendedSalePrice:t.extendedSalePrice,productId:t.productId,quantity:t.quantity,variantId:t.variantId}})),giftCertificates:t.lineItems.giftCertificates.slice().sort((function(t,e){return(""+t.id).localeCompare(""+e.id)})).map((function(t){return{amount:t.amount,recipient:t.recipient}})),physicalItems:t.lineItems.physicalItems.slice().sort((function(t,e){return(""+t.productId+t.variantId).localeCompare(""+e.productId+e.variantId)})).map((function(t){return{extendedSalePrice:t.extendedSalePrice,productId:t.productId,quantity:t.quantity,variantId:t.variantId,giftWrapping:t.giftWrapping}}))}}},t}(),Pr=function(t){function e(e,n){var r=t.call(this,"An update to your shopping cart has been detected and your available shipping costs have been updated.")||this;return r.name="CartChangedError",r.type="cart_changed",r.data={previous:e,updated:n},r}return(0,o.__extends)(e,t),e}(l),Ar=function(){function t(t){this._checkoutRequestSender=t}return t.prototype.validate=function(t,e){var n=this;if(!t)throw new kn(xn.MissingCheckout);return this._checkoutRequestSender.loadCheckout(t.id,e).then((function(e){var r=new Ir;if(!(t.outstandingBalance===e.body.outstandingBalance&&n._compareCoupons(t.coupons,e.body.coupons)&&n._compareGiftCertificates(t.giftCertificates,e.body.giftCertificates)&&r.isEqual(t.cart,e.body.cart)))throw new Pr(n._getComparableCheckout(t),n._getComparableCheckout(e.body))}))},t.prototype._compareCoupons=function(t,e){return(0,y.isEqual)((0,y.map)(t,"code"),(0,y.map)(e,"code"))},t.prototype._compareGiftCertificates=function(t,e){return(0,y.isEqual)((0,y.map)(t,"code"),(0,y.map)(e,"code"))},t.prototype._getComparableCheckout=function(t){var e=t.cart,n=t.coupons,r=t.giftCertificates,i=t.outstandingBalance;return{cart:{cartAmount:e.cartAmount,currency:e.currency,lineItems:e.lineItems},coupons:n,giftCertificates:r,outstandingBalance:i}},t}(),Or=function(){function t(t){this._configRequestSender=t}return t.prototype.loadConfig=function(t){var e=this;return Jn.y.create((function(n){n.next((0,a.PH)(Q.LoadConfigRequested)),e._configRequestSender.loadConfig(t).then((function(t){n.next((0,a.PH)(Q.LoadConfigSucceeded,t.body)),n.complete()})).catch((function(t){n.error((0,a.bR)(Q.LoadConfigFailed,t))}))}))},(0,o.__decorate)([Xn],t.prototype,"loadConfig",null),t}(),Tr=function(){function t(t){this._requestSender=t}return t.prototype.loadConfig=function(t){var e=void 0===t?{}:t,n=e.timeout,r=e.params;return this._requestSender.get("/api/storefront/checkout-settings",{timeout:n,headers:(0,o.__assign)({Accept:nr.JsonV1,"X-API-INTERNAL":rr},ir),params:r}).catch((function(t){if(t.status>=400&&t.status<500)throw new Cr(t);throw t}))},t}();var xr=n(64440);function Rr(t){return Rr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Rr(t)}function kr(t){var e=t;return"object"===Rr(e)&&"object"===Rr(e.payload)&&"string"==typeof e.payload.token}const Mr=function(){function t(t,e,n){this._customerRequestSender=t,this._checkoutActionCreator=e,this._spamProtectionActionCreator=n}return t.prototype.createCustomer=function(t,e){var n=this;return function(r){var i=r.getState().config.getStoreConfigOrThrow().checkoutSettings.isStorefrontSpamProtectionEnabled,u=function(i){return(0,P.D)(n._customerRequestSender.createAccount((0,o.__assign)((0,o.__assign)({},t),{token:i}),e)).pipe((0,xr.w)((function(){return(0,sr.z)(n._checkoutActionCreator.loadCurrentCheckout(e)(r),(0,cr.of)((0,a.PH)(gt.CreateCustomerSucceeded)))})))};return(0,sr.z)((0,cr.of)((0,a.PH)(gt.CreateCustomerRequested)),i?(0,P.D)(n._spamProtectionActionCreator.execute()(r)).pipe((0,xr.w)((function(t){var e;return kr(t)?(0,sr.z)((0,cr.of)(t),u(null===(e=t.payload)||void 0===e?void 0:e.token)):(0,cr.of)(t)}))):u()).pipe((0,A.K)((function(t){return pr(gt.CreateCustomerFailed,t)})))}},t.prototype.createAddress=function(t,e){var n=this;return(0,sr.z)((0,cr.of)((0,a.PH)(gt.CreateCustomerAddressRequested)),(0,dr.P)((function(){return(0,o.__awaiter)(n,void 0,void 0,(function(){var n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._customerRequestSender.createAddress(t,e)];case 1:return n=r.sent().body,[2,(0,a.PH)(gt.CreateCustomerAddressSucceeded,n)]}}))}))}))).pipe((0,A.K)((function(t){return pr(gt.CreateCustomerAddressFailed,t)})))},t.prototype.signInCustomer=function(t,e){var n=this;return function(r){return(0,sr.z)((0,cr.of)((0,a.PH)(gt.SignInCustomerRequested)),(0,P.D)(n._customerRequestSender.signInCustomer(t,e)).pipe((0,xr.w)((function(t){var i=t.body;return(0,sr.z)(n._checkoutActionCreator.loadCurrentCheckout(e)(r),(0,cr.of)((0,a.PH)(gt.SignInCustomerSucceeded,i.data)))})))).pipe((0,A.K)((function(t){return pr(gt.SignInCustomerFailed,t)})))}},t.prototype.signOutCustomer=function(t){var e=this;return function(n){return(0,sr.z)((0,cr.of)((0,a.PH)(gt.SignOutCustomerRequested)),(0,P.D)(e._customerRequestSender.signOutCustomer(t)).pipe((0,xr.w)((function(r){var i=r.body;return(0,sr.z)(e._checkoutActionCreator.loadCurrentCheckout(t)(n),(0,cr.of)((0,a.PH)(gt.SignOutCustomerSucceeded,i.data)))})))).pipe((0,A.K)((function(t){return pr(gt.SignOutCustomerFailed,t)})))}},t}(),Nr=function(){function t(t){this._requestSender=t}return t.prototype.createAccount=function(t,e){var n=(void 0===e?{}:e).timeout;return this._requestSender.post("/api/storefront/customer",{timeout:n,headers:ir,body:t})},t.prototype.createAddress=function(t,e){var n=(void 0===e?{}:e).timeout;return this._requestSender.post("/api/storefront/customer-address",{timeout:n,headers:ir,body:t})},t.prototype.signInCustomer=function(t,e){var n=(void 0===e?{}:e).timeout;return this._requestSender.post("/internalapi/v1/checkout/customer",{timeout:n,headers:ir,body:t})},t.prototype.signOutCustomer=function(t){var e=(void 0===t?{}:t).timeout;return this._requestSender.delete("/internalapi/v1/checkout/customer",{timeout:e,headers:ir})},t}(),Dr=function(){function t(t){this._formFieldsRequestSender=t}return t.prototype.loadFormFields=function(t){var e=this;return(0,sr.z)((0,cr.of)((0,a.PH)(Lt.LoadFormFieldsRequested)),(0,dr.P)((function(){return(0,o.__awaiter)(e,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return[4,this._formFieldsRequestSender.loadFields(t)];case 1:return e=n.sent().body,[2,(0,a.PH)(Lt.LoadFormFieldsSucceeded,e)]}}))}))}))).pipe((0,A.K)((function(t){return pr(Lt.LoadFormFieldsFailed,t)})))},(0,o.__decorate)([Xn],t.prototype,"loadFormFields",null),t}(),Lr=function(){function t(t){this._requestSender=t}return t.prototype.loadFields=function(t){var e=(void 0===t?{}:t).timeout;return this._requestSender.get("/api/storefront/form-fields",{timeout:e,headers:(0,o.__assign)({Accept:nr.JsonV1,"X-API-INTERNAL":rr},ir)})},t}();n(95040);const zr=function(t){var e=this,n=new Promise((function(t,n){e.cancel=n}));this.promise=Promise.race([t,n])},jr=function(t){function e(e){var n=t.call(this,e||"Unable to proceed because the required element is unexpectedly detached from the page.")||this;return n.name="UnexpectedDetachmentError",n.type="unexpected_detachment",n}return(0,o.__extends)(e,t),e}(l),Ur=function(){function t(t){this._mutationObserver=t}return t.prototype.ensurePresence=function(t,e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r,i,a;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:n=new zr(e),(r=this._mutationObserver.create((function(e){e.forEach((function(e){0!==Array.from(e.removedNodes).filter((function(e){return t.some((function(t){return e===t||e.contains(t)}))})).length&&n.cancel(new jr)}))}))).observe(document.body,{childList:!0,subtree:!0}),o.label=1;case 1:return o.trys.push([1,3,,4]),[4,n.promise];case 2:return i=o.sent(),r.disconnect(),[2,i];case 3:throw a=o.sent(),r.disconnect(),a;case 4:return[2]}}))}))},t}();var Fr=function(){function t(t){void 0===t&&(t=window),this._window=t}return t.prototype.create=function(t){return new this._window.MutationObserver(t)},t}(),qr=n(55343),Br=n(20239),Gr=n(92160),Vr=n(31407);n(57347);const Yr=function(t){function e(e){var n=t.call(this,e||"Invalid arguments have been provided.")||this;return n.name="InvalidArgumentError",n.type="invalid_argument",n}return(0,o.__extends)(e,t),e}(l);function Hr(t){if(!/^(https?:)?\/\//.test(t))throw new Yr("The provided URL must be absolute.");var e=document.createElement("a");e.href=t;var n=e.port&&-1!==t.indexOf(e.hostname+":"+e.port)?e.port:"";return{hash:e.hash,hostname:e.hostname,href:e.href,origin:e.protocol+"//"+e.hostname+(n?":"+n:""),pathname:e.pathname,port:n,protocol:e.protocol,search:e.search}}function Wr(t,e){return t.type===e}const Kr=function(){function t(t,e){this._targetWindow=e,this._targetOrigin="*"===t?"*":Hr(t).origin}return t.prototype.post=function(t,e){var n=this,r=this._targetWindow;if(window!==r){if(!r)throw new Error("Unable to post message because target window is not set.");var i=e&&(0,qr.R)(window,"message").pipe((0,Br.h)((function(t){return t.origin===n._targetOrigin&&Wr(t.data,t.data.type)&&-1!==[e.successType,e.errorType].indexOf(t.data.type)})),(0,Gr.U)((function(t){if(e.errorType===t.data.type)throw t.data;return t.data})),(0,Vr.q)(1)).toPromise();return r.postMessage(t,this._targetOrigin),i}},t.prototype.setTarget=function(t){this._targetWindow=t},t}();n(19926);const Zr=function(t,e,n){return e&&n?$r(0,e,n):function(t){var e=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return(0,o.__extends)(e,t),e}(t);return Object.getOwnPropertyNames(t.prototype).forEach((function(n){var r=Object.getOwnPropertyDescriptor(t.prototype,n);r&&"constructor"!==n&&Object.defineProperty(e.prototype,n,$r(t.prototype,n,r))})),e}(t)};function $r(t,e,n){if("function"!=typeof n.value)return n;var r=n.value;return{get:function(){var t=r.bind(this);return Object.defineProperty(this,e,(0,o.__assign)((0,o.__assign)({},n),{value:t})),t},set:function(t){r=t}}}const Jr=function(){function t(t){var e;this._sourceOrigins=[Hr(t).origin,(e=Hr(t),Hr(0===e.hostname.indexOf("www")?e.href:e.href.replace(e.hostname,"www."+e.hostname))).origin],this._isListening=!1,this._listeners={}}return t.prototype.listen=function(){this._isListening||(this._isListening=!0,window.addEventListener("message",this._handleMessage))},t.prototype.stopListen=function(){this._isListening&&(this._isListening=!1,window.removeEventListener("message",this._handleMessage))},t.prototype.addListener=function(t,e){var n=this._listeners[t];n||(this._listeners[t]=n=[]),-1===n.indexOf(e)&&n.push(e)},t.prototype.removeListener=function(t,e){var n=this._listeners[t];if(n){var r=n.indexOf(e);r>=0&&n.splice(r,1)}},t.prototype.trigger=function(t){var e=this._listeners[t.type];e&&e.forEach((function(e){return e(t)}))},t.prototype._handleMessage=function(t){-1!==this._sourceOrigins.indexOf(t.origin)&&Wr(t.data,t.data.type)&&this.trigger(t.data)},(0,o.__decorate)([Zr],t.prototype,"_handleMessage",null),t}(),Qr=function(t){function e(){var e=t.call(this,"You haven't complete our spam protection challenge. Please try again.")||this;return e.name="SpamProtectionChallengeNotCompletedError",e.type="spam_protection_challenge_not_completed",e}return(0,o.__extends)(e,t),e}(l),Xr=function(t){function e(){var e=t.call(this,"Please complete our human verification challenge and try again.")||this;return e.name="CardingProtectionChallengeNotCompletedError",e.type="carding_protection_challenge_not_completed",e}return(0,o.__extends)(e,t),e}(l),ti=function(t){function e(){var e=t.call(this,"We were not able to verify that you are not a robot. Please try again.")||this;return e.name="CardingProtectionFailedError",e.type="carding_protection_failed",e}return(0,o.__extends)(e,t),e}(l),ei=function(){function t(t){this._googleRecaptcha=t}return t.prototype.handle=function(t,e){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(n){return"string"==typeof t?[2,this.handleWithRecaptchaSitekey(t,e)]:[2,this.handleWithPaymentHumanVerificationRequestError(t)]}))}))},t.prototype.handleWithPaymentHumanVerificationRequestError=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(e){switch(e.label){case 0:if(!this._isPaymentHumanVerificationRequest(t))throw t;return[4,this._initialize(t.body.additional_action_required.data.key)];case 1:return e.sent(),[2,this._performRecaptcha()]}}))}))},t.prototype.handleWithRecaptchaSitekey=function(t,e){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if("recaptcha_v2"!==t)throw Error("Human verification method is not supported.");if(!e)throw Error("Recaptcha site key is missing.");return[4,this._initialize(e)];case 1:return n.sent(),[2,this._performRecaptcha()]}}))}))},t.prototype._performRecaptcha=function(){var t=this;return this._googleRecaptcha.execute().pipe((0,Vr.q)(1)).pipe((0,xr.w)((function(e){var n=e.error,r=e.token;return(0,o.__awaiter)(t,void 0,void 0,(function(){return(0,o.__generator)(this,(function(t){if(n instanceof Qr)throw new Xr;if(n||!r)throw new ti;return[2,{type:"recaptcha_v2_verification",data:{human_verification_token:r}}]}))}))}))).toPromise()},t.prototype._initialize=function(t){var e="cardingProtectionContainer",n=document.getElementById(e);return n&&n.parentNode&&n.parentNode.removeChild(n),(n=document.createElement("div")).setAttribute("id",e),document.body.appendChild(n),this._googleRecaptcha.load(e,t)},t.prototype._isPaymentHumanVerificationRequest=function(t){var e=t.body||{},n=e.additional_action_required;return"additional_action_required"===e.status&&n&&"recaptcha_v2_verification"===n.type},t}();var ni,ri=n(99357),ii=n(62156),oi=n(5026);!function(t){t[t.CheckoutButtonNotInitialized=0]="CheckoutButtonNotInitialized",t[t.CustomerNotInitialized=1]="CustomerNotInitialized",t[t.PaymentNotInitialized=2]="PaymentNotInitialized",t[t.ShippingNotInitialized=3]="ShippingNotInitialized",t[t.SpamProtectionNotInitialized=4]="SpamProtectionNotInitialized"}(ni||(ni={}));const ai=function(t){function e(e){var n=t.call(this,function(t){switch(t){case ni.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case ni.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case ni.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case ni.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;return n.subtype=e,n.name="NotInitializedError",n.type="not_initialized",n}return(0,o.__extends)(e,t),e}(l),ui=function(t){function e(){var e=t.call(this,"We were not able to complete your spam protection verification. Please try again.")||this;return e.name="SpamProtectionFailedError",e.type="spam_protection_failed",e}return(0,o.__extends)(e,t),e}(l),si=function(t){function e(){var e=t.call(this,"Spam protection is not loaded. Please try again.")||this;return e.name="SpamProtectionNotLoadedError",e.type="spam_protection_failed",e}return(0,o.__extends)(e,t),e}(l),ci=function(){function t(t,e){var n=this;this.googleRecaptchaScriptLoader=t,this.mutationObserverFactory=e,this._memoized=(0,Rn.HP)((function(t,e,r){var i=new ri.xQ;if(!r)throw new Error;return n._widgetId=t.render(r.id,{sitekey:e,size:"invisible",callback:function(){i.next({token:t.getResponse(n._widgetId)}),t.reset(n._widgetId)},"error-callback":function(){i.next({error:new ui})}}),i}),{isEqual:function(t,e){return t===e}})}return t.prototype.load=function(t,e){var n=this;return this.googleRecaptchaScriptLoader.load().then((function(r){r&&(n._event$=n._memoized(r,e,document.getElementById(t)),n._recaptcha=r)}))},t.prototype.execute=function(){var t=this;return(0,dr.P)((function(){var e=t._event$,n=t._recaptcha;if(!e||!n)throw new ai(ni.SpamProtectionNotInitialized);return(0,dr.P)((function(){var t=document.querySelector('iframe[src*="bframe"]');return t?(0,cr.of)(t):(0,fr._)(new si)})).pipe((0,ii.a)((function(t){return t.pipe((0,oi.g)(250),(0,xr.w)((function(t,e){return e<28?(0,cr.of)(t):(0,fr._)(t)})))})),(0,xr.w)((function(r){return t._watchRecaptchaChallengeWindow(e,r),n.execute(t._widgetId),e})),(0,A.K)((function(t){return(0,cr.of)({error:t})})))}))},t.prototype._watchRecaptchaChallengeWindow=function(t,e){var n=e.parentElement;if(!n)throw new si;var r=n.parentElement;if(!r)throw new si;this.mutationObserverFactory.create((function(){"hidden"===r.style.visibility&&t.next({error:new Qr})})).observe(r,{attributes:!0,attributeFilter:["style"]})},t}();n(83823);const di=function(){function t(t,e){void 0===e&&(e=window),this._scriptLoader=t,this._window=e}return t.prototype.load=function(){return this._loadPromise||(this._loadPromise=this._loadScript()),this._loadPromise},t.prototype._loadScript=function(){var t=this,e="initRecaptcha",n=["onload="+e,"render=explicit"].join("&");return new Promise((function(r,i){t._window[e]=function(){return r(t._window.grecaptcha)},t._scriptLoader.loadScript("//www.google.com/recaptcha/api.js?"+n).catch((function(e){t._loadPromise=void 0,i(e)}))}))},t}();function li(t){return new ci(new di(t),new Fr)}const fi=function(t){function e(e){var n=t.call(this,e||"Unable to proceed due to invalid configuration provided for the hosted payment form.")||this;return n.name="InvalidHostedFormConfigError",n.type="invalid_hosted_form_config",n}return(0,o.__extends)(e,t),e}(l),pi=function(t){function e(e){var n=t.call(this,e||"Unable to proceed due to an unknown error with the hosted payment form.")||this;return n.name="InvalidHostedFormError",n.type="invalid_hosted_form",n}return(0,o.__extends)(e,t),e}(l),hi=function(t){function e(e){var n=t.call(this,(0,o.__spreadArrays)(["Unable to proceed due to invalid user input values"],(0,y.flatMap)((0,y.values)(e),(function(t){return(0,y.map)(t,(function(t){return t.message}))}))).join(". "))||this;return n.errors=e,n.name="InvalidHostedFormValueError",n.type="invalid_hosted_form_value",n}return(0,o.__extends)(e,t),e}(l);var yi,mi;!function(t){t.AttachRequested="HOSTED_FIELD:ATTACH_REQUESTED",t.SubmitRequested="HOSTED_FIELD:SUBMITTED_REQUESTED",t.ValidateRequested="HOSTED_FIELD:VALIDATE_REQUESTED"}(yi||(yi={})),function(t){t.AttachSucceeded="HOSTED_INPUT:ATTACH_SUCCEEDED",t.AttachFailed="HOSTED_INPUT:ATTACH_FAILED",t.BinChanged="HOSTED_INPUT:BIN_CHANGED",t.Blurred="HOSTED_INPUT:BLURRED",t.Changed="HOSTED_INPUT:CHANGED",t.CardTypeChanged="HOSTED_INPUT:CARD_TYPE_CHANGED",t.Entered="HOSTED_INPUT:ENTERED",t.Focused="HOSTED_INPUT:FOCUSED",t.SubmitSucceeded="HOSTED_INPUT:SUBMIT_SUCCEEDED",t.SubmitFailed="HOSTED_INPUT:SUBMIT_FAILED",t.Validated="HOSTED_INPUT:VALIDATED"}(mi||(mi={}));const vi=function(){function t(t,e,n,r,i,o,a,u,s){this._type=t,this._containerId=e,this._placeholder=n,this._accessibilityLabel=r,this._styles=i,this._eventPoster=o,this._eventListener=a,this._detachmentObserver=u,this._cardInstrument=s,this._iframe=document.createElement("iframe"),this._iframe.src="/checkout/payment/hosted-field?version=1.398.1",this._iframe.style.border="none",this._iframe.style.height="100%",this._iframe.style.overflow="hidden",this._iframe.style.width="100%"}return t.prototype.getType=function(){return this._type},t.prototype.attach=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,e,n=this;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:if(!(t=document.getElementById(this._containerId)))throw new fi("Unable to proceed because the provided container ID is not valid.");return t.appendChild(this._iframe),this._eventListener.listen(),e=(0,qr.R)(this._iframe,"load").pipe((0,xr.w)((function(t){var e=t.target;return(0,o.__awaiter)(n,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if(!(t=e&&e.contentWindow))throw new Error("The content window of the iframe cannot be accessed.");return this._eventPoster.setTarget(t),[4,this._eventPoster.post({type:yi.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:mi.AttachSucceeded,errorType:mi.AttachFailed})];case 1:return n.sent(),[2]}}))}))})),(0,Vr.q)(1)).toPromise(),[4,this._detachmentObserver.ensurePresence([this._iframe],e)];case 1:return r.sent(),[2]}}))}))},t.prototype.detach=function(){this._iframe.parentElement&&(this._iframe.parentElement.removeChild(this._iframe),this._eventListener.stopListen())},t.prototype.submitForm=function(t,e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),n=this._eventPoster.post({type:yi.SubmitRequested,payload:{fields:t,data:e}},{successType:mi.SubmitSucceeded,errorType:mi.SubmitFailed}),[4,this._detachmentObserver.ensurePresence([this._iframe],n)];case 1:return[2,i.sent()];case 2:if(r=i.sent(),this._isSubmitErrorEvent(r)){if("hosted_form_error"===r.payload.error.code)throw new pi(r.payload.error.message);if(r.payload.response)throw v(r.payload.response);throw new Error(r.payload.error.message)}throw r;case 3:return[2]}}))}))},t.prototype.validateForm=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return t=this._eventPoster.post({type:yi.ValidateRequested},{successType:mi.Validated}),[4,this._detachmentObserver.ensurePresence([this._iframe],t)];case 1:if(!(e=n.sent().payload).isValid)throw new hi(e.errors);return[2]}}))}))},t.prototype._getFontUrls=function(){var t=this,e="fonts.googleapis.com",n=document.querySelectorAll("link[href*='"+e+"'][rel='stylesheet']");return Array.prototype.slice.call(n).filter((function(t){return Hr(t.href).hostname===e})).filter((function(e){return(0,y.values)(t._styles).map((function(t){return t&&t.fontFamily})).filter((function(t){return"string"==typeof t})).some((function(t){return t.split(/,\s/).some((function(t){return-1!==e.href.indexOf(t.replace(" ","+"))}))}))})).map((function(t){return t.href}))},t.prototype._isSubmitErrorEvent=function(t){return t.type===mi.SubmitFailed},t}(),gi=function(){function t(t,e,n,r,i){var a=this;this._fields=t,this._eventListener=e,this._payloadTransformer=n,this._eventCallbacks=r,this._paymentHumanVerificationHandler=i,this._handleEnter=function(t){var e=t.payload;return(0,o.__awaiter)(a,void 0,void 0,(function(){var t,n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,this.validate()];case 1:return r.sent(),[3,3];case 2:if("InvalidHostedFormValueError"!==(t=r.sent()).name)throw t;return[3,3];case 3:return(void 0===(n=this._eventCallbacks.onEnter)?y.noop:n)(e),[2]}}))}))};var u=this._eventCallbacks,s=u.onBlur,c=void 0===s?y.noop:s,d=u.onCardTypeChange,l=void 0===d?y.noop:d,f=u.onFocus,p=void 0===f?y.noop:f,h=u.onValidate,m=void 0===h?y.noop:h;this._eventListener.addListener(mi.Blurred,(function(t){var e=t.payload;return c(e)})),this._eventListener.addListener(mi.CardTypeChanged,(function(t){var e=t.payload;return l(e)})),this._eventListener.addListener(mi.Focused,(function(t){var e=t.payload;return p(e)})),this._eventListener.addListener(mi.Validated,(function(t){var e=t.payload;return m(e)})),this._eventListener.addListener(mi.Entered,this._handleEnter),this._eventListener.addListener(mi.CardTypeChanged,(function(t){var e=t.payload;return a._cardType=e.cardType})),this._eventListener.addListener(mi.BinChanged,(function(t){var e=t.payload;return a._bin=e.bin}))}return t.prototype.getBin=function(){return this._bin},t.prototype.getCardType=function(){return this._cardType},t.prototype.attach=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return this._eventListener.listen(),t=this._getFirstField(),e=(0,y.without)(this._fields,t),[4,t.attach()];case 1:return n.sent(),[4,Promise.all(e.map((function(t){return t.attach()})))];case 2:return n.sent(),[2]}}))}))},t.prototype.detach=function(){this._eventListener.stopListen(),this._fields.forEach((function(t){t.detach()}))},t.prototype.submit=function(t,e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,5]),[4,this._getFirstField().submitForm(this._fields.map((function(t){return t.getType()})),this._payloadTransformer.transform(t,e))];case 1:case 4:return[2,i.sent()];case 2:return n=i.sent(),[4,this._paymentHumanVerificationHandler.handle(n)];case 3:return r=i.sent(),[4,this._getFirstField().submitForm(this._fields.map((function(t){return t.getType()})),this._payloadTransformer.transform(t,r))];case 5:return[2]}}))}))},t.prototype.validate=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(t){return[2,this._getFirstField().validateForm()]}))}))},t.prototype._getFirstField=function(){var t=this._fields[0];if(!t)throw new fi("Unable to proceed because the payment form has no field defined.");return t},t}();function _i(t){return Boolean(t.instrumentId)}const bi=function(){function t(t){this._store=t}return t.prototype.transform=function(t,e){var n=this._store.getState(),r=n.checkout.getCheckout(),i=n.config.getConfig(),o=n.instruments.getInstrumentsMeta(),a=n.order.getOrder(),u=n.order.getOrderMeta(),s=(0,y.omit)(t.paymentData,"ccExpiry","ccName","ccNumber","ccCvv"),c=n.paymentMethods.getPaymentMethod(t.methodId,t.gatewayId),d=n.paymentMethods.getPaymentMethodsMeta(),l=o&&s&&_i(s)?n.payment.getPaymentToken()+", "+o.vaultAccessToken:n.payment.getPaymentToken();if(!l)throw new kn(xn.MissingPaymentToken);return{additionalAction:e,authToken:l,checkout:r,config:i,order:a,orderMeta:u,payment:s,paymentMethod:c,paymentMethodMeta:d}},t}(),Si=function(){function t(t){this._store=t}return t.prototype.create=function(t,e){var n=this,r=Object.keys(e.fields).reduce((function(r,i){var a=e.fields[i];return a?(0,o.__spreadArrays)(r,[new vi(i,a.containerId,a.placeholder||"",a.accessibilityLabel||"",e.styles||{},new Kr(t),new Jr(t),new Ur(new Fr),"instrumentId"in a?n._getCardInstrument(a.instrumentId):void 0)]):r}),[]);return new gi(r,new Jr(t),new bi(this._store),(0,y.pick)(e,"onBlur","onEnter","onFocus","onCardTypeChange","onValidate"),new ei(li((0,ar.VD)())))},t.prototype._getCardInstrument=function(t){var e=(0,this._store.getState().instruments.getCardInstrument)(t);if(!e)throw new kn(xn.MissingPaymentInstrument);return e},t}(),wi=function(t){function e(){var e=t.call(this,"You haven't complete our spam check. Please try again.")||this;return e.name="SpamProtectionNotCompletedError",e.type="spam_protection_not_completed",e}return(0,o.__extends)(e,t),e}(l),Ci=function(){function t(t,e){this._orderRequestSender=t,this._checkoutValidator=e}return t.prototype.loadOrder=function(t,e){var n=this;return new Jn.y((function(r){r.next((0,a.PH)(ut.LoadOrderRequested)),n._orderRequestSender.loadOrder(t,e).then((function(t){r.next((0,a.PH)(ut.LoadOrderSucceeded,t.body)),r.complete()})).catch((function(t){r.error((0,a.bR)(ut.LoadOrderFailed,t))}))}))},t.prototype.loadOrderPayments=function(t,e){var n=this;return new Jn.y((function(r){r.next((0,a.PH)(ut.LoadOrderPaymentsRequested)),n._orderRequestSender.loadOrder(t,e).then((function(t){r.next((0,a.PH)(ut.LoadOrderPaymentsSucceeded,t.body)),r.complete()})).catch((function(t){r.error((0,a.bR)(ut.LoadOrderPaymentsFailed,t))}))}))},t.prototype.loadCurrentOrder=function(t){var e=this;return function(n){return(0,dr.P)((function(){var r=e._getCurrentOrderId(n.getState());if(!r)throw new kn(xn.MissingOrderId);return e.loadOrder(r,t)}))}},t.prototype.submitOrder=function(t,e){var n=this;return function(r){return(0,sr.z)((0,cr.of)((0,a.PH)(ut.SubmitOrderRequested)),(0,dr.P)((function(){var i=r.getState(),u=i.config.getExternalSource(),s=i.config.getVariantIdentificationToken(),c=i.checkout.getCheckout();if(!c)throw new kn(xn.MissingCheckout);if(c.shouldExecuteSpamCheck)throw new wi;return(0,P.D)(n._checkoutValidator.validate(c,e).then((function(){return n._orderRequestSender.submitOrder(n._mapToOrderRequestBody(null!=t?t:{},c.id,c.customerMessage,u),(0,o.__assign)((0,o.__assign)({},e),{headers:{checkoutVariant:s}}))}))).pipe((0,xr.w)((function(t){return(0,sr.z)(n.loadOrder(t.body.data.order.orderId,e),(0,cr.of)((0,a.PH)(ut.SubmitOrderSucceeded,t.body.data,(0,o.__assign)((0,o.__assign)({},t.body.meta),{token:t.headers.token}))))})))})).pipe((0,A.K)((function(t){return pr(ut.SubmitOrderFailed,t)}))))}},t.prototype.finalizeOrder=function(t,e){var n=this;return(0,sr.z)((0,cr.of)((0,a.PH)(ut.FinalizeOrderRequested)),(0,P.D)(this._orderRequestSender.finalizeOrder(t,e)).pipe((0,xr.w)((function(r){return(0,sr.z)(n.loadOrder(t,e),(0,cr.of)((0,a.PH)(ut.FinalizeOrderSucceeded,r.body.data)))})))).pipe((0,A.K)((function(t){return pr(ut.FinalizeOrderFailed,t)})))},t.prototype._getCurrentOrderId=function(t){var e=t.order.getOrder(),n=t.checkout.getCheckout();return e&&e.orderId||n&&n.orderId},t.prototype._mapToOrderRequestBody=function(t,e,n,r){var i=t.payment,a=(0,o.__rest)(t,["payment"]);return i?(0,o.__assign)((0,o.__assign)({},a),{cartId:e,customerMessage:n,externalSource:r,payment:{paymentData:i.paymentData,name:i.methodId,gateway:i.gatewayId}}):(0,o.__assign)((0,o.__assign)({},a),{cartId:e,customerMessage:n,externalSource:r})},t}(),Ei=function(t){function e(e){var n=t.call(this,e||"Your checkout could not be processed because some details have changed. Please review your order and try again.")||this;return n.name="CartConsistencyError",n.type="cart_consistency",n}return(0,o.__extends)(e,t),e}(l),Ii=function(t){function e(e){var n=t.call(this,e||"The tax provider is unavailable.")||this;return n.name="OrderTaxProviderUnavailableError",n.type="tax_provider_unavailable",n}return(0,o.__extends)(e,t),e}(l),Pi=function(){function t(t){this._requestSender=t}return t.prototype.loadOrder=function(t,e){var n=(void 0===e?{}:e).timeout,r="/api/storefront/orders/"+t,i=(0,o.__assign)({Accept:nr.JsonV1},ir);return this._requestSender.get(r,{params:{include:br(["payments","lineItems.physicalItems.socialMedia","lineItems.physicalItems.options","lineItems.physicalItems.categories","lineItems.digitalItems.socialMedia","lineItems.digitalItems.options","lineItems.digitalItems.categories"])},headers:i,timeout:n})},t.prototype.submitOrder=function(t,e){var n=void 0===e?{}:e,r=n.headers,i=n.timeout;return this._requestSender.post("/internalapi/v1/checkout/order",{body:t,headers:(0,y.omitBy)((0,o.__assign)({"X-Checkout-Variant":r&&r.checkoutVariant},ir),y.isNil),timeout:i}).catch((function(t){if("tax_provider_unavailable"===t.body.type)throw new Ii;if("cart_has_changed"===t.body.type)throw new Ei;throw t}))},t.prototype.finalizeOrder=function(t,e){var n=(void 0===e?{}:e).timeout,r="/internalapi/v1/checkout/order/"+t;return this._requestSender.post(r,{timeout:n,headers:ir})},t}(),Ai=function(){function t(t,e,n,r){var i=this;this._paymentRequestSender=t,this._orderActionCreator=e,this._paymentRequestTransformer=n,this._paymentHumanVerificationHandler=r,this.initializeOffsitePayment=function(t){var e=t.methodId,n=t.gatewayId,r=t.instrumentId,o=t.target,u=t.promise,s=t.shouldSaveInstrument,c=t.shouldSetAsDefaultInstrument;return function(t){var d;r?d={formattedPayload:{bigpay_token:r}}:s&&(d={formattedPayload:{vault_payment_instrument:s,set_as_default_stored_instrument:c||null}});var l=i._paymentRequestTransformer.transform({gatewayId:n,methodId:e,paymentData:d},t.getState());return(0,sr.z)((0,cr.of)((0,a.PH)(oe.InitializeOffsitePaymentRequested)),Promise.race([i._paymentRequestSender.initializeOffsitePayment(l,o),u].filter(Boolean)).then((function(){return(0,a.PH)(oe.InitializeOffsitePaymentSucceeded)}))).pipe((0,A.K)((function(t){return pr(oe.InitializeOffsitePaymentFailed,t)})))}}}return t.prototype.submitPayment=function(t){var e=this;return function(n){return(0,sr.z)((0,cr.of)((0,a.PH)(oe.SubmitPaymentRequested)),(0,dr.P)((function(){return(0,o.__awaiter)(e,void 0,void 0,(function(){var e,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,5]),[4,this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform(t,n.getState()))];case 1:case 4:return[2,i.sent()];case 2:return e=i.sent(),[4,this._paymentHumanVerificationHandler.handle(e)];case 3:return r=i.sent(),[4,this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform((0,o.__assign)((0,o.__assign)({},t),{additionalAction:r}),n.getState()))];case 5:return[2]}}))}))})).pipe((0,xr.w)((function(t){var r=t.body;return(0,sr.z)(e._orderActionCreator.loadCurrentOrder()(n),(0,cr.of)((0,a.PH)(oe.SubmitPaymentSucceeded,r)))})))).pipe((0,A.K)((function(t){return pr(oe.SubmitPaymentFailed,t)})))}},t}(),Oi=function(){function t(t){this._client=t}return t.prototype.submitPayment=function(t){var e=this;return new Promise((function(n,r){e._client.submitPayment(t,(function(t,i){t?r(e._transformResponse(t)):n(e._transformResponse(i))}))}))},t.prototype.initializeOffsitePayment=function(t,e){var n=this;return new Promise((function(){n._client.initializeOffsitePayment(t,null,e)}))},t.prototype._transformResponse=function(t){return{headers:t.headers,body:t.data,status:t.status,statusText:t.statusText}},t}();var Ti=n(36438);function xi(t,e){var n;return function(t){return void 0!==t.id}(t)?n=t.id:e&&e.length&&(n=e[0].id),{id:n,firstName:t.firstName,lastName:t.lastName,company:t.company,addressLine1:t.address1,addressLine2:t.address2,city:t.city,province:t.stateOrProvince,provinceCode:t.stateOrProvinceCode,postCode:t.postalCode,country:t.country,countryCode:t.countryCode,phone:t.phone,customFields:t.customFields}}const Ri=function(){function t(t){this._decimalPlaces=t}return t.prototype.toInteger=function(t){return Math.round(t*Math.pow(10,this._decimalPlaces))},t}();var ki,Mi=["per_item_discount","percentage_discount","per_total_discount","shipping_discount","free_shipping"];function Ni(t){return{code:t.code,discount:t.displayName,discountType:Mi.indexOf(t.couponType)}}function Di(t){return{code:t.code,discountedAmount:t.used,remainingBalance:t.remaining,giftCertificate:{balance:t.balance,code:t.code,purchaseDate:t.purchaseDate}}}function Li(t,e,n){return void 0===n&&(n="id"),Object.keys(t).reduce((function(r,i){return(0,o.__spreadArrays)(r,t[i].map((function(t){return"giftCertificates"===i?function(t,e){var n=new Ri(e);return{id:t.id,imageUrl:"",name:t.name,amount:t.amount,amountAfterDiscount:t.amount,discount:0,integerAmount:n.toInteger(t.amount),integerAmountAfterDiscount:n.toInteger(t.amount),integerUnitPrice:n.toInteger(t.amount),integerUnitPriceAfterDiscount:n.toInteger(t.amount),integerDiscount:0,quantity:1,sender:t.sender,recipient:t.recipient,type:"ItemGiftCertificateEntity",attributes:[],variantId:null}}(t,e):function(t,e,n,r){void 0===r&&(r="id");var i=new Ri(n);return{id:t[r],imageUrl:t.imageUrl,amount:t.extendedListPrice,amountAfterDiscount:t.extendedSalePrice,discount:t.discountAmount,integerAmount:i.toInteger(t.extendedListPrice),integerAmountAfterDiscount:i.toInteger(t.extendedSalePrice),integerDiscount:i.toInteger(t.discountAmount),integerUnitPrice:i.toInteger(t.listPrice),integerUnitPriceAfterDiscount:i.toInteger(t.salePrice),downloadsPageUrl:t.downloadPageUrl,name:t.name,quantity:t.quantity,brand:t.brand,sku:t.sku,categoryNames:t.categoryNames,variantId:t.variantId,productId:t.productId,attributes:(t.options||[]).map((function(t){return{name:t.name,value:t.value}})),addedByPromotion:t.addedByPromotion,type:e}}(t,function(t){switch(t){case"physicalItems":return"ItemPhysicalEntity";case"digitalItems":return"ItemDigitalEntity";case"giftCertificates":return"ItemGiftCertificateEntity";default:return""}}(i),e,n)})))}),[])}function zi(t){var e,n,r=t.cart.currency.decimalPlaces,i=new Ri(r);return{id:t.cart.id,items:Li(t.cart.lineItems,r),currency:t.cart.currency.code,coupon:{discountedAmount:(0,y.reduce)(t.cart.coupons,(function(t,e){return t+e.discountedAmount}),0),coupons:t.cart.coupons.map(Ni)},discount:{amount:t.cart.discountAmount,integerAmount:i.toInteger(t.cart.discountAmount)},discountNotifications:(e=t.promotions,n=[],(e||[]).forEach((function(t){(t.banners||[]).forEach((function(t){n.push({placeholders:[],discountType:null,message:"",messageHtml:t.text})}))})),n),giftCertificate:{totalDiscountedAmount:(0,y.reduce)(t.giftCertificates,(function(t,e){return t+e.used}),0),appliedGiftCertificates:(0,y.keyBy)(t.giftCertificates.map(Di),"code")},shipping:{amount:t.shippingCostTotal,integerAmount:i.toInteger(t.shippingCostTotal),amountBeforeDiscount:t.shippingCostBeforeDiscount,integerAmountBeforeDiscount:i.toInteger(t.shippingCostBeforeDiscount),required:(0,y.some)(t.cart.lineItems.physicalItems,(function(t){return t.isShippingRequired}))},subtotal:{amount:t.subtotal,integerAmount:i.toInteger(t.subtotal)},storeCredit:{amount:t.customer?t.customer.storeCredit:0},taxSubtotal:{amount:t.taxTotal,integerAmount:i.toInteger(t.taxTotal)},taxes:t.taxes,taxTotal:{amount:t.taxTotal,integerAmount:i.toInteger(t.taxTotal)},handling:{amount:t.handlingCostTotal,integerAmount:i.toInteger(t.handlingCostTotal)},grandTotal:{amount:t.grandTotal,integerAmount:i.toInteger(t.grandTotal)}}}!function(t){t.APPLEPAY="applepay",t.AMAZON_PAY_V2="amazonpay",t.BRAINTREE_PAYPAL="braintreepaypal",t.BRAINTREE_VENMO="braintreevenmo",t.BRAINTREE_PAYPAL_CREDIT="braintreepaypalcredit",t.GOOGLEPAY_ADYENV2="googlepayadyenv2",t.GOOGLEPAY_ADYENV3="googlepayadyenv3",t.GOOGLEPAY_AUTHORIZENET="googlepayauthorizenet",t.GOOGLEPAY_BNZ="googlepaybnz",t.GOOGLEPAY_BRAINTREE="googlepaybraintree",t.GOOGLEPAY_CHECKOUTCOM="googlepaycheckoutcom",t.GOOGLEPAY_CYBERSOURCEV2="googlepaycybersourcev2",t.GOOGLEPAY_ORBITAL="googlepayorbital",t.GOOGLEPAY_STRIPE="googlepaystripe",t.GOOGLEPAY_STRIPEUPE="googlepaystripeupe",t.GOOGLEPAY_WORLDPAYACCESS="googlepayworldpayaccess",t.MASTERPASS="masterpass",t.PAYPALEXPRESS="paypalexpress"}(ki||(ki={}));const ji=ki;function Ui(t,e){var n=t.firstName||e.firstName||"",r=t.lastName||e.lastName||"";return{addresses:(t.addresses||[]).map((function(t){return xi(t)})),customerId:t.id,isGuest:t.isGuest,storeCredit:t.storeCredit,email:t.email||e.email||"",firstName:n,lastName:r,name:t.fullName||[n,r].join(" "),customerGroupName:t.customerGroup&&t.customerGroup.name}}const Fi=function(){function t(){}return t.prototype.format=function(t){var e=t.split(new RegExp("\\s*/\\s*")),n=e[0],r=void 0===n?"":n,i=e[1],o=void 0===i?"":i,a=r.slice(0,2),u=4===o.length?o.slice(-2):o?o.slice(0,2):r.slice(2);return t.length<2?r:t.length>3&&!u?a:a+" / "+u},t.prototype.toObject=function(t){var e=t.split(new RegExp("\\s*/\\s*")),n=e[0],r=void 0===n?"":n,i=e[1],o=void 0===i?"":i;return/^\d+$/.test(r)&&/^\d+$/.test(o)?{month:1===r.length?"0"+r:r.slice(0,2),year:2===o.length?"20"+o:o.slice(0,4)}:{month:"",year:""}},t}();var qi=n(67061);const Bi=function(){function t(){}return t.prototype.format=function(t){var e=(0,qi.number)(t).card;if(!e)return t;var n=(0,y.max)((0,qi.creditCardType)(t).map((function(t){return(0,y.max)(t.lengths)}))),r=this.unformat(t).slice(0,n);return e.gaps.filter((function(t){return r.length>t})).reduce((function(t,e,n){return[t.slice(0,e+n),t.slice(e+n)].join(" ")}),r)},t.prototype.unformat=function(t){return(0,qi.number)(t).card?t.replace(new RegExp(" ","g"),""):t},t}();function Gi(t,e){void 0===e&&(e={});var n,r,i=t.currency.decimalPlaces,o=new Ri(i);return{id:t.orderId,items:Li(t.lineItems,t.currency.decimalPlaces,"productId"),orderId:t.orderId,currency:t.currency.code,customerCanBeCreated:t.customerCanBeCreated,payment:Yi(t.payments,e.payment),subtotal:{amount:t.baseAmount,integerAmount:o.toInteger(t.baseAmount)},coupon:{discountedAmount:(0,y.reduce)(t.coupons,(function(t,e){return t+e.discountedAmount}),0),coupons:t.coupons.map(Ni)},discount:{amount:t.discountAmount,integerAmount:o.toInteger(t.discountAmount)},token:e.orderToken,callbackUrl:e.callbackUrl,discountNotifications:[],giftCertificate:(n=t.payments,r=(0,y.filter)(n,{providerId:"giftcertificate"}),{totalDiscountedAmount:(0,y.reduce)(r,(function(t,e){return e.amount+t}),0),appliedGiftCertificates:(0,y.keyBy)(r.map((function(t){return{code:t.detail.code,discountedAmount:t.amount,remainingBalance:t.detail.remaining,giftCertificate:{balance:t.amount+t.detail.remaining,code:t.detail.code,purchaseDate:""}}})),"code")}),socialData:Wi(t),status:t.status,hasDigitalItems:t.hasDigitalItems,isDownloadable:t.isDownloadable,isComplete:t.isComplete,shipping:{amount:t.shippingCostTotal,integerAmount:o.toInteger(t.shippingCostTotal),amountBeforeDiscount:t.shippingCostBeforeDiscount,integerAmountBeforeDiscount:o.toInteger(t.shippingCostBeforeDiscount)},storeCredit:{amount:Vi(t.payments)},taxes:t.taxes,taxTotal:{amount:t.taxTotal,integerAmount:o.toInteger(t.taxTotal)},handling:{amount:t.handlingCostTotal,integerAmount:o.toInteger(t.handlingCostTotal)},grandTotal:{amount:t.orderAmount,integerAmount:t.orderAmountAsInteger}}}function Vi(t){var e=(0,y.find)(t,{providerId:"storecredit"});return e?e.amount:0}function Yi(t,e){void 0===e&&(e={});var n,r=(0,y.find)(t,Hi);return r?{id:r.providerId,status:(n=r.detail.step,"PAYMENT_STATUS_"+n),helpText:r.detail.instructions,returnUrl:e.returnUrl}:{}}function Hi(t){return"giftcertificate"!==t.providerId&&"storecredit"!==t.providerId}function Wi(t){var e={};return(0,o.__spreadArrays)(t.lineItems.physicalItems,t.lineItems.digitalItems).forEach((function(t){var n;e[t.id]=(n=t,["fb","tw","gp"].reduce((function(t,e){var r=n.socialMedia&&(0,y.find)(n.socialMedia,(function(t){return t.code===e}));return r?(t[e]={name:n.name,description:n.name,image:n.imageUrl,url:r.link,shareText:r.text,sharingLink:r.link,channelName:r.channel,channelCode:r.code},t):t}),{}))})),e}function Ki(t,e){return{description:t.description,module:t.type,price:t.cost,id:t.id,selected:e,isRecommended:t.isRecommended,imageUrl:t.imageUrl,transitTime:t.transitTime}}n(88720);const Zi=function(){function t(){this._cardExpiryFormatter=new Fi,this._cardNumberFormatter=new Bi}return t.prototype.transform=function(t,e){var n,r=e.billingAddress.getBillingAddress(),i=e.checkout.getCheckout(),a=e.customer.getCustomer(),u=e.order.getOrder(),s=e.paymentMethods.getPaymentMethod(t.methodId,t.gatewayId),c=this._mapShippingAddress(e,s),d=e.consignments.getConsignments(),l=e.consignments.getShippingOption(),f=e.config.getStoreConfig(),p=e.config.getContextConfig(),h=e.instruments.getInstrumentsMeta(),m=e.paymentMethods.getPaymentMethodsMeta(),v=e.order.getOrderMeta(),g=a&&r&&Ui(a,r),_=h&&t.paymentData&&(_i(t.paymentData)||(n=t.paymentData.formattedPayload)&&("string"==typeof n.bigpay_token||Boolean(n.bigpay_token&&n.bigpay_token.token)))?e.payment.getPaymentToken()+", "+h.vaultAccessToken:e.payment.getPaymentToken();if(!_)throw new kn(xn.MissingPaymentToken);return{additionalAction:t.additionalAction,authToken:_,customer:g,billingAddress:r&&xi(r),shippingAddress:c&&xi(c,d),shippingOption:l&&Ki(l,!0),cart:i&&zi(i),order:u&&Gi(u,v),orderMeta:v,payment:t.paymentData,paymentMethod:s&&this._transformPaymentMethod(s),quoteMeta:{request:(0,o.__assign)((0,o.__assign)({},m),{geoCountryCode:p&&p.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:(0,y.pick)(f&&f.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}},t.prototype.transformWithHostedFormData=function(t,e,n){var r=e.additionalAction,i=e.authToken,a=e.checkout,u=e.config,s=e.order,c=e.orderMeta,d=e.payment,l=void 0===d?{}:d,f=e.paymentMethod,p=e.paymentMethodMeta,h=a&&a.consignments[0],m=h&&h.shippingAddress,v=h&&h.selectedShippingOption;return{additionalAction:r,authToken:i,paymentMethod:f&&this._transformPaymentMethod(f),customer:s&&s.billingAddress&&a&&Ui(a.customer,s.billingAddress),billingAddress:s&&s.billingAddress&&xi(s.billingAddress),shippingAddress:m&&a&&xi(m,a.consignments),shippingOption:v&&Ki(v,!0),cart:a&&zi(a),order:s&&Gi(s,c),orderMeta:c,payment:this._transformHostedInputValues(t,l,n),quoteMeta:{request:(0,o.__assign)((0,o.__assign)({},p),{geoCountryCode:u&&u.context.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:u&&(0,y.pick)(u.storeConfig.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}},t.prototype._transformPaymentMethod=function(t){return"multi-option"!==t.method||t.gateway?t.initializationData&&t.initializationData.gateway?(0,o.__assign)((0,o.__assign)({},t),{id:t.initializationData.gateway}):t.id===ji.BRAINTREE_VENMO?(0,o.__assign)((0,o.__assign)({},t),{id:ji.BRAINTREE_PAYPAL}):t:(0,o.__assign)((0,o.__assign)({},t),{gateway:t.id})},t.prototype._transformHostedInputValues=function(t,e,n){return"instrumentId"in e?(0,o.__assign)((0,o.__assign)({},e),{ccCvv:t.cardCodeVerification,ccNumber:t.cardNumberVerification&&this._cardNumberFormatter.unformat(t.cardNumberVerification),hostedFormNonce:n}):(0,o.__assign)((0,o.__assign)({},e),{ccCvv:t.cardCode,ccExpiry:this._cardExpiryFormatter.toObject(t.cardExpiry||""),ccName:t.cardName||"",ccNumber:this._cardNumberFormatter.unformat(t.cardNumber||""),hostedFormNonce:n})},t.prototype._mapShippingAddress=function(t,e){var n,r,i,o;if(e){var a=null===(r=null===(n=e.initializationData)||void 0===n?void 0:n.bopis)||void 0===r?void 0:r.enabled,u=null===(o=null===(i=e.initializationData)||void 0===i?void 0:i.bopis)||void 0===o?void 0:o.requiredAddress,s=t.consignments.getConsignments(),c=null==s?void 0:s.every((function(t){return t.selectedPickupOption}));if(a&&c&&"none"===u)return}return t.shippingAddress.getShippingAddress()},t}();var $i;function Ji(t){return Ji="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ji(t)}!function(t){t.AvailableShippingOptions="consignments.availableShippingOptions",t.PhysicalItemsCategoryNames="cart.lineItems.physicalItems.categoryNames",t.DigitalItemsCategoryNames="cart.lineItems.digitalItems.categoryNames"}($i||($i={}));const Qi=function(){function t(t,e){this._consignmentRequestSender=t,this._checkoutRequestSender=e}return t.prototype.unassignItemsByAddress=function(t,e){var n=this;return function(r){var i=r.getState();if(!i.checkout.getCheckout())throw new kn(xn.MissingCheckout);var o=n._consignmentHasAddress(t)?t.address:t.shippingAddress,a=i.consignments.getConsignmentByAddress(o);if(!a)throw new Yr("No consignment found for the specified address");var u=n._removeLineItems(t.lineItems,a,i.cart.getCart());return u.length?n.updateConsignment({id:a.id,address:o,lineItems:u},e)(r):n.deleteConsignment(a.id,e)(r)}},t.prototype.assignItemsByAddress=function(t,e){var n=this;return function(r){var i=r.getState(),o=n._consignmentHasAddress(t)?t.address:t.shippingAddress,a=i.consignments.getConsignmentByAddress(o);return n._createOrUpdateConsignment({id:a&&a.id,address:o,lineItems:n._addLineItems(t.lineItems,a,i.cart.getCart())},e)(r)}},t.prototype.selectShippingOption=function(t,e){var n=this;return function(r){return Jn.y.create((function(i){var o=r.getState(),u=o.checkout.getCheckout(),s=o.consignments.getConsignments();if(!u)throw new kn(xn.MissingCheckout);if(!s||!s.length)throw new kn(xn.MissingConsignments);var c={id:s[0].id,shippingOptionId:t},d={id:s[0].id};i.next((0,a.PH)(Y.UpdateShippingOptionRequested,void 0,d)),n._consignmentRequestSender.updateConsignment(u.id,c,e).then((function(t){var e=t.body;i.next((0,a.PH)(Y.UpdateShippingOptionSucceeded,e,d)),i.complete()})).catch((function(t){i.error((0,a.bR)(Y.UpdateShippingOptionFailed,t,d))}))}))}},t.prototype.loadShippingOptions=function(t){var e=this;return function(n){return Jn.y.create((function(r){var i=n.getState().checkout.getCheckout();if(!i)throw new kn(xn.MissingCheckout);r.next((0,a.PH)(Y.LoadShippingOptionsRequested)),e._checkoutRequestSender.loadCheckout(i.id,(0,o.__assign)((0,o.__assign)({},t),{params:{include:[$i.AvailableShippingOptions]}})).then((function(t){var e=t.body;r.next((0,a.PH)(Y.LoadShippingOptionsSucceeded,e)),r.complete()})).catch((function(t){r.error((0,a.bR)(Y.LoadShippingOptionsFailed,t))}))}))}},t.prototype.updateAddress=function(t,e){var n=this;return function(r){var i=n._getUpdateAddressRequestBody(t,r),o=r.getState().consignments.getConsignments();return o&&o.length&&(i.id=o[0].id),n._createOrUpdateConsignment(i,e)(r)}},t.prototype.createConsignments=function(t,e){var n=this;return function(r){return Jn.y.create((function(i){var o=r.getState().checkout.getCheckout();if(!o||!o.id)throw new kn(xn.MissingCheckout);i.next((0,a.PH)(Y.CreateConsignmentsRequested)),n._consignmentRequestSender.createConsignments(o.id,t,e).then((function(t){var e=t.body;i.next((0,a.PH)(Y.CreateConsignmentsSucceeded,e)),i.complete()})).catch((function(t){i.error((0,a.bR)(Y.CreateConsignmentsFailed,t))}))}))}},t.prototype.updateConsignment=function(t,e){var n=this;return function(r){return Jn.y.create((function(i){var o=r.getState().checkout.getCheckout();if(!o||!o.id)throw new kn(xn.MissingCheckout);var u={id:t.id};i.next((0,a.PH)(Y.UpdateConsignmentRequested,void 0,u)),n._consignmentRequestSender.updateConsignment(o.id,t,e).then((function(t){var e=t.body;i.next((0,a.PH)(Y.UpdateConsignmentSucceeded,e,u)),i.complete()})).catch((function(t){i.error((0,a.bR)(Y.UpdateConsignmentFailed,t,u))}))}))}},t.prototype.deleteConsignment=function(t,e){var n=this;return function(r){return Jn.y.create((function(i){var o=r.getState().checkout.getCheckout(),u={id:t};if(!o||!o.id)throw new kn(xn.MissingCheckout);i.next((0,a.PH)(Y.DeleteConsignmentRequested,void 0,u)),n._consignmentRequestSender.deleteConsignment(o.id,t,e).then((function(t){var e=t.body;i.next((0,a.PH)(Y.DeleteConsignmentSucceeded,e,u)),i.complete()})).catch((function(t){i.error((0,a.bR)(Y.DeleteConsignmentFailed,t,u))}))}))}},t.prototype.updateShippingOption=function(t,e){var n=this;return function(r){return Jn.y.create((function(i){var o=r.getState().checkout.getCheckout();if(!o||!o.id)throw new kn(xn.MissingCheckout);var u={id:t.id};i.next((0,a.PH)(Y.UpdateShippingOptionRequested,void 0,u)),n._consignmentRequestSender.updateConsignment(o.id,t,e).then((function(t){var e=t.body;i.next((0,a.PH)(Y.UpdateShippingOptionSucceeded,e,u)),i.complete()})).catch((function(t){i.error((0,a.bR)(Y.UpdateShippingOptionFailed,t,u))}))}))}},t.prototype._createOrUpdateConsignment=function(t,e){var n=this;return function(r){var i=r.getState().checkout.getCheckout();if(!i||!i.id)throw new kn(xn.MissingCheckout);return n._isUpdateConsignmentRequest(t)?n.updateConsignment(t,e)(r):n.createConsignments([t],e)(r)}},t.prototype._getUpdateAddressRequestBody=function(t,e){var n=e.getState().cart.getCart();if(!n)throw new kn(xn.MissingCart);var r=n.lineItems,i=r.physicalItems,a=r.customItems,u=void 0===a?[]:a;return{address:t,lineItems:(0,o.__spreadArrays)(i,u).map((function(t){return{itemId:t.id,quantity:t.quantity}}))}},t.prototype._removeLineItems=function(t,e,n){if(!n)throw new kn(xn.MissingCart);return this._hydrateLineItems(e.lineItemIds,n).map((function(e){var n=(0,y.find)(t,(function(t){return t.itemId===e.itemId}));return(0,o.__assign)((0,o.__assign)({},e),{quantity:n?e.quantity-n.quantity:e.quantity})})).filter((function(t){return t.quantity>0}))},t.prototype._addLineItems=function(t,e,n){if(!e)return t;if(!n)throw new kn(xn.MissingCart);return t.concat(this._hydrateLineItems(e.lineItemIds,n)).filter((function(t){return t.quantity>0}))},t.prototype._hydrateLineItems=function(t,e){return t.map((function(t){var n=(0,y.find)(e.lineItems.physicalItems,(function(e){return e.id===t}));return{itemId:t,quantity:n?n.quantity:0}}))},t.prototype._isUpdateConsignmentRequest=function(t){return!!t.id},t.prototype._consignmentHasAddress=function(t){return"object"===Ji(t)&&"address"in t},t}();var Xi=["consignments.availableShippingOptions","cart.lineItems.physicalItems.options","cart.lineItems.digitalItems.options","customer","promotions.banners"];const to=function(){function t(t){this._requestSender=t}return t.prototype.createConsignments=function(t,e,n){var r=void 0===n?{}:n,i=r.timeout,a=r.params,u=(void 0===a?{}:a).include,s="/api/storefront/checkouts/"+t+"/consignments",c=(0,o.__assign)({Accept:nr.JsonV1},ir);return this._requestSender.post(s,{body:e,params:{include:Sr(Xi,u)},headers:c,timeout:i})},t.prototype.updateConsignment=function(t,e,n){var r=void 0===n?{}:n,i=r.timeout,a=r.params,u=(void 0===a?{}:a).include,s=e.id,c=(0,o.__rest)(e,["id"]),d="/api/storefront/checkouts/"+t+"/consignments/"+s,l=(0,o.__assign)({Accept:nr.JsonV1},ir);return this._requestSender.put(d,{body:c,params:{include:Sr(Xi,u)},headers:l,timeout:i})},t.prototype.deleteConsignment=function(t,e,n){var r=(void 0===n?{}:n).timeout,i="/api/storefront/checkouts/"+t+"/consignments/"+e,a=(0,o.__assign)({Accept:nr.JsonV1},ir),u=br(Xi);return this._requestSender.delete(i,{params:{include:u},headers:a,timeout:r})},t}(),eo=function(){function t(t,e){this._googleRecaptcha=t,this._requestSender=e}return t.prototype.initialize=function(t){var e=this;return function(n){return(0,sr.z)((0,cr.of)((0,a.PH)(bn.InitializeRequested,void 0)),(0,dr.P)((function(){return(0,o.__awaiter)(e,void 0,void 0,(function(){var e,r,i,u,s;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:return e=t?t.containerId:"spamProtectionContainer",t||document.getElementById(e)||((r=document.createElement("div")).setAttribute("id",e),document.body.appendChild(r)),i=n.getState(),u=i.config.getStoreConfigOrThrow(),s=u.checkoutSettings.googleRecaptchaSitekey,[4,this._googleRecaptcha.load(e,s)];case 1:return o.sent(),[2,(0,a.PH)(bn.InitializeSucceeded)]}}))}))}))).pipe((0,A.K)((function(t){return pr(bn.InitializeFailed,t)})))}},t.prototype.verifyCheckoutSpamProtection=function(){var t=this;return function(e){return(0,dr.P)((function(){var n=e.getState().checkout.getCheckout();if(!n)throw new kn(xn.MissingCheckout);return(0,sr.z)((0,cr.of)((0,a.PH)(bn.VerifyCheckoutRequested)),(0,P.D)(t.execute()(e)).pipe((0,xr.w)((function(e){return kr(e)&&e.payload?(0,P.D)(t._requestSender.validate(n.id,e.payload.token)).pipe((0,xr.w)((function(t){var n=t.body;return(0,sr.z)((0,cr.of)(e),(0,cr.of)((0,a.PH)(bn.VerifyCheckoutSucceeded,n)))}))):(0,cr.of)(e)})))).pipe((0,A.K)((function(t){return pr(bn.VerifyCheckoutFailed,t)})))}))}},t.prototype.execute=function(){var t=this;return function(e){return(0,sr.z)((0,cr.of)((0,a.PH)(bn.ExecuteRequested)),t.initialize()(e),t._googleRecaptcha.execute().pipe((0,Vr.q)(1)).pipe((0,xr.w)((function(e){var n=e.error,r=e.token;return(0,o.__awaiter)(t,void 0,void 0,(function(){return(0,o.__generator)(this,(function(t){if(n instanceof Qr)throw n;if(n||!r)throw new ui;return[2,(0,a.PH)(bn.ExecuteSucceeded,{token:r})]}))}))})))).pipe((0,A.K)((function(t){return pr(bn.ExecuteFailed,t)})))}},t}(),no=function(){function t(t){this._requestSender=t}return t.prototype.validate=function(t,e,n){var r=(void 0===n?{}:n).timeout,i="/api/storefront/checkouts/"+t+"/spam-protection",a=(0,o.__assign)({Accept:nr.JsonV1},ir);return this._requestSender.post(i,{body:{token:e},headers:a,timeout:r})},t}(),ro=function(){function t(t){this._storeCreditRequestSender=t}return t.prototype.applyStoreCredit=function(t,e){var n=this;return function(r){return(0,sr.z)((0,cr.of)((0,a.PH)(dn.ApplyStoreCreditRequested)),(0,dr.P)((function(){return(0,o.__awaiter)(n,void 0,void 0,(function(){var n,i,u;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(n=r.getState(),!(i=n.checkout.getCheckout()))throw new kn(xn.MissingCheckout);return[4,t?this._storeCreditRequestSender.applyStoreCredit(i.id,e):this._storeCreditRequestSender.removeStoreCredit(i.id,e)];case 1:return u=o.sent().body,[2,(0,a.PH)(dn.ApplyStoreCreditSucceeded,u)]}}))}))}))).pipe((0,A.K)((function(t){return pr(dn.ApplyStoreCreditFailed,t)})))}},t}(),io=function(){function t(t){this._requestSender=t}return t.prototype.applyStoreCredit=function(t,e){var n=(void 0===e?{}:e).timeout,r="/api/storefront/checkouts/"+t+"/store-credit",i=(0,o.__assign)({Accept:nr.JsonV1},ir);return this._requestSender.post(r,{headers:i,timeout:n,params:{include:br(wr)}})},t.prototype.removeStoreCredit=function(t,e){var n=(void 0===e?{}:e).timeout,r="/api/storefront/checkouts/"+t+"/store-credit",i=(0,o.__assign)({Accept:nr.JsonV1},ir);return this._requestSender.delete(r,{headers:i,timeout:n,params:{include:br(wr)}})},t}(),oo=function(t){function e(e){var n=t.call(this,e)||this;return n.name="UpdateSubscriptionsError",n.type="update_subscriptions",n}return(0,o.__extends)(e,t),e}(p),ao=function(){function t(t){this._subscriptionsRequestSender=t}return t.prototype.updateSubscriptions=function(t,e){var n=this;return(0,sr.z)((0,cr.of)((0,a.PH)(E.UpdateSubscriptionsRequested)),(0,dr.P)((function(){return(0,o.__awaiter)(n,void 0,void 0,(function(){var n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._subscriptionsRequestSender.updateSubscriptions(t,e)];case 1:return n=r.sent().body,[2,(0,a.PH)(E.UpdateSubscriptionsSucceeded,n)]}}))}))}))).pipe((0,A.K)((function(t){return pr(E.UpdateSubscriptionsFailed,new oo(t))})))},t}(),uo=function(){function t(t){this._requestSender=t}return t.prototype.updateSubscriptions=function(t,e){var n=(void 0===e?{}:e).timeout,r=(0,o.__assign)({Accept:nr.JsonV1},ir);return this._requestSender.post("/api/storefront/subscriptions",{body:t,headers:r,timeout:n})},t}();function so(t){return so="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},so(t)}var co=(0,y.memoize)((function(t){return Array.isArray(t)?t.map((function(t){return lo(t)})):F(t)?Object.keys(t).reduce((function(e,n){var r;return(0,o.__assign)((0,o.__assign)({},e),((r={})[n]=lo(t[n]),r))}),{}):t}));co.cache=new WeakMap;var lo=function(t){return"object"===so(t)&&null!==t?co(t):t};function fo(t){return function(){for(var e=[],n=0;n55?55:t<25?25:t}function Pa(t){var e=t.billingAddress,n=t.email,r=t.firstName,i=t.lastName,o=t.phone,a=t.shippingAddress,u=e||a;return{email:n,first_name:r,last_name:i,phone_number:o,address_line_1:null==u?void 0:u.line1,address_line_2:null==u?void 0:u.line2,city:null==u?void 0:u.city,state:null==u?void 0:u.state,country_code:null==u?void 0:u.countryCode,postal_code:null==u?void 0:u.postalCode}}function Aa(t){var e=t.email,n=t.phone,r=t.shippingAddress,i=((null==r?void 0:r.recipientName)||"").split(" ");return{email:e,first_name:i[0]||"",last_name:i[1]||"",phone_number:n,address_line_1:null==r?void 0:r.line1,address_line_2:null==r?void 0:r.line2,city:null==r?void 0:r.city,state:null==r?void 0:r.state,country_code:null==r?void 0:r.countryCode,postal_code:null==r?void 0:r.postalCode}}const Oa=function(){function t(t,e,n,r,i,o){this._store=t,this._checkoutActionCreator=e,this._cartRequestSender=n,this._braintreeSDKCreator=r,this._formPoster=i,this._window=o}return t.prototype.initialize=function(t){var e,n;return(0,o.__awaiter)(this,void 0,void 0,(function(){var r,i,a,u,s,c,d,l,f,p,h,y,m=this;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(r=t.braintreepaypal,i=t.containerId,a=t.methodId,s=(u=r||{}).messagingContainerId,c=u.onError,!a)throw new Yr('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new Yr('Unable to initialize payment because "options.containerId" argument is not provided.');if(!r)throw new Yr('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');if(!r.buyNowInitializeOptions)return[3,1];if(d=this._store.getState(),l=d.paymentMethods.getPaymentMethodOrThrow(a),!r.currencyCode)throw new Yr('Unable to initialize payment because "options.braintreepaypal.currencyCode" argument is not provided.');return f=r.currencyCode,[3,3];case 1:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 2:d=o.sent(),l=d.paymentMethods.getPaymentMethodOrThrow(a),f=d.cart.getCartOrThrow().currency.code,o.label=3;case 3:if(!l.clientToken)throw new kn(xn.MissingPaymentMethod);return p={currency:f,intent:null===(e=l.initializationData)||void 0===e?void 0:e.intent,isCreditEnabled:null===(n=l.initializationData)||void 0===n?void 0:n.isCreditEnabled},h=function(t){m._renderPayPalComponents(t,r,i,a,Boolean(l.config.testMode))},y=function(t){return m._handleError(t,i,s,c)},this._braintreeSDKCreator.initialize(l.clientToken),[4,this._braintreeSDKCreator.getPaypalCheckout(p,h,y)];case 4:return o.sent(),[2]}}))}))},t.prototype.deinitialize=function(){return this._braintreeSDKCreator.teardown(),Promise.resolve()},t.prototype._renderPayPalComponents=function(t,e,n,r,i){var o=e.messagingContainerId;this._renderPayPalMessages(o),this._renderPayPalButton(t,e,n,r,i)},t.prototype._renderPayPalButton=function(t,e,n,r,i){var o=this,a=e.style,u=e.shouldProcessPayment,s=e.onAuthorizeError,c=this._window.paypal,d=null==c?void 0:c.FUNDING.PAYPAL;if(c&&d){var l=a?Ea(a):{},f=c.Buttons({env:i?"sandbox":"production",commit:!1,fundingSource:d,style:l,createOrder:function(){return o._setupPayment(t,e,r)},onApprove:function(e){return o._tokenizePayment(e,t,r,u,s)}});f.isEligible()&&f.render("#"+n)}else this._removeElement(n)},t.prototype._renderPayPalMessages=function(t){var e=t&&Boolean(document.getElementById(t)),n=this._window.paypal;if(n&&e){var r=this._store.getState().cart.getCartOrThrow();n.Messages({amount:r.cartAmount,placement:"cart"}).render("#"+t)}else this._removeElement(t)},t.prototype._setupPayment=function(t,e,n){var r,i;return(0,o.__awaiter)(this,void 0,void 0,(function(){var a,u,s,c,d,l,f,p,h,y,m,v;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:a=e.buyNowInitializeOptions,u=e.shippingAddress,s=e.onPaymentError,o.label=1;case 1:return o.trys.push([1,7,,8]),d=this,[4,this._createBuyNowCart({buyNowInitializeOptions:a})];case 2:return d._buyNowCart=o.sent(),this._buyNowCart?(c=this._store.getState(),[3,5]):[3,3];case 3:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 4:c=o.sent(),o.label=5;case 5:return l=c.customer.getCustomer(),f=c.paymentMethods.getPaymentMethodOrThrow(n),p=this._buyNowCart?this._buyNowCart.cartAmount:c.checkout.getCheckoutOrThrow().outstandingBalance,h=null!==(r=e.currencyCode)&&void 0!==r?r:c.config.getStoreConfigOrThrow().currency.code,y=u||(null==l?void 0:l.addresses[0]),m=y?Ca(y):void 0,[4,t.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:m,amount:p,currency:h,offerCredit:!1,intent:null===(i=f.initializationData)||void 0===i?void 0:i.intent})];case 6:return[2,o.sent()];case 7:throw v=o.sent(),s&&s(v),v;case 8:return[2]}}))}))},t.prototype._createBuyNowCart=function(t){var e=t.buyNowInitializeOptions;return(0,o.__awaiter)(this,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if("function"!=typeof(null==e?void 0:e.getBuyNowCartRequestBody))return[3,4];if(!(t=e.getBuyNowCartRequestBody()))throw new kn(xn.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._cartRequestSender.createBuyNowCart(t)];case 2:return[2,n.sent().body];case 3:throw n.sent(),new ga;case 4:return[2]}}))}))},t.prototype._tokenizePayment=function(t,e,n,r,i){var a;return(0,o.__awaiter)(this,void 0,void 0,(function(){var u,s,c,d,l,f;return(0,o.__generator)(this,(function(p){switch(p.label){case 0:return p.trys.push([0,3,,4]),[4,this._braintreeSDKCreator.getDataCollector({paypal:!0})];case 1:return u=p.sent().deviceData,[4,e.tokenizePayment(t)];case 2:return s=p.sent(),c=s.details,d=s.nonce,l=null===(a=this._buyNowCart)||void 0===a?void 0:a.id,this._formPoster.postForm("/checkout.php",(0,o.__assign)({payment_type:"paypal",provider:n,action:r?"process_payment":"set_external_checkout",nonce:d,device_data:u,billing_address:JSON.stringify(Pa(c)),shipping_address:JSON.stringify(Aa(c))},l&&{cart_id:l})),[2,s];case 3:throw f=p.sent(),i&&i(f),f;case 4:return[2]}}))}))},t.prototype._handleError=function(t,e,n,r){this._removeElement(e),this._removeElement(n),r&&r(t)},t.prototype._removeElement=function(t){var e=t&&document.getElementById(t);e&&e.remove()},t}();var Ta,xa,Ra,ka,Ma;!function(t){t.HORIZONTAL="horizontal",t.VERTICAL="vertical"}(Ta||(Ta={})),function(t){t.SMALL="small",t.MEDIUM="medium",t.LARGE="large",t.RESPONSIVE="responsive"}(xa||(xa={})),function(t){t.GOLD="gold",t.BLUE="blue",t.SIlVER="silver",t.BLACK="black"}(Ra||(Ra={})),function(t){t.CHECKOUT="checkout",t.PAY="pay",t.BUYNOW="buynow",t.PAYPAL="paypal",t.CREDIT="credit"}(ka||(ka={})),function(t){t.PILL="pill",t.RECT="rect"}(Ma||(Ma={}));const Na=function(){function t(t,e,n,r,i,o){this._store=t,this._checkoutActionCreator=e,this._cartRequestSender=n,this._braintreeSDKCreator=r,this._formPoster=i,this._window=o}return t.prototype.initialize=function(t){var e,n;return(0,o.__awaiter)(this,void 0,void 0,(function(){var r,i,a,u,s,c,d,l,f,p=this;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(r=t.braintreepaypalcredit,i=t.containerId,!(a=t.methodId))throw new Yr('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new Yr('Unable to initialize payment because "options.containerId" argument is not provided.');if(!r)throw new Yr('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');if(!r.buyNowInitializeOptions)return[3,1];if(u=this._store.getState(),s=u.paymentMethods.getPaymentMethodOrThrow(a),!r.currencyCode)throw new Yr('Unable to initialize payment because "options.braintreepaypalcredit.currencyCode" argument is not provided.');return c=r.currencyCode,[3,3];case 1:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 2:u=o.sent(),s=u.paymentMethods.getPaymentMethodOrThrow(a),c=u.cart.getCartOrThrow().currency.code,o.label=3;case 3:if(!s.clientToken)throw new kn(xn.MissingPaymentMethod);return d={currency:c,intent:null===(e=s.initializationData)||void 0===e?void 0:e.intent,isCreditEnabled:null===(n=s.initializationData)||void 0===n?void 0:n.isCreditEnabled},l=function(t){return p._renderPayPalButton(t,r,i,a,Boolean(s.config.testMode))},f=function(t){return p._handleError(t,i,r.onError)},this._braintreeSDKCreator.initialize(s.clientToken),[4,this._braintreeSDKCreator.getPaypalCheckout(d,l,f)];case 4:return o.sent(),[2]}}))}))},t.prototype.deinitialize=function(){return this._braintreeSDKCreator.teardown(),Promise.resolve()},t.prototype._renderPayPalButton=function(t,e,n,r,i){var a=this,u=e.style,s=e.shouldProcessPayment,c=e.onAuthorizeError,d=this._window.paypal,l=!1;if(d){var f=[d.FUNDING.PAYLATER,d.FUNDING.CREDIT],p=u?Ea(u):{};f.forEach((function(u){var f=u===d.FUNDING.CREDIT?(0,o.__assign)({label:ka.CREDIT},p):p;if(!l){var h=d.Buttons({env:i?"sandbox":"production",commit:!1,fundingSource:u,style:f,createOrder:function(){return a._setupPayment(t,e,r)},onApprove:function(e){return a._tokenizePayment(e,t,r,s,c)}});h.isEligible()&&(h.render("#"+n),l=!0)}}))}d&&l||this._removeElement(n)},t.prototype._setupPayment=function(t,e,n){var r,i;return(0,o.__awaiter)(this,void 0,void 0,(function(){var a,u,s,c,d,l,f,p,h,y,m,v;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:a=e.onPaymentError,u=e.shippingAddress,s=e.buyNowInitializeOptions,o.label=1;case 1:return o.trys.push([1,7,,8]),d=this,[4,this._createBuyNowCart({buyNowInitializeOptions:s})];case 2:return d._buyNowCart=o.sent(),this._buyNowCart?(c=this._store.getState(),[3,5]):[3,3];case 3:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 4:c=o.sent(),o.label=5;case 5:return l=c.customer.getCustomer(),f=c.paymentMethods.getPaymentMethodOrThrow(n),p=this._buyNowCart?this._buyNowCart.cartAmount:c.checkout.getCheckoutOrThrow().outstandingBalance,h=null!==(r=e.currencyCode)&&void 0!==r?r:c.config.getStoreConfigOrThrow().currency.code,y=u||(null==l?void 0:l.addresses[0]),m=y?Ca(y):void 0,[4,t.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:m,amount:p,currency:h,offerCredit:!0,intent:null===(i=f.initializationData)||void 0===i?void 0:i.intent})];case 6:return[2,o.sent()];case 7:throw v=o.sent(),a&&a(v),v;case 8:return[2]}}))}))},t.prototype._createBuyNowCart=function(t){var e=t.buyNowInitializeOptions;return(0,o.__awaiter)(this,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if("function"!=typeof(null==e?void 0:e.getBuyNowCartRequestBody))return[3,4];if(!(t=e.getBuyNowCartRequestBody()))throw new kn(xn.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._cartRequestSender.createBuyNowCart(t)];case 2:return[2,n.sent().body];case 3:throw n.sent(),new ga;case 4:return[2]}}))}))},t.prototype._tokenizePayment=function(t,e,n,r,i){var a;return(0,o.__awaiter)(this,void 0,void 0,(function(){var u,s,c,d,l,f;return(0,o.__generator)(this,(function(p){switch(p.label){case 0:return p.trys.push([0,3,,4]),[4,this._braintreeSDKCreator.getDataCollector({paypal:!0})];case 1:return u=p.sent().deviceData,[4,e.tokenizePayment(t)];case 2:return s=p.sent(),c=s.details,d=s.nonce,l=null===(a=this._buyNowCart)||void 0===a?void 0:a.id,this._formPoster.postForm("/checkout.php",(0,o.__assign)({payment_type:"paypal",provider:n,action:r?"process_payment":"set_external_checkout",nonce:d,device_data:u,billing_address:JSON.stringify(Pa(c)),shipping_address:JSON.stringify(Aa(c))},l&&{cart_id:l})),[2,s];case 3:throw f=p.sent(),i&&i(f),f;case 4:return[2]}}))}))},t.prototype._handleError=function(t,e,n){this._removeElement(e),n&&n(t)},t.prototype._removeElement=function(t){var e=t&&document.getElementById(t);e&&e.remove()},t}();var Da={backgroundColor:"#3D95CE",backgroundPosition:"50% 50%",backgroundSize:"80px auto",backgroundImage:'url("/app/assets/img/payment-providers/venmo-logo-white.svg")',backgroundRepeat:"no-repeat",borderRadius:"4px",cursor:"pointer",transition:"0.2s ease",minHeight:"40px",minWidth:"150px",height:"100%",width:"100%"};const La=function(){function t(t,e,n,r,i){this._store=t,this._paymentMethodActionCreator=e,this._cartRequestSender=n,this._braintreeSDKCreator=r,this._formPoster=i,this._onError=y.noop}return t.prototype.initialize=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n,r,i,a,u=this;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(e=t.braintreevenmo,n=t.containerId,!(r=t.methodId))throw new Yr('Unable to initialize payment because "options.methodId" argument is not provided.');return[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(r))];case 1:if(i=o.sent(),!(a=i.paymentMethods.getPaymentMethodOrThrow(r)).clientToken)throw new kn(xn.MissingPaymentMethod);if(!n)throw new Yr('Unable to initialize payment because "options.containerId" argument is not provided.');return this._onError=(null==e?void 0:e.onError)||this._handleError,this._braintreeSDKCreator.initialize(a.clientToken),[4,this._braintreeSDKCreator.getVenmoCheckout((function(t){return u._handleInitializationVenmoSuccess(t,n,null==e?void 0:e.buyNowInitializeOptions)}),(function(t){return u._handleInitializationVenmoError(t,n)}))];case 2:return o.sent(),[2]}}))}))},t.prototype.deinitialize=function(){return this._braintreeSDKCreator.teardown(),Promise.resolve()},t.prototype._handleError=function(t){throw new Error(t.message)},t.prototype._handleInitializationVenmoSuccess=function(t,e,n){return this._renderVenmoButton(t,e,n)},t.prototype._handleInitializationVenmoError=function(t,e){return this._removeVenmoContainer(e),this._onError(t)},t.prototype._removeVenmoContainer=function(t){var e=document.getElementById(t);e&&e.remove()},t.prototype._renderVenmoButton=function(t,e,n){var r=this,i=document.getElementById(e);if(!i)throw new Yr("Unable to create wallet button without valid container ID.");i.setAttribute("aria-label","Venmo"),Object.assign(i.style,Da),i.addEventListener("click",(function(){return(0,o.__awaiter)(r,void 0,void 0,(function(){var e,r=this;return(0,o.__generator)(this,(function(a){switch(a.label){case 0:return i.setAttribute("disabled","true"),[4,this._createBuyNowCart(n)];case 1:return e=a.sent(),t.tokenize&&t.tokenize((function(t,n){return(0,o.__awaiter)(r,void 0,void 0,(function(){return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return i.removeAttribute("disabled"),t?[2,this._onError(t)]:[4,this._handlePostForm(n,null==e?void 0:e.id)];case 1:return r.sent(),[2]}}))}))})),[2]}}))}))})),i.addEventListener("mouseenter",(function(){i.style.backgroundColor="#0a7fc2"})),i.addEventListener("mouseleave",(function(){i.style.backgroundColor=Da.backgroundColor}))},t.prototype._createBuyNowCart=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if("function"!=typeof(null==t?void 0:t.getBuyNowCartRequestBody))return[3,4];if(!(e=t.getBuyNowCartRequestBody()))throw new kn(xn.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._cartRequestSender.createBuyNowCart(e)];case 2:return[2,n.sent().body];case 3:throw n.sent(),new ga;case 4:return[2]}}))}))},t.prototype._handlePostForm=function(t,e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r,i;return(0,o.__generator)(this,(function(a){switch(a.label){case 0:return[4,this._braintreeSDKCreator.getDataCollector()];case 1:return n=a.sent().deviceData,r=t.nonce,i=t.details,this._formPoster.postForm("/checkout.php",(0,o.__assign)({nonce:r,provider:ji.BRAINTREE_VENMO,payment_type:"paypal",device_data:n,action:"set_external_checkout",billing_address:JSON.stringify(Pa(i)),shipping_address:JSON.stringify(Aa(i))},e&&{cart_id:e})),[2]}}))}))},t}();const za=function(t){function e(e){var n=t.call(this,e||"Invalid arguments have been provided.")||this;return n.name="InvalidArgumentError",n.type="invalid_argument",n}return(0,o.__extends)(e,t),e}(u);var ja;!function(t){t[t.CheckoutButtonNotInitialized=0]="CheckoutButtonNotInitialized",t[t.CustomerNotInitialized=1]="CustomerNotInitialized",t[t.PaymentNotInitialized=2]="PaymentNotInitialized",t[t.ShippingNotInitialized=3]="ShippingNotInitialized",t[t.SpamProtectionNotInitialized=4]="SpamProtectionNotInitialized"}(ja||(ja={}));const Ua=function(t){function e(e){var n=t.call(this,function(t){switch(t){case ja.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case ja.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case ja.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case ja.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;return n.subtype=e,n.name="NotInitializedError",n.type="not_initialized",n}return(0,o.__extends)(e,t),e}(u);var Fa;!function(t){t[t.MissingBillingAddress=0]="MissingBillingAddress",t[t.MissingCart=1]="MissingCart",t[t.MissingCheckout=2]="MissingCheckout",t[t.MissingConsignments=3]="MissingConsignments",t[t.MissingCustomer=4]="MissingCustomer",t[t.MissingCheckoutConfig=5]="MissingCheckoutConfig",t[t.MissingOrder=6]="MissingOrder",t[t.MissingOrderConfig=7]="MissingOrderConfig",t[t.MissingOrderId=8]="MissingOrderId",t[t.MissingPayment=9]="MissingPayment",t[t.MissingPaymentId=10]="MissingPaymentId",t[t.MissingPaymentInstrument=11]="MissingPaymentInstrument",t[t.MissingPaymentMethod=12]="MissingPaymentMethod",t[t.MissingPaymentRedirectUrl=13]="MissingPaymentRedirectUrl",t[t.MissingPaymentStatus=14]="MissingPaymentStatus",t[t.MissingPaymentToken=15]="MissingPaymentToken",t[t.MissingShippingAddress=16]="MissingShippingAddress"}(Fa||(Fa={}));const qa=function(t){function e(e){var n=t.call(this,function(t){switch(t){case Fa.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case Fa.MissingCart:return"Unable to proceed because cart data is unavailable.";case Fa.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case Fa.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case Fa.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case Fa.MissingCheckoutConfig:case Fa.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case Fa.MissingOrder:return"Unable to proceed because order data is unavailable.";case Fa.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case Fa.MissingPayment:return"Unable to proceed because payment data is unavailable.";case Fa.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case Fa.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case Fa.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(e))||this;return n.subtype=e,n.name="MissingDataError",n.type="missing_data",n}return(0,o.__extends)(e,t),e}(u),Ba=function(){function t(t,e,n,r,i){this._store=t,this._formPoster=e,this._checkoutActionCreator=n,this._googlePayPaymentProcessor=r,this._cartRequestSender=i}return t.prototype.initialize=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n,r,i,a,u,s,c,d;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(e=t.containerId,n=t.methodId,r=t.currencyCode,i=this._getGooglePayOptions(t),a=i.buyNowInitializeOptions,!e||!n)throw new za('Unable to proceed because "containerId" argument is not provided.');if(u=this._store.getState(),s=u.paymentMethods.getPaymentMethod(n),c=((null==s?void 0:s.config)||{}).testMode,this._methodId=n,this._isBuyNowFlow=!!a,!this._isBuyNowFlow)return[3,2];if(!r)throw new za('Unable to initialize payment because "options.currencyCode" argument is not provided.');return d=i.buyNowInitializeOptions,this._googlePayPaymentProcessor.updateBuyNowFlowFlag(this._isBuyNowFlow),[4,this._googlePayPaymentProcessor.initialize(this._getMethodId(),this._getGooglePayClientOptions(r,c,d))];case 1:return o.sent(),[3,5];case 2:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 3:return o.sent(),[4,this._googlePayPaymentProcessor.initialize(this._getMethodId())];case 4:o.sent(),o.label=5;case 5:return this._walletButton=this._createSignInButton(e,i,r),[2]}}))}))},t.prototype.deinitialize=function(){return this._walletButton&&this._walletButton.parentNode&&(this._walletButton.parentNode.removeChild(this._walletButton),this._walletButton=void 0),this._googlePayPaymentProcessor.deinitialize()},t.prototype._getGooglePayClientOptions=function(t,e,n){var r=this;return{environment:e?"TEST":"PRODUCTION",paymentDataCallbacks:{onPaymentDataChanged:function(e){var i=e.callbackTrigger;return(0,o.__awaiter)(r,void 0,void 0,(function(){var e,r,a,u,s;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(i!==Wo.INITIALIZE)return[2];o.label=1;case 1:return o.trys.push([1,5,,6]),e=this,[4,this._createBuyNowCart(n)];case 2:return e._buyNowCart=o.sent(),this._buyNowCart?(r=this._buyNowCart,a=r.id,u=r.cartAmount,[4,this._store.dispatch(this._checkoutActionCreator.loadCheckout(a))]):[3,4];case 3:return o.sent(),[2,{newTransactionInfo:{currencyCode:t,totalPrice:String(u),totalPriceStatus:Ko.FINAL}}];case 4:return[3,6];case 5:throw s=o.sent(),new ga(s);case 6:return[2]}}))}))}}}},t.prototype._createSignInButton=function(t,e,n){var r=this,i=document.getElementById(t),o=e.buttonType,a=e.buttonColor;if(!i)throw new za("Unable to create sign-in button without valid container ID.");var u=this._googlePayPaymentProcessor.createButton((function(t){return r._handleWalletButtonClick(t,n)}),o,a);return i.appendChild(u),u},t.prototype._getMethodId=function(){if(!this._methodId)throw new Ua(ja.PaymentNotInitialized);return this._methodId},t.prototype._getGooglePayOptions=function(t){if(t.methodId===ji.GOOGLEPAY_ADYENV2&&t.googlepayadyenv2)return t.googlepayadyenv2;if(t.methodId===ji.GOOGLEPAY_ADYENV3&&t.googlepayadyenv3)return t.googlepayadyenv3;if(t.methodId===ji.GOOGLEPAY_AUTHORIZENET&&t.googlepayauthorizenet)return t.googlepayauthorizenet;if(t.methodId===ji.GOOGLEPAY_BNZ&&t.googlepaybnz)return t.googlepaybnz;if(t.methodId===ji.GOOGLEPAY_BRAINTREE&&t.googlepaybraintree)return t.googlepaybraintree;if(t.methodId===ji.GOOGLEPAY_CHECKOUTCOM&&t.googlepaycheckoutcom)return t.googlepaycheckoutcom;if(t.methodId===ji.GOOGLEPAY_CYBERSOURCEV2&&t.googlepaycybersourcev2)return t.googlepaycybersourcev2;if(t.methodId===ji.GOOGLEPAY_ORBITAL&&t.googlepayorbital)return t.googlepayorbital;if(t.methodId===ji.GOOGLEPAY_STRIPE&&t.googlepaystripe)return t.googlepaystripe;if(t.methodId===ji.GOOGLEPAY_STRIPEUPE&&t.googlepaystripeupe)return t.googlepaystripeupe;if(t.methodId===ji.GOOGLEPAY_WORLDPAYACCESS&&t.googlepayworldpayaccess)return t.googlepayworldpayaccess;throw new za},t.prototype._createBuyNowCart=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if("function"!=typeof(null==t?void 0:t.getBuyNowCartRequestBody))return[3,4];if(!(e=t.getBuyNowCartRequestBody()))throw new qa(Fa.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._cartRequestSender.createBuyNowCart(e)];case 2:return[2,n.sent().body];case 3:throw n.sent(),new ga;case 4:return[2]}}))}))},t.prototype._handleWalletButtonClick=function(t,e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:t.preventDefault(),i.label=1;case 1:return i.trys.push([1,7,,8]),this._isBuyNowFlow&&e&&this._googlePayPaymentProcessor.updatePaymentDataRequest({transactionInfo:{currencyCode:e,totalPrice:"0",totalPriceStatus:Ko.ESTIMATED},callbackIntents:[Zo.OFFER]}),[4,this._googlePayPaymentProcessor.displayWallet()];case 2:return n=i.sent(),[4,this._googlePayPaymentProcessor.handleSuccess(n)];case 3:return i.sent(),xo(this._store.getState().cart.getCartOrThrow())>0&&n.shippingAddress?[4,this._googlePayPaymentProcessor.updateShippingAddress(n.shippingAddress)]:[3,5];case 4:i.sent(),i.label=5;case 5:return[4,this._onPaymentSelectComplete()];case 6:return i.sent(),[3,8];case 7:if((r=i.sent())&&"CANCELED"!==r.message)throw r;return[3,8];case 8:return[2]}}))}))},t.prototype._onPaymentSelectComplete=function(){var t,e=null===(t=this._buyNowCart)||void 0===t?void 0:t.id;this._formPoster.postForm("/checkout.php",(0,o.__assign)({headers:(0,o.__assign)({Accept:"text/html","Content-Type":"application/x-www-form-urlencoded"},ir)},e&&{action:"set_external_checkout",provider:this._methodId,cart_id:e}))},(0,o.__decorate)([Zr],t.prototype,"_handleWalletButtonClick",null),t}();var Ga={es:["es_es","es_mx","es_pe","es_co","es_ar","es_cl"],en:["en_us","en_gb","en_ca","en_es","en_fr","en_ie","en_sg","en_au","en_nz","en_my","en_hk","en_th","en_ae","en_sa","en_qa","en_kw","en_za"],pt:["pt_br"],zu:["zu_za"],ar:["ar_sa","ar_ae","ar_qa","ar_kw"],zh:["zh_sg","zh_hk"],ms:["ms_my"],uk:["uk_ua"],sv:["sv_se"],hr:["hr_hr"],pl:["pl_pl"],nl:["nl_be"],it:["it_it"],de:["de_de"],fr:["fr_fr","fr_ca"]};function Va(t){var e=t.replace("-","_").toLowerCase().split("_"),n=e[0],r=n+"_"+e[1],i=Ga[n];return i?i.indexOf(r)>-1?r:i[0]:"en_us"}const Ya=function(){function t(t,e,n,r){this._store=t,this._checkoutActionCreator=e,this._masterpassScriptLoader=n,this._locale=r}return t.prototype.initialize=function(t){var e=this,n=t.containerId,r=t.methodId;if(!n||!r)throw new Yr('Unable to proceed because "containerId" argument is not provided.');return this._methodId=r,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()).then((function(t){var n=t.paymentMethods.getPaymentMethod(r);if(!n||!n.initializationData.checkoutId)throw new kn(xn.MissingPaymentMethod);var i={useMasterpassSrc:n.initializationData.isMasterpassSrcEnabled,language:Va(e._locale),testMode:n.config.testMode,checkoutId:n.initializationData.checkoutId};return e._masterpassScriptLoader.load(i)})).then((function(t){e._masterpassClient=t,e._signInButton=e._createSignInButton(n)}))},t.prototype.deinitialize=function(){return this._signInButton&&this._signInButton.parentNode&&(this._signInButton.removeEventListener("click",this._handleWalletButtonClick),this._signInButton.parentNode.removeChild(this._signInButton),this._signInButton=void 0),Promise.resolve()},t.prototype._createSignInButton=function(t){var e=document.getElementById(t),n=this._store.getState(),r=this._methodId?n.paymentMethods.getPaymentMethod(this._methodId):null,i=n.config.getStoreConfig();if(!e)throw new Error("Need a container to place the button");if(!r)throw new kn(xn.MissingPaymentMethod);if(!i)throw new Yr("Unable to retrieve store configuration");var o=document.createElement("input");if(o.type="image",r.initializationData.isMasterpassSrcEnabled){var a=r.config.testMode?"sandbox.":"",u=r.initializationData.checkoutId,s=["locale="+Va(this._locale),"paymentmethod=master,visa,amex,discover","checkoutid="+u];o.src=["https://"+a+"src.mastercard.com/assets/img/btn/src_chk_btn_126x030px.svg",s.join("&")].join("?")}else o.src="https://static.masterpass.com/dyn/img/btn/global/mp_chk_btn_160x037px.svg";return e.appendChild(o),o.addEventListener("click",this._handleWalletButtonClick),o},t.prototype._createMasterpassPayload=function(){var t=this._store.getState(),e=t.checkout.getCheckout(),n=this._methodId?t.paymentMethods.getPaymentMethod(this._methodId):null;if(!e)throw new kn(xn.MissingCheckout);if(!n)throw new kn(xn.MissingPaymentMethod);return{checkoutId:n.initializationData.checkoutId,allowedCardTypes:n.initializationData.allowedCardTypes,amount:e.cart.cartAmount.toString(),currency:e.cart.currency.code,cartId:e.cart.id,callbackUrl:("cart",window.location.origin+"/checkout.php?action=set_external_checkout&provider=masterpass&gateway=stripe&origin=cart")}},t.prototype._handleWalletButtonClick=function(){if(!this._masterpassClient)throw new ai(ni.CheckoutButtonNotInitialized);this._masterpassClient.checkout(this._createMasterpassPayload())},(0,o.__decorate)([Zr],t.prototype,"_handleWalletButtonClick",null),t}(),Ha=function(){function t(t,e,n,r,i){void 0===i&&(i=""),this._store=t,this._checkoutActionCreator=e,this._paypalScriptLoader=n,this._formPoster=r,this._host=i}return t.prototype.initialize=function(t){var e=this,n=t.paypal,r=this._store.getState(),i=this._paymentMethod=r.paymentMethods.getPaymentMethod(t.methodId);if(!n)throw new Yr;if(!i)throw new kn(xn.MissingPaymentMethod);return this._paypalScriptLoader.loadPaypal(i.config.merchantId).then((function(r){var a,u,s;if(!i||!i.config.merchantId)throw new kn(xn.MissingPaymentMethod);var c=i.config.merchantId,d=i.config.testMode?"sandbox":"production",l=((a={})[d]=n.clientId,a),f=r.FUNDING.CREDIT||"credit",p=n.allowCredit?[f]:[],h=n.allowCredit?[]:[f];return r.Button.render({env:d,client:l,commit:n.shouldProcessPayment,funding:{allowed:p,disallowed:h},style:(0,o.__assign)((0,o.__assign)({shape:Ma.RECT},(0,y.pick)(n.style,"layout","color","label","shape","tagline","fundingicons")),{size:"paypalexpress"===i.id&&"small"===(null===(u=n.style)||void 0===u?void 0:u.size)?xa.RESPONSIVE:null===(s=n.style)||void 0===s?void 0:s.size}),payment:function(t,r){return e._setupPayment(c,r,n.onPaymentError)},onAuthorize:function(t,r){return e._tokenizePayment(t,r,n.shouldProcessPayment,n.onAuthorizeError)}},t.containerId)}))},t.prototype.deinitialize=function(){return this._paymentMethod=void 0,Promise.resolve()},t.prototype._setupPayment=function(t,e,n){var r=this;if(!e)throw new ai(ni.CheckoutButtonNotInitialized);return this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()).then((function(n){var i=n.cart.getCart(),a=i?i.id:"";return e.request.post(r._host+"/api/storefront/payment/paypalexpress",{merchantId:t,cartId:a},{headers:(0,o.__assign)({"X-API-INTERNAL":rr},ir)})})).then((function(t){return t.id})).catch((function(t){throw n&&n(t),t}))},t.prototype._tokenizePayment=function(t,e,n,r){var i=this;if(!this._paymentMethod)throw new ai(ni.CheckoutButtonNotInitialized);if(!e)throw new ai(ni.CheckoutButtonNotInitialized);if(!t.paymentID||!t.payerID)throw new kn(xn.MissingPayment);var o=this._paymentMethod.id;return e.payment.get(t.paymentID).then((function(e){i._formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:o,action:n?"process_payment":"set_external_checkout",paymentId:t.paymentID,payerId:t.payerID,payerInfo:JSON.stringify(e.payer.payer_info)})}))},t}();function Wa(){try{return"production"}catch(t){return"development"}}n(64701);const Ka=function(){function t(t){this._console=t}return t.prototype.log=function(){for(var t=[],e=0;e0}));a.length>1&&a[0].matches===a[1].matches&&"development"===Wa()&&Ja.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.");var u=a[0];if(u&&u.token)return u.token;if(this._useFallback){var s=null===(n=o.find((function(t){return t.default})))||void 0===n?void 0:n.token;if(s)return s}throw new Error("Unable to resolve to a registered token with the provided token.")},t}();function Xa(t,e){return Object.assign(t,{resolveIds:e})}const tu=function(t){function e(e){var n=t.call(this,e||"Payment process was cancelled.")||this;return n.name="PaymentMethodCancelledError",n.type="payment_cancelled",n}return(0,o.__extends)(e,t),e}(u);const eu=function(t){function e(e){var n=t.call(this,e||"An unexpected error has occurred during buy now cart creation process. Please try again later.")||this;return n.name="BuyNowCartCreationError",n.type="buy_now_cart_creation_error",n}return(0,o.__extends)(e,t),e}(u);function nu(t){if(!function(t){return"ApplePaySession"in t}(t))throw new Error("Apple pay is not supported")}const ru=function(){function t(){}return t.prototype.create=function(t){return nu(window),new ApplePaySession(1,t)},t}();var iu;!function(t){t.Subtotal="Subtotal",t.Shipping="Shipping"}(iu||(iu={}));const ou=function(){function t(t,e,n){this._requestSender=t,this._paymentIntegrationService=e,this._sessionFactory=n,this._onAuthorizeCallback=y.noop,this._subTotalLabel=iu.Subtotal,this._shippingLabel=iu.Shipping}return t.prototype.initialize=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n,r,i,a,u,s,c;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(e=t.methodId,n=t.containerId,r=t.applepay,nu(window),!e||!r)throw new qa(Fa.MissingPaymentMethod);return i=r.buttonClassName,a=r.onPaymentAuthorize,u=r.buyNowInitializeOptions,s=r.requiresShipping,this._requiresShipping=s,this._buyNowInitializeOptions=u,this._onAuthorizeCallback=a,u?[3,2]:[4,this._paymentIntegrationService.loadDefaultCheckout()];case 1:o.sent(),o.label=2;case 2:return[4,this._paymentIntegrationService.loadPaymentMethod(e)];case 3:return o.sent(),c=this._paymentIntegrationService.getState(),this._paymentMethod=c.getPaymentMethodOrThrow(e),[4,this._paymentIntegrationService.verifyCheckoutSpamProtection()];case 4:return o.sent(),this._applePayButton=this._createButton(n,i),this._applePayButton.addEventListener("click",this._handleWalletButtonClick.bind(this)),[2,Promise.resolve()]}}))}))},t.prototype.deinitialize=function(){return Promise.resolve()},t.prototype._createButton=function(t,e){void 0===e&&(e="apple-pay-checkout-button");var n=document.getElementById(t);if(!n)throw new za("Unable to create wallet button without valid container ID.");document.body.classList.add("apple-pay-supported");var r=document.createElement("div");return r.setAttribute("class",e),r.setAttribute("role","button"),r.setAttribute("aria-label","Apple Pay button"),n.appendChild(r),r},t.prototype._handleWalletButtonClick=function(t){var e;return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r,i,a,u,s,c,d,l,f,p,h;return(0,o.__generator)(this,(function(o){if(t.preventDefault(),!this._paymentMethod||!this._paymentMethod.initializationData)throw new qa(Fa.MissingPaymentMethod);return this._buyNowInitializeOptions&&"function"==typeof this._buyNowInitializeOptions.getBuyNowCartRequestBody?(n=this._paymentMethod.initializationData,r=n.countryCode,i=n.currencyCode,a=n.merchantCapabilities,u=n.supportedNetworks,s=n.storeName,p=this._getRequestWithEmptyTotal(r,i,u,a),this._requiresShipping&&(null===(e=p.requiredShippingContactFields)||void 0===e||e.push("postalAddress")),h=this._sessionFactory.create(p),this._handleApplePayEvents(h,this._paymentMethod,s),h.begin()):(c=this._paymentIntegrationService.getState(),d=c.getCartOrThrow(),l=c.getStoreConfigOrThrow(),f=c.getCheckoutOrThrow(),p=this._getBaseRequest(d,f,l,this._paymentMethod),h=this._sessionFactory.create(p),this._handleApplePayEvents(h,this._paymentMethod,l.storeProfile.storeName),h.begin()),[2]}))}))},t.prototype._getRequestWithEmptyTotal=function(t,e,n,r){return{countryCode:t,currencyCode:e,supportedNetworks:n,merchantCapabilities:r,total:{label:"",amount:"0",type:"pending"},requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"]}},t.prototype._getBaseRequest=function(t,e,n,r){var i,o=n.storeProfile,a=o.storeCountryCode,u=o.storeName,s=t.currency,c=s.code,d=s.decimalPlaces,l=r.initializationData,f=l.merchantCapabilities,p=l.supportedNetworks,h=t.lineItems.physicalItems.length>0,y={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:a,currencyCode:c,merchantCapabilities:f,supportedNetworks:p,lineItems:[],total:h?{label:u,amount:""+e.grandTotal.toFixed(d),type:"pending"}:{label:u,amount:""+e.grandTotal.toFixed(d),type:"final"}};if(h)null===(i=y.requiredShippingContactFields)||void 0===i||i.push("postalAddress");else{var m=[{label:this._subTotalLabel,amount:""+e.subtotal.toFixed(d)}];e.taxes.forEach((function(t){return m.push({label:t.name,amount:""+t.amount.toFixed(d)})})),y.lineItems=m}return y},t.prototype._handleApplePayEvents=function(t,e,n){var r=this;t.onvalidatemerchant=function(n){return(0,o.__awaiter)(r,void 0,void 0,(function(){var r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this._onValidateMerchant(e,n)];case 1:return r=i.sent().body,t.completeMerchantValidation(r),[3,3];case 2:throw i.sent(),new Error("Merchant validation failed");case 3:return[2]}}))}))},this._buyNowInitializeOptions&&!this._requiresShipping&&(t.onpaymentmethodselected=function(){return(0,o.__awaiter)(r,void 0,void 0,(function(){return(0,o.__generator)(this,(function(e){switch(e.label){case 0:return[4,this._createBuyNowCart()];case 1:return e.sent(),this._handlePaymentMethodSelected(t),[2]}}))}))}),t.onshippingcontactselected=function(e){return(0,o.__awaiter)(r,void 0,void 0,(function(){return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return this._buyNowInitializeOptions&&this._requiresShipping?[4,this._createBuyNowCart()]:[3,2];case 1:r.sent(),r.label=2;case 2:return[4,this._handleShippingContactSelected(t,n,e)];case 3:return r.sent(),[2]}}))}))},t.onshippingmethodselected=function(e){return(0,o.__awaiter)(r,void 0,void 0,(function(){return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._handleShippingMethodSelected(t,n,e)];case 1:return r.sent(),[2]}}))}))},t.oncancel=function(){return(0,o.__awaiter)(r,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return n.trys.push([0,3,,4]),t="/remote-checkout/"+e.id+"/signout",[4,this._requestSender.get(t)];case 1:return n.sent(),[4,this._paymentIntegrationService.loadCheckout()];case 2:return[2,n.sent()];case 3:throw n.sent(),new tu;case 4:return[2]}}))}))},t.onpaymentauthorized=function(n){return(0,o.__awaiter)(r,void 0,void 0,(function(){return(0,o.__generator)(this,(function(r){return[2,this._onPaymentAuthorized(n,t,e)]}))}))}},t.prototype._createBuyNowCart=function(){var t,e;return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:if(i.trys.push([0,3,,4]),!(n=null===(e=null===(t=this._buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody)||void 0===e?void 0:e.call(t)))throw new qa(Fa.MissingCart);return[4,this._paymentIntegrationService.createBuyNowCart(n)];case 1:return r=i.sent(),[4,this._paymentIntegrationService.loadCheckout(r.id)];case 2:return i.sent(),[3,4];case 3:throw i.sent(),new eu;case 4:return[2]}}))}))},t.prototype._handlePaymentMethodSelected=function(t){var e=this._paymentIntegrationService.getState(),n=e.getCartOrThrow(),r=e.getStoreConfigOrThrow(),i=e.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new qa(Fa.MissingPaymentMethod);var o=this._getBaseRequest(n,i,r,this._paymentMethod);delete o.total.type,t.completePaymentMethodSelection({newTotal:o.total,newLineItems:o.lineItems})},t.prototype._handleShippingContactSelected=function(t,e,n){var r;return(0,o.__awaiter)(this,void 0,void 0,(function(){var i,a,u,s,c,d,l,f,p,h,y,m;return(0,o.__generator)(this,(function(v){switch(v.label){case 0:i=this._transformContactToAddress(n.shippingContact),v.label=1;case 1:return v.trys.push([1,3,,4]),[4,this._paymentIntegrationService.updateShippingAddress(i)];case 2:return v.sent(),[3,4];case 3:throw v.sent(),t.abort(),new Error("Shipping address update failed");case 4:if(a=this._paymentIntegrationService.getState(),u=a.getCartOrThrow().currency.decimalPlaces,s=a.getCheckoutOrThrow(),c=null===(r=s.consignments[0].selectedShippingOption)||void 0===r?void 0:r.id,d=s.consignments[0].availableShippingOptions,l=null==d?void 0:d.find((function(t){return t.id===c})),f=null==d?void 0:d.filter((function(t){return t.id!==c})),p=l?[{label:l.description,amount:""+l.cost.toFixed(u),detail:l.additionalDescription,identifier:l.id}]:[],f&&(0,o.__spreadArrays)(f.filter((function(t){return t.isRecommended})),f.filter((function(t){return!t.isRecommended}))).forEach((function(t){return p.push({label:t.description,amount:""+t.cost.toFixed(u),detail:t.additionalDescription,identifier:t.id})})),!(d instanceof Array))throw new Error("Shipping options not available.");if(0===d.length)return t.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:e,amount:""+s.grandTotal.toFixed(u)},[]),[2];h=d.find((function(t){return t.isRecommended})),y=h?h.id:d[0].id,m=l?l.id:y,v.label=5;case 5:return v.trys.push([5,7,,8]),[4,this._updateShippingOption(m)];case 6:return v.sent(),[3,8];case 7:throw v.sent(),new Error("Shipping options update failed");case 8:return a=this._paymentIntegrationService.getState(),s=a.getCheckoutOrThrow(),t.completeShippingContactSelection({newShippingMethods:p,newTotal:{type:"final",label:e,amount:""+s.grandTotal.toFixed(u)},newLineItems:this._getUpdatedLineItems(s,u)}),[2]}}))}))},t.prototype._handleShippingMethodSelected=function(t,e,n){return(0,o.__awaiter)(this,void 0,void 0,(function(){var r,i,a,u;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:r=n.shippingMethod.identifier,o.label=1;case 1:return o.trys.push([1,3,,4]),[4,this._updateShippingOption(r)];case 2:return o.sent(),[3,4];case 3:throw o.sent(),t.abort(),new Error("Shipping option selection update failed.");case 4:return i=this._paymentIntegrationService.getState(),a=i.getCartOrThrow().currency.decimalPlaces,u=i.getCheckoutOrThrow(),t.completeShippingMethodSelection({newTotal:{type:"final",label:e,amount:""+u.grandTotal.toFixed(a)},newLineItems:this._getUpdatedLineItems(u,a)}),[2]}}))}))},t.prototype._getUpdatedLineItems=function(t,e){var n=[{label:this._subTotalLabel,amount:""+t.subtotal.toFixed(e)}];return t.taxes.forEach((function(t){return n.push({label:t.name,amount:""+t.amount.toFixed(e)})})),n.push({label:this._shippingLabel,amount:""+t.shippingCostTotal.toFixed(e)}),n},t.prototype._updateShippingOption=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(e){return[2,this._paymentIntegrationService.selectShippingOption(t)]}))}))},t.prototype._onValidateMerchant=function(t,e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n;return(0,o.__generator)(this,(function(r){return n=["validationUrl="+e.validationURL,"merchantIdentifier="+t.initializationData.merchantId,"displayName="+t.initializationData.storeName,"domainName="+window.location.hostname].join("&"),[2,this._requestSender.post((i=t.initializationData.paymentsUrl,i+"/api/public/v1/payments/applepay/validate_merchant"),{credentials:!1,headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","X-XSRF-TOKEN":null},body:n})];var i}))}))},t.prototype._onPaymentAuthorized=function(t,e,n){return(0,o.__awaiter)(this,void 0,void 0,(function(){var r,i,a,u,s,c,d,l,f,p,h,y;return(0,o.__generator)(this,(function(m){switch(m.label){case 0:r=t.payment,i=r.token,a=r.billingContact,u=r.shippingContact,s=this._paymentIntegrationService.getState(),c=s.getCartOrThrow(),d=c.lineItems.physicalItems.length>0,l={methodId:n.id,paymentData:{formattedPayload:{apple_pay_token:{payment_data:i.paymentData,payment_method:i.paymentMethod,transaction_id:i.transactionIdentifier}}}},f=this._transformContactToAddress(a),p=this._transformContactToAddress(u),h=null==u?void 0:u.emailAddress,y=(null==u?void 0:u.phoneNumber)||"",m.label=1;case 1:return m.trys.push([1,7,,8]),[4,this._paymentIntegrationService.updateBillingAddress((0,o.__assign)((0,o.__assign)({},f),{email:h,phone:y}))];case 2:return m.sent(),d?[4,this._paymentIntegrationService.updateShippingAddress(p)]:[3,4];case 3:m.sent(),m.label=4;case 4:return[4,this._paymentIntegrationService.submitOrder({useStoreCredit:!1})];case 5:return m.sent(),[4,this._paymentIntegrationService.submitPayment(l)];case 6:return m.sent(),e.completePayment(ApplePaySession.STATUS_SUCCESS),[2,this._onAuthorizeCallback()];case 7:throw m.sent(),e.completePayment(ApplePaySession.STATUS_FAILURE),new Error("Payment cannot complete");case 8:return[2]}}))}))},t.prototype._transformContactToAddress=function(t){return{firstName:(null==t?void 0:t.givenName)||"",lastName:(null==t?void 0:t.familyName)||"",city:(null==t?void 0:t.locality)||"",company:"",address1:(null==t?void 0:t.addressLines)&&t.addressLines[0]||"",address2:(null==t?void 0:t.addressLines)&&t.addressLines[1]||"",postalCode:(null==t?void 0:t.postalCode)||"",countryCode:(null==t?void 0:t.countryCode)||"",phone:(null==t?void 0:t.phoneNumber)||"",stateOrProvince:(null==t?void 0:t.administrativeArea)||"",stateOrProvinceCode:(null==t?void 0:t.administrativeArea)||"",customFields:[]}},t}(),au=Xa((function(t){var n=t.getState().getHost;return new ou((0,e.createRequestSender)({host:n()}),t,new ru)}),[{id:"applepay"}]);var uu=n(15373);const su=function(t){function e(e){var n=t.call(this,e||"Not implemented.")||this;return n.name="NotImplementedError",n.type="not_implemented",n}return(0,o.__extends)(e,t),e}(u);var cu,du,lu;!function(t){t.SandboxMode="bolt_sandbox",t.StagingMode="bolt_staging",t.DevelopmentMode="bolt_development"}(cu||(cu={})),function(t){t.Small="small",t.Medium="medium",t.Large="large"}(du||(du={})),function(t){t.Pill="pill",t.Rect="rect"}(lu||(lu={}));const fu=function(){function t(t,e,n){void 0===n&&(n=window),this.paymentIntegrationService=t,this.boltScriptLoader=e,this.boltHostWindow=n}return t.prototype.initialize=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n,r,i,a,u,s,c,d,l,f,p,h;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(e=t.bolt,n=t.containerId,r=t.methodId,a=(i=e||{}).buyNowInitializeOptions,u=i.style,!r)throw new za('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new za('Unable to initialize payment because "options.containerId" argument is not provided.');if(!e)throw new za('Unable to initialize payment because "options.bolt" argument is not provided.');if(!Boolean(a))throw new su("Only buy now flow is implemented for Bolt button");if(!(null==a?void 0:a.storefrontApiToken)||"string"!=typeof a.storefrontApiToken)throw new za('Unable to initialize payment because "options.storefrontApiToken" argument is not provided.');return s=this.paymentIntegrationService.getState(),c=s.getPaymentMethodOrThrow(r),d=c.initializationData,l=c.config,p=(f=d||{}).publishableKey,h=f.developerConfig,[4,this.boltScriptLoader.loadBoltClient(p,l.testMode,h,"BigCommerce",a.storefrontApiToken)];case 1:return o.sent(),this.renderButton(n,c,u),[2]}}))}))},t.prototype.deinitialize=function(){return Promise.resolve()},t.prototype.renderButton=function(t,e,n){var r;"function"==typeof(null===(r=this.boltHostWindow.BoltConnect)||void 0===r?void 0:r.setupProductPageCheckout)&&(this.addButtonContainer(t,e,n),this.boltHostWindow.BoltConnect.setupProductPageCheckout())},t.prototype.addButtonContainer=function(t,e,n){var r=document.getElementById(t);if(r){var i=document.createElement("div"),o=document.createElement("object");i.setAttribute("id","product-page-checkout-wrapper"),i.setAttribute("class","bolt-button-wrapper"),i.setAttribute("style","display:none"),i.setAttribute("data-tid","product-page-checkout-wrapper"),o.setAttribute("data",this.getBoltObjectData(e,n)),o.setAttribute("class","bolt-product-checkout-button"),i.append(o),r.innerHTML="",r.append(i)}},t.prototype.getBoltObjectData=function(t,e){var n=t.initializationData,r=t.config,i=n||{},o=i.publishableKey,a=i.developerConfig,u=this.boltScriptLoader.getDomainURL(!!r.testMode,a),s=this.getButtonHeight(null==e?void 0:e.size),c=this.getButtonBorderRadius(null==e?void 0:e.shape,s);return(0,uu.stringifyUrl)({url:"https://"+u+"/v1/checkout_button",query:{publishable_key:o,variant:"ppc",height:s,border_radius:c}})},t.prototype.getButtonHeight=function(t){if(t)switch(t){case du.Small:return 25;case du.Large:return 45;case du.Medium:default:return 40}},t.prototype.getButtonBorderRadius=function(t,e){if(t)switch(t){case lu.Pill:return e?Math.round(e/2):void 0;case lu.Rect:default:return 4}},t}();const pu=function(t){function e(e){var n=t.call(this,e||"Unable to proceed because the client library of a payment method is not loaded or ready to be used.")||this;return n.name="PaymentMethodClientUnavailableError",n.type="payment_method_client_unavailable",n}return(0,o.__extends)(e,t),e}(u),hu=function(){function t(t,e){void 0===e&&(e=window),this.scriptLoader=t,this.boltHostWindow=e}return t.prototype.loadBoltClient=function(t,e,n,r,i){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(this.boltHostWindow.BoltCheckout)return[2,this.boltHostWindow.BoltCheckout];if(!t)throw new za('Unable to initialize payment because "publishableKey" argument is not provided.');return[4,this.scriptLoader.loadScript("//"+this.getDomainURL(!!e,n)+"/connect-bigcommerce.js",this.getScriptOptions("bolt-connect",t,r,i))];case 1:return o.sent(),[4,this.scriptLoader.loadScript("//"+this.getDomainURL(!!e,n)+"/track.js",this.getScriptOptions("bolt-track",t))];case 2:if(o.sent(),!this.boltHostWindow.BoltCheckout)throw new pu;return[2,this.boltHostWindow.BoltCheckout]}}))}))},t.prototype.loadBoltEmbedded=function(t,e,n){return(0,o.__awaiter)(this,void 0,void 0,(function(){var r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:return r={async:!0,attributes:{id:"bolt-embedded"}},[4,this.scriptLoader.loadScript("//"+this.getDomainURL(!!e,n)+"/embed.js",r)];case 1:if(i.sent(),!this.boltHostWindow.Bolt)throw new pu;return[2,this.boltHostWindow.Bolt(t)]}}))}))},t.prototype.getDomainURL=function(t,e){if(!t)return"connect.bolt.com";if(e)switch(e.developerMode){case cu.StagingMode:return"connect-staging.bolt.com";case cu.DevelopmentMode:return"connect."+e.developerDomain}return"connect-sandbox.bolt.com"},t.prototype.getScriptOptions=function(t,e,n,r){return{async:!0,attributes:(0,o.__assign)((0,o.__assign)({id:t,"data-publishable-key":e},n&&{"data-shopping-cart-id":n}),r&&{"data-storefront-api-token":r})}},t}(),yu=Xa((function(t){return new fu(t,new hu((0,ar.Vr)()))}),[{id:"bolt"}]);var mu,vu,gu,_u,bu,Su,wu;!function(t){t.BuyNow="BUY_NOW"}(mu||(mu={})),function(t){t.AUTHORIZE="authorize",t.CAPTURE="capture"}(vu||(vu={})),function(t){t.paypal="paypal",t.checkout="checkout",t.buynow="buynow",t.pay="pay",t.installment="installment"}(gu||(gu={})),function(t){t.gold="gold",t.blue="blue",t.silver="silver",t.black="black",t.white="white"}(_u||(_u={})),function(t){t.pill="pill",t.rect="rect"}(bu||(bu={})),function(t){t.OXXO="oxxo"}(Su||(Su={})),function(t){t.Approved="APPROVED",t.Created="CREATED",t.PayerActionRequired="PAYER_ACTION_REQUIRED"}(wu||(wu={}));const Cu=function(){function t(t,e,n,r){this.formPoster=t,this.paymentIntegrationService=e,this.paypalCommerceRequestSender=n,this.paypalCommerceScriptLoader=r}return t.prototype.loadPayPalSdk=function(t,e,n){return(0,o.__awaiter)(this,void 0,void 0,(function(){var r,i,a,u;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:return r=this.paymentIntegrationService.getState(),i=e||r.getCartOrThrow().currency.code,a=r.getPaymentMethodOrThrow(t),u=this,[4,this.paypalCommerceScriptLoader.getPayPalSDK(a,i,n)];case 1:return u.paypalSdk=o.sent(),[2,this.paypalSdk]}}))}))},t.prototype.getPayPalSdkOrThrow=function(){if(!this.paypalSdk)throw new pu;return this.paypalSdk},t.prototype.createBuyNowCartOrThrow=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if(!(e=t.getBuyNowCartRequestBody()))throw new qa(Fa.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.paymentIntegrationService.createBuyNowCart(e)];case 2:return[2,n.sent()];case 3:throw n.sent(),new eu;case 4:return[2]}}))}))},t.prototype.createOrder=function(t,e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return n=this.paymentIntegrationService.getState().getCartOrThrow().id,[4,this.paypalCommerceRequestSender.createOrder(t,(0,o.__assign)({cartId:n},e))];case 1:return[2,r.sent().orderId]}}))}))},t.prototype.updateOrder=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,e,n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:t=this.paymentIntegrationService.getState(),e=t.getCartOrThrow(),n=t.getConsignmentsOrThrow()[0],r.label=1;case 1:return r.trys.push([1,3,,4]),[4,this.paypalCommerceRequestSender.updateOrder({availableShippingOptions:n.availableShippingOptions,cartId:e.id,selectedShippingOption:n.selectedShippingOption})];case 2:return r.sent(),[3,4];case 3:throw r.sent(),new c;case 4:return[2]}}))}))},t.prototype.getOrderStatus=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,this.paypalCommerceRequestSender.getOrderStatus()];case 1:return[2,t.sent().status];case 2:throw t.sent(),new c;case 3:return[2]}}))}))},t.prototype.tokenizePayment=function(t,e){var n=this.paymentIntegrationService.getState().getCartOrThrow();if(!e)throw new qa(Fa.MissingOrderId);return this.formPoster.postForm("/checkout.php",(0,o.__assign)({payment_type:"paypal",action:"set_external_checkout",provider:t,order_id:e},n.source===mu.BuyNow&&{cart_id:n.id}))},t.prototype.submitPayment=function(t,e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return n={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:t,paypal_account:{order_id:e}}},[4,this.paymentIntegrationService.submitPayment({methodId:t,paymentData:n})];case 1:return r.sent(),[2]}}))}))},t.prototype.getShippingOptionOrThrow=function(t){var e=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],n=e.availableShippingOptions||[],r=n.find((function(t){return t.isRecommended})),i=(t?n.find((function(e){return e.id===t})):n.find((function(t){var n;return t.id===(null===(n=e.selectedShippingOption)||void 0===n?void 0:n.id)})))||r||n[0];if(!i)throw new Error("Your order can't be shipped to this address");return i},t.prototype.getAddress=function(t){return{firstName:(null==t?void 0:t.firstName)||"",lastName:(null==t?void 0:t.lastName)||"",email:(null==t?void 0:t.email)||"",phone:"",company:"",address1:(null==t?void 0:t.address1)||"",address2:"",city:(null==t?void 0:t.city)||"",countryCode:(null==t?void 0:t.countryCode)||"",postalCode:(null==t?void 0:t.postalCode)||"",stateOrProvince:"",stateOrProvinceCode:(null==t?void 0:t.stateOrProvinceCode)||"",customFields:[]}},t.prototype.getBillingAddressFromOrderDetails=function(t){var e=t.payer;return this.getAddress({firstName:e.name.given_name,lastName:e.name.surname,email:e.email_address,address1:e.address.address_line_1,city:e.address.admin_area_2,countryCode:e.address.country_code,postalCode:e.address.postal_code,stateOrProvinceCode:e.address.admin_area_1})},t.prototype.getShippingAddressFromOrderDetails=function(t){var e,n,r=t.payer,i=(null===(n=null===(e=t.purchase_units[0])||void 0===e?void 0:e.shipping)||void 0===n?void 0:n.address)||{};return this.getAddress({firstName:r.name.given_name,lastName:r.name.surname,email:r.email_address,address1:i.address_line_1,city:i.admin_area_2,countryCode:i.country_code,postalCode:i.postal_code,stateOrProvinceCode:i.admin_area_1})},t.prototype.getValidButtonStyle=function(t){var e=t||{},n=e.color,r=e.height,i=e.label,o=e.shape,a={color:n&&_u[n]?n:void 0,height:this.getValidHeight(r),label:i&&gu[i]?i:void 0,shape:o&&bu[o]?o:void 0};return(0,y.omitBy)(a,y.isNil)},t.prototype.getValidHeight=function(t){return t&&"number"==typeof t?t>55?55:t<25?25:t:40},t.prototype.removeElement=function(t){var e=t&&document.getElementById(t);e&&e.remove()},t}();var Eu,Iu="This API endpoint is for internal use only and may change in the future";!function(t){t.Json="application/json",t.JsonV1="application/vnd.bc.v1+json"}(Eu||(Eu={}));const Pu=Eu;var Au={"X-Checkout-SDK-Version":"1.398.1"};const Ou=function(){function t(t){this.requestSender=t}return t.prototype.createOrder=function(t,e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r,i;return(0,o.__generator)(this,(function(a){switch(a.label){case 0:return n="/api/storefront/payment/"+t,r=e,i=(0,o.__assign)({"X-API-INTERNAL":Iu,"Content-Type":Pu.Json},Au),[4,this.requestSender.post(n,{headers:i,body:r})];case 1:return[2,a.sent().body]}}))}))},t.prototype.updateOrder=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return e=t,n=(0,o.__assign)({"X-API-INTERNAL":Iu,"Content-Type":Pu.Json},Au),[4,this.requestSender.put("/api/storefront/initialization/paypalcommerce",{headers:n,body:e})];case 1:return[2,r.sent().body]}}))}))},t.prototype.getOrderStatus=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(e){switch(e.label){case 0:return t=(0,o.__assign)({"X-API-INTERNAL":Iu,"Content-Type":Pu.Json},Au),[4,this.requestSender.get("/api/storefront/initialization/paypalcommerce",{headers:t})];case 1:return[2,e.sent().body]}}))}))},t}(),Tu=function(){function t(t){this.scriptLoader=t,this.window=window}return t.prototype.getPayPalSDK=function(t,e,n){return(0,o.__awaiter)(this,void 0,void 0,(function(){var r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:return this.paypalSdk?[3,2]:(r=this,[4,this.loadPayPalSDK(this.getPayPalSdkScriptConfigOrThrow(t,e,n))]);case 1:r.paypalSdk=i.sent(),i.label=2;case 2:return[2,this.paypalSdk]}}))}))},t.prototype.loadPayPalSDK=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(e){switch(e.label){case 0:return this.window.paypalLoadScript?[3,2]:[4,this.scriptLoader.loadScript("https://unpkg.com/@paypal/paypal-js@5.0.5/dist/iife/paypal-js.min.js",{async:!0,attributes:{}})];case 1:if(e.sent(),!this.window.paypalLoadScript)throw new pu;e.label=2;case 2:return[4,this.window.paypalLoadScript(t)];case 3:if(e.sent(),!this.window.paypal)throw new pu;return[2,this.window.paypal]}}))}))},t.prototype.getPayPalSdkScriptConfigOrThrow=function(t,e,n){void 0===n&&(n=!0);var r=t.id,i=t.clientToken,a=t.initializationData;if(!(null==a?void 0:a.clientId))throw new qa(Fa.MissingPaymentMethod);var u=a.intent,s=a.clientId,c=a.merchantId,d=a.buyerCountry,l=a.attributionId,f=a.isVenmoEnabled,p=a.isHostedCheckoutEnabled,h=a.isPayPalCreditAvailable,y=a.isDeveloperModeApplicable,m=a.availableAlternativePaymentMethods,v=void 0===m?[]:m,g=a.enabledAlternativePaymentMethods,_=void 0===g?[]:g,b=p||n,S="paypalcommercecreditcards"===r,w=S?["card"]:[],C=S?[]:["card"],E=h?["credit","paylater"]:[],I=h?[]:["credit","paylater"],P=n||!b,A=P&&f?["venmo"]:[],O=P&&f?[]:["venmo"],T=P?_:[],x=P?v.filter((function(t){return!_.includes(t)})):v,R=(0,o.__spreadArrays)(C,I,O,x),k=(0,o.__spreadArrays)(w,E,A,T);return(0,o.__assign)({"client-id":s,"data-partner-attribution-id":l,"data-client-token":i,"merchant-id":c,"enable-funding":k.length>0?k:void 0,"disable-funding":R.length>0?R:void 0,commit:b,components:["buttons","hosted-fields","messages","payment-fields"],currency:e,intent:u},y&&{"buyer-country":d})},t}(),xu=function(t){var n=t.getState().getHost;return new Cu((0,i.createFormPoster)(),t,new Ou((0,e.createRequestSender)({host:n()})),new Tu((0,ar.Vr)()))},Ru=function(){function t(t,e){this.paymentIntegrationService=t,this.paypalCommerceIntegrationService=e}return t.prototype.initialize=function(t){var e;return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r,i,a,u;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(n=t.paypalcommerce,r=t.containerId,i=t.methodId,a=Boolean(null==n?void 0:n.buyNowInitializeOptions),!i)throw new za('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new za('Unable to initialize payment because "options.containerId" argument is not provided.');if(!n)throw new za('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');if(a&&!n.currencyCode)throw new za('Unable to initialize payment because "options.paypalcommerce.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null===(e=n.buyNowInitializeOptions)||void 0===e?void 0:e.getBuyNowCartRequestBody))throw new za('Unable to initialize payment because "options.paypalcommerce.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');return a?[3,2]:[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:o.sent(),o.label=2;case 2:return u=a?n.currencyCode:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,[4,this.paypalCommerceIntegrationService.loadPayPalSdk(i,u,!1)];case 3:return o.sent(),this.renderButton(r,i,n),[2]}}))}))},t.prototype.deinitialize=function(){return Promise.resolve()},t.prototype.renderButton=function(t,e,n){var r=this,i=n.buyNowInitializeOptions,a=n.style,u=n.onComplete,s=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),c=(this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData||{}).isHostedCheckoutEnabled,d={createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommerce")},onApprove:function(t){var n=t.orderID;return r.paypalCommerceIntegrationService.tokenizePayment(e,n)}},l={onClick:function(){return r.handleClick(i)},onCancel:function(){return r.paymentIntegrationService.loadDefaultCheckout()}},f={onShippingAddressChange:function(t){return r.onShippingAddressChange(t)},onShippingOptionsChange:function(t){return r.onShippingOptionsChange(t)},onApprove:function(t,n){return r.onHostedCheckoutApprove(t,n,e,u)}},p=(0,o.__assign)((0,o.__assign)((0,o.__assign)({fundingSource:s.FUNDING.PAYPAL,style:this.paypalCommerceIntegrationService.getValidButtonStyle(a)},d),i&&l),c&&f),h=s.Buttons(p);h.isEligible()?h.render("#"+t):this.paypalCommerceIntegrationService.removeElement(t)},t.prototype.handleClick=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return t?[4,this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(t)]:[3,3];case 1:return e=n.sent(),[4,this.paymentIntegrationService.loadCheckout(e.id)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},t.prototype.onHostedCheckoutApprove=function(t,e,n,r){return(0,o.__awaiter)(this,void 0,void 0,(function(){var i,a,u,s,c,d;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(!t.orderID)throw new qa(Fa.MissingOrderId);return i=this.paymentIntegrationService.getState(),a=i.getCartOrThrow(),[4,e.order.get()];case 1:u=o.sent(),o.label=2;case 2:return o.trys.push([2,9,,10]),s=this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(u),[4,this.paymentIntegrationService.updateBillingAddress(s)];case 3:return o.sent(),a.lineItems.physicalItems.length>0?(c=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(u),[4,this.paymentIntegrationService.updateShippingAddress(c)]):[3,6];case 4:return o.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:o.sent(),o.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return o.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,t.orderID)];case 8:return o.sent(),r&&"function"==typeof r&&r(),[2,!0];case 9:throw d=o.sent(),new Error(d);case 10:return[2]}}))}))},t.prototype.onShippingAddressChange=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:e=this.paypalCommerceIntegrationService.getAddress({city:t.shippingAddress.city,countryCode:t.shippingAddress.country_code,postalCode:t.shippingAddress.postal_code,stateOrProvinceCode:t.shippingAddress.state}),i.label=1;case 1:return i.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(e)];case 2:return i.sent(),[4,this.paymentIntegrationService.updateShippingAddress(e)];case 3:return i.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return i.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return i.sent(),[3,7];case 6:throw r=i.sent(),new Error(r);case 7:return[2]}}))}))},t.prototype.onShippingOptionsChange=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(t.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(e.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:throw n=r.sent(),new Error(n);case 5:return[2]}}))}))},t}(),ku=Xa((function(t){return new Ru(t,xu(t))}),[{id:"paypalcommerce"}]),Mu=function(){function t(t,e){this.paymentIntegrationService=t,this.paypalCommerceIntegrationService=e}return t.prototype.initialize=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n,r,i,a,u,s,c,d;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(e=t.paypalcommercecredit,n=t.containerId,r=t.methodId,a=(i=e||{}).buyNowInitializeOptions,u=i.currencyCode,s=i.messagingContainerId,c=!!a,!r)throw new za('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new za('Unable to initialize payment because "options.containerId" argument is not provided.');if(!e)throw new za('Unable to initialize payment because "options.paypalcommercecredit" argument is not provided.');if(c&&!u)throw new za('Unable to initialize payment because "options.paypalcommercecredit.currencyCode" argument is not provided.');if(c&&"function"!=typeof(null==a?void 0:a.getBuyNowCartRequestBody))throw new za('Unable to initialize payment because "options.paypalcommercecredit.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');return c?[3,2]:[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:o.sent(),o.label=2;case 2:return d=c?u:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,[4,this.paypalCommerceIntegrationService.loadPayPalSdk(r,d,!1)];case 3:return o.sent(),this.renderButton(n,r,e),this.renderMessages(s),[2]}}))}))},t.prototype.deinitialize=function(){return Promise.resolve()},t.prototype.renderButton=function(t,e,n){var r=this,i=n.buyNowInitializeOptions,a=n.style,u=n.onComplete,s=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),c=(this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData||{}).isHostedCheckoutEnabled,d={createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommercecredit")},onApprove:function(t){var n=t.orderID;return r.paypalCommerceIntegrationService.tokenizePayment(e,n)}},l={onClick:function(){return r.handleClick(i)},onCancel:function(){return r.paymentIntegrationService.loadDefaultCheckout()}},f={onShippingAddressChange:function(t){return r.onShippingAddressChange(t)},onShippingOptionsChange:function(t){return r.onShippingOptionsChange(t)},onApprove:function(t,n){return r.onHostedCheckoutApprove(t,n,e,u)}},p=[s.FUNDING.PAYLATER,s.FUNDING.CREDIT],h=!1;p.forEach((function(e){if(!h){var n=(0,o.__assign)((0,o.__assign)((0,o.__assign)({fundingSource:e,style:r.paypalCommerceIntegrationService.getValidButtonStyle(a)},d),i&&l),c&&f),u=s.Buttons(n);u.isEligible()&&(u.render("#"+t),h=!0)}})),h||this.paypalCommerceIntegrationService.removeElement(t)},t.prototype.handleClick=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return t?[4,this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(t)]:[3,3];case 1:return e=n.sent(),[4,this.paymentIntegrationService.loadCheckout(e.id)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},t.prototype.onHostedCheckoutApprove=function(t,e,n,r){return(0,o.__awaiter)(this,void 0,void 0,(function(){var i,a,u,s,c,d;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(!t.orderID)throw new qa(Fa.MissingOrderId);return i=this.paymentIntegrationService.getState(),a=i.getCartOrThrow(),[4,e.order.get()];case 1:u=o.sent(),o.label=2;case 2:return o.trys.push([2,9,,10]),s=this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(u),[4,this.paymentIntegrationService.updateBillingAddress(s)];case 3:return o.sent(),a.lineItems.physicalItems.length>0?(c=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(u),[4,this.paymentIntegrationService.updateShippingAddress(c)]):[3,6];case 4:return o.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:o.sent(),o.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return o.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,t.orderID)];case 8:return o.sent(),r&&"function"==typeof r&&r(),[2,!0];case 9:throw d=o.sent(),new Error(d);case 10:return[2]}}))}))},t.prototype.onShippingAddressChange=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:e=this.paypalCommerceIntegrationService.getAddress({city:t.shippingAddress.city,countryCode:t.shippingAddress.country_code,postalCode:t.shippingAddress.postal_code,stateOrProvinceCode:t.shippingAddress.state}),i.label=1;case 1:return i.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(e)];case 2:return i.sent(),[4,this.paymentIntegrationService.updateShippingAddress(e)];case 3:return i.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return i.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return i.sent(),[3,7];case 6:throw r=i.sent(),new Error(r);case 7:return[2]}}))}))},t.prototype.onShippingOptionsChange=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(t.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(e.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:throw n=r.sent(),new Error(n);case 5:return[2]}}))}))},t.prototype.renderMessages=function(t){var e=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();if(t&&document.getElementById(t)){var n={amount:this.paymentIntegrationService.getState().getCartOrThrow().cartAmount,placement:"cart",style:{layout:"text"}};e.Messages(n).render("#"+t)}},t}(),Nu=Xa((function(t){return new Mu(t,xu(t))}),[{id:"paypalcommercecredit"}]),Du=function(){function t(t,e){this.paymentIntegrationService=t,this.paypalCommerceIntegrationService=e}return t.prototype.initialize=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n,r,i,a,u,s,c;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(e=t.paypalcommercevenmo,n=t.containerId,r=t.methodId,a=(i=e||{}).buyNowInitializeOptions,u=i.currencyCode,s=!!a,!r)throw new za('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new za('Unable to initialize payment because "options.containerId" argument is not provided.');if(!e)throw new za('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');if(s&&!u)throw new za('Unable to initialize payment because "options.paypalcommercevenmo.currencyCode" argument is not provided.');if(s&&"function"!=typeof(null==a?void 0:a.getBuyNowCartRequestBody))throw new za('Unable to initialize payment because "options.paypalcommercevenmo.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');return s?[3,2]:[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:o.sent(),o.label=2;case 2:return c=s?u:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,[4,this.paypalCommerceIntegrationService.loadPayPalSdk(r,c,!1)];case 3:return o.sent(),this.renderButton(n,r,e),[2]}}))}))},t.prototype.deinitialize=function(){return Promise.resolve()},t.prototype.renderButton=function(t,e,n){var r=this,i=n.buyNowInitializeOptions,a=n.style,u=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),s=u.FUNDING.VENMO,c={createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommercevenmo")},onApprove:function(t){var n=t.orderID;return r.paypalCommerceIntegrationService.tokenizePayment(e,n)}},d={onClick:function(){return r.handleClick(i)},onCancel:function(){return r.paymentIntegrationService.loadDefaultCheckout()}},l=(0,o.__assign)((0,o.__assign)({fundingSource:s,style:this.getValidVenmoButtonStyles(a)},c),i&&d),f=u.Buttons(l);f.isEligible()?f.render("#"+t):this.paypalCommerceIntegrationService.removeElement(t)},t.prototype.getValidVenmoButtonStyles=function(t){var e=this.paypalCommerceIntegrationService.getValidButtonStyle(t);return e.color===_u.gold?(0,o.__assign)((0,o.__assign)({},e),{color:void 0}):e},t.prototype.handleClick=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return t?[4,this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(t)]:[3,3];case 1:return e=n.sent(),[4,this.paymentIntegrationService.loadCheckout(e.id)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},t}(),Lu=Xa((function(t){return new Du(t,xu(t))}),[{id:"paypalcommercevenmo"}]),zu=function(){function t(t,e){this.paymentIntegrationService=t,this.paypalCommerceIntegrationService=e}return t.prototype.initialize=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n,r,i,a,u,s,c,d;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(e=t.paypalcommercealternativemethods,n=t.containerId,r=t.methodId,a=(i=e||{}).apm,u=i.buyNowInitializeOptions,s=i.currencyCode,c=!!u,!r)throw new za('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new za('Unable to initialize payment because "options.containerId" argument is not provided.');if(!e)throw new za('Unable to initialize payment because "options.paypalcommercealternativemethods" argument is not provided.');if(!a)throw new za('Unable to initialize payment because "options.paypalcommercealternativemethods.apm" argument is not provided.');if(c&&!s)throw new za('Unable to initialize payment because "options.paypalcommercealternativemethods.currencyCode" argument is not provided.');if(c&&"function"!=typeof(null==u?void 0:u.getBuyNowCartRequestBody))throw new za('Unable to initialize payment because "options.paypalcommercealternativemethods.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');return c?[3,2]:[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:o.sent(),o.label=2;case 2:return d=c?s:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,[4,this.paypalCommerceIntegrationService.loadPayPalSdk(r,d,!1)];case 3:return o.sent(),this.renderButton(n,r,e),[2]}}))}))},t.prototype.deinitialize=function(){return Promise.resolve()},t.prototype.renderButton=function(t,e,n){var r=this,i=n.apm,a=n.buyNowInitializeOptions,u=n.style,s=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();if(!Object.values(s.FUNDING).includes(i))throw new za('Unable to initialize PayPal button because "options.paypalcommercealternativemethods.apm" argument is not valid funding source.');var c={createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommercealternativemethod")},onApprove:function(t){var n=t.orderID;return r.paypalCommerceIntegrationService.tokenizePayment(e,n)}},d={onClick:function(){return r.handleClick(a)},onCancel:function(){return r.paymentIntegrationService.loadDefaultCheckout()}},l=(0,o.__assign)((0,o.__assign)({fundingSource:i,style:this.paypalCommerceIntegrationService.getValidButtonStyle(u)},c),a&&d),f=s.Buttons(l);f.isEligible()?f.render("#"+t):this.paypalCommerceIntegrationService.removeElement(t)},t.prototype.handleClick=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return t?[4,this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(t)]:[3,3];case 1:return e=n.sent(),[4,this.paymentIntegrationService.loadCheckout(e.id)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},t}(),ju=Xa((function(t){return new zu(t,xu(t))}),[{id:"paypalcommercealternativemethods"}]);var Uu,Fu,qu,Bu,Gu;!function(t){t.HORIZONTAL="horizontal",t.VERTICAL="vertical"}(Uu||(Uu={})),function(t){t.SMALL="small",t.MEDIUM="medium",t.LARGE="large",t.RESPONSIVE="responsive"}(Fu||(Fu={})),function(t){t.GOLD="gold",t.BLUE="blue",t.SIlVER="silver",t.BLACK="black"}(qu||(qu={})),function(t){t.CHECKOUT="checkout",t.PAY="pay",t.BUYNOW="buynow",t.PAYPAL="paypal",t.CREDIT="credit"}(Bu||(Bu={})),function(t){t.PILL="pill",t.RECT="rect"}(Gu||(Gu={}));const Vu=function(){function t(t,e,n){this.paymentIntegrationService=t,this.paypalExpressScriptLoader=e,this.formPoster=n}return t.prototype.initialize=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:if(e=this.paymentIntegrationService.getState(),n=e.getPaymentMethodOrThrow(t.methodId),!t.paypal)throw new za;if(!n.config.merchantId)throw new qa(Fa.MissingPaymentMethod);return[4,this.paypalExpressScriptLoader.loadPaypalSDK(n.config.merchantId)];case 1:return r=i.sent(),this.renderButton(t,r),[2]}}))}))},t.prototype.deinitialize=function(){return Promise.resolve()},t.prototype.renderButton=function(t,e){var n,r=this,i=t.containerId,o=t.methodId,a=t.paypal,u=a.allowCredit,s=a.clientId,c=a.onPaymentError,d=a.shouldProcessPayment,l=a.style,f=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t.methodId);if(!f.config.merchantId)throw new qa(Fa.MissingPaymentMethod);var p=f.config.merchantId,h=f.config.testMode?"sandbox":"production",y=((n={})[h]=s,n),m=e.FUNDING.CREDIT||"credit",v=u?[m]:[],g=u?[]:[m];return e.Button.render({env:h,client:y,commit:d,funding:{allowed:v,disallowed:g},style:this.getStyle(l),payment:function(t,e){return r.setupPayment(p,e,c)},onAuthorize:function(t,e){return r.tokenizePayment(t,o,e,d)}},i)},t.prototype.getStyle=function(t){var e=t||{},n=e.color,r=e.fundingicons,i=e.label,o=e.layout,a=e.shape,u=e.size,s=e.tagline;return{color:n,fundingicons:r,label:i,layout:o,shape:a||Gu.RECT,size:"small"===u?Fu.RESPONSIVE:u,tagline:s}},t.prototype.setupPayment=function(t,e,n){return(0,o.__awaiter)(this,void 0,void 0,(function(){var r,i,a,u;return(0,o.__generator)(this,(function(s){switch(s.label){case 0:if(!e)throw new Ua(ja.CheckoutButtonNotInitialized);s.label=1;case 1:return s.trys.push([1,4,,5]),[4,this.paymentIntegrationService.loadDefaultCheckout()];case 2:return r=s.sent(),i=r.getCartOrThrow().id,a=r.getHost()||"",[4,e.request.post(a+"/api/storefront/payment/paypalexpress",{merchantId:t,cartId:i},{headers:(0,o.__assign)({"X-API-INTERNAL":Iu},Au)})];case 3:return[2,s.sent().id];case 4:throw u=s.sent(),n&&n(u),u;case 5:return[2]}}))}))},t.prototype.tokenizePayment=function(t,e,n,r){return(0,o.__awaiter)(this,void 0,void 0,(function(){var i,a,u;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(!n)throw new Ua(ja.CheckoutButtonNotInitialized);if(!t.paymentID||!t.payerID)throw new qa(Fa.MissingPayment);return i=this.paymentIntegrationService.getState(),a=i.getPaymentMethodOrThrow(e),[4,n.payment.get(t.paymentID)];case 1:return u=o.sent(),[2,this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:a.id,action:r?"process_payment":"set_external_checkout",paymentId:t.paymentID,payerId:t.payerID,payerInfo:JSON.stringify(u.payer.payer_info)})]}}))}))},t}();const Yu=function(){function t(t){this.scriptLoader=t,this.window=window}return t.prototype.loadPaypalSDK=function(t){return void 0===t&&(t=""),(0,o.__awaiter)(this,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return e=(0,o.__assign)({async:!0,attributes:{"data-merchant-id":t}},t&&{attributes:{"data-merchant-id":t}}),[4,this.scriptLoader.loadScript("//www.paypalobjects.com/api/checkout.min.js",e)];case 1:if(n.sent(),!this.window.paypal)throw new pu;return[2,this.window.paypal]}}))}))},t}(),Hu=Xa((function(t){return new Vu(t,new Yu((0,ar.Vr)()),(0,i.createFormPoster)())}),[{id:"paypalexpress"}]);function Wu(n){var r=null!=n?n:{},o=r.host,a=r.locale,u=void 0===a?"en":a,s=$n(),c=(0,e.createRequestSender)({host:o}),d=(0,i.createFormPoster)({host:o}),l=function(e,n){void 0===n&&(n=t);for(var r=new Qa,i=function(t){if(!function(t){return"resolveIds"in t}(t))return"continue";for(var n=0,i=t.resolveIds;n(()=>{var t={89538:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=d(n(66534)),o=d(n(43279)),a=d(n(86202)),u=d(n(98834)),s=d(n(43961)),c=d(n(11906));function d(t){return t&&t.__esModule?t:{default:t}}function l(t){return l="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},l(t)}function f(t,e){for(var n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;e.default={host:""}},56280:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.APPLICATION_JSON=void 0,e.APPLICATION_JSON="application/json"},44955:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var r=n(56280),i=n(99338),o={headers:{Accept:r.APPLICATION_JSON,"Content-Type":r.APPLICATION_JSON},method:i.GET};e.default=o},99338:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.POST=e.GET=e.DELETE=void 0,e.GET="GET",e.POST="POST",e.DELETE="DELETE"},92197:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(5099),n(38490),n(64668),n(16368),n(99023),n(40737),n(74035),n(10951),n(58443),n(34500),n(25959),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i,o=(i=n(66534))&&i.__esModule?i:{default:i},a=n(56280),u=n(60301);function s(t){return s="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},s(t)}function c(t,e){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:a.APPLICATION_JSON;return t&&(0,u.includes)(e,a.APPLICATION_JSON)?JSON.stringify(t):t}},{key:"fromResponse",value:function(t){var e=this.parseResponseHeaders(t.getAllResponseHeaders()),n=t.getResponseHeader("Content-Type"),r=t.status,i=t.statusText,o="response"in t?t.response:t.responseText;return o&&(0,u.includes)(n,a.APPLICATION_JSON)&&(o=JSON.parse(o)),{data:o,headers:e,status:r,statusText:i}}},{key:"parseResponseHeaders",value:function(t){return(t?t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/):[]).reduce((function(t,e){var n=e.split(":"),r=(n.shift()||"").trim();return r?(0,o.default)({},t,function(t,e,n){return(e=d(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}({},r.toLowerCase(),n.join(":").trim())):t}),{})}}],r=[{key:"create",value:function(){return new t}}],n&&c(e.prototype,n),r&&c(e,r),Object.defineProperty(e,"prototype",{writable:!1}),t}();e.default=l},48773:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function o(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=d(n(18712)),o=d(n(66534)),a=n(99338),u=d(n(44955)),s=d(n(92197)),c=d(n(48773));function d(t){return t&&t.__esModule?t:{default:t}}function l(t){return l="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},l(t)}function f(t,e){for(var n=0;n=200&&t.status<300}}])&&f(e.prototype,n),r&&f(e,r),Object.defineProperty(e,"prototype",{writable:!1}),t}();e.default=p},50630:(t,e,n)=>{"use strict";n(6550),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t,e){return!(!Array.isArray(t)&&"string"!=typeof t)&&-1!==t.indexOf(e)}},60301:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"includes",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(e,"isNil",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(e,"isObject",{enumerable:!0,get:function(){return o.default}}),Object.defineProperty(e,"omitEmptyStringAndNil",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(e,"omitNil",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(e,"omitProperty",{enumerable:!0,get:function(){return s.default}}),Object.defineProperty(e,"toNumber",{enumerable:!0,get:function(){return c.default}}),Object.defineProperty(e,"toSnakeCase",{enumerable:!0,get:function(){return d.default}}),Object.defineProperty(e,"toString",{enumerable:!0,get:function(){return l.default}});var r=f(n(50630)),i=f(n(65480)),o=f(n(63387)),a=f(n(91145)),u=f(n(75750)),s=f(n(66206)),c=f(n(30439)),d=f(n(27302)),l=f(n(78267));function f(t){return t&&t.__esModule?t:{default:t}}},57457:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return""===t}},32713:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return(0,r.default)(t)||(0,i.default)(t)};var r=o(n(57457)),i=o(n(65480));function o(t){return t&&t.__esModule?t:{default:t}}},65480:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return null==t}},63387:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}n(93942),n(70472),n(93270),n(38490),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return null!==t&&"object"===i(t)&&!Array.isArray(t)}},91145:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return(0,i.default)(t,r.default)};var r=o(n(32713)),i=o(n(66206));function o(t){return t&&t.__esModule?t:{default:t}}},75750:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return(0,i.default)(t,r.default)};var r=o(n(65480)),i=o(n(66206));function o(t){return t&&t.__esModule?t:{default:t}}},66206:(t,e,n)=>{"use strict";n(13722),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t,e){return(0,i.default)(t)?Object.keys(t).reduce((function(n,r){var i=t[r];return e(i)||(n[r]=i),n}),{}):t};var r,i=(r=n(63387))&&r.__esModule?r:{default:r}},30439:(t,e,n)=>{"use strict";n(83681),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return parseFloat(t)||0}},27302:(t,e,n)=>{"use strict";n(58443),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return"string"!=typeof t?t:t.replace(/([a-z\d])([A-Z]+)/g,"$1_$2").replace(/[-\s]+/g,"_").toLowerCase()}},78267:(t,e,n)=>{"use strict";n(99023),n(80226),n(40737),n(26667),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return"string"==typeof t?t:"number"!=typeof t||Number.isNaN(t)?"":t.toString()}},36438:(t,e,n)=>{"use strict";e.e=function(t){return i.default.create(t)};var r,i=(r=n(89538))&&r.__esModule?r:{default:r}},98834:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=u(n(14735)),o=u(n(15859)),a=u(n(92239));function u(t){return t&&t.__esModule?t:{default:t}}function s(t){return s="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},s(t)}function c(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(13751),o=n(7969),a=s(n(14088)),u=s(n(92239));function s(t){return t&&t.__esModule?t:{default:t}}function c(t){return c="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},c(t)}function d(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e,n){return(e=s(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function u(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(34745),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(26667),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=l(n(66534)),o=n(60301),a=l(n(45860)),u=l(n(31146)),s=l(n(8006)),c=l(n(80720)),d=l(n(85064));function l(t){return t&&t.__esModule?t:{default:t}}function f(t){return f="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},f(t)}function p(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(26667),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.PAYPAL_COMMERCE_VENMO=e.PAYPAL_COMMERCE_CREDIT_CARDS=e.PAYPAL_COMMERCE_CREDIT=e.PAYPAL_COMMERCE_ALTERNATIVE_METHODS=e.PAYPAL_COMMERCE=e.BRAINTREE_VISACHECKOUT=e.BRAINTREE_PAYPAL_CREDIT=e.BRAINTREE_PAYPAL=e.BRAINTREE_LOCAL_METHODS=e.BRAINTREE_GOOGLEPAY=e.BRAINTREE_ACH=e.BRAINTREE=void 0,e.BRAINTREE="braintree",e.BRAINTREE_PAYPAL="braintreepaypal",e.BRAINTREE_PAYPAL_CREDIT="braintreepaypalcredit",e.BRAINTREE_VISACHECKOUT="braintreevisacheckout",e.BRAINTREE_LOCAL_METHODS="braintreelocalmethods",e.BRAINTREE_GOOGLEPAY="googlepaybraintree",e.BRAINTREE_ACH="braintreeach",e.PAYPAL_COMMERCE="paypalcommerce",e.PAYPAL_COMMERCE_ALTERNATIVE_METHODS="paypalcommercealternativemethods",e.PAYPAL_COMMERCE_CREDIT="paypalcommercecredit",e.PAYPAL_COMMERCE_CREDIT_CARDS="paypalcommercecreditcards",e.PAYPAL_COMMERCE_VENMO="paypalcommercevenmo"},80720:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(9257),o=n(86879);function a(t){return a="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},a(t)}function u(t,e){for(var n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.PPSDK_CREDIT_CARD=e.MULTI_OPTION=e.CREDIT_CARD=void 0,e.CREDIT_CARD="credit-card",e.MULTI_OPTION="multi-option",e.PPSDK_CREDIT_CARD="card"},86202:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=c(n(14735)),o=n(7969),a=c(n(86130)),u=c(n(22147)),s=c(n(92239));function c(t){return t&&t.__esModule?t:{default:t}}function d(t){return d="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},d(t)}function l(t,e){for(var n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.SDK=e.OFFLINE=e.HOSTED=e.API=void 0,e.API="PAYMENT_TYPE_API",e.HOSTED="PAYMENT_TYPE_HOSTED",e.OFFLINE="PAYMENT_TYPE_OFFLINE",e.SDK="PAYMENT_TYPE_SDK"},22147:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301),o=n(9257);function a(t){return a="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},a(t)}function u(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function o(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(26667),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(95412),n(16368),n(34745),n(99023),n(40737),n(26667),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301),o=c(n(43085)),a=c(n(11106)),u=c(n(47752)),s=c(n(58332));function c(t){return t&&t.__esModule?t:{default:t}}function d(t){return d="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},d(t)}function l(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=u(n(66534)),o=n(60301),a=u(n(80720));function u(t){return t&&t.__esModule?t:{default:t}}function s(t){return s="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},s(t)}function c(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(26667),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(95412),n(16368),n(34745),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301),o=c(n(45873)),a=c(n(43026)),u=c(n(70170)),s=c(n(23393));function c(t){return t&&t.__esModule?t:{default:t}}function d(t){return d="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},d(t)}function l(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i,o=n(60301),a=(i=n(80720))&&i.__esModule?i:{default:i};function u(t){return u="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},u(t)}function s(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=s(n(14735)),o=n(99338),a=s(n(25682)),u=n(68109);function s(t){return t&&t.__esModule?t:{default:t}}function c(t){return c="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},c(t)}function d(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function o(t,e){for(var n=0;n{"use strict";n(95412),Object.defineProperty(e,"__esModule",{value:!0}),e.mapToHeaders=function(){var t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).authToken;return(0,r.omitNil)({Authorization:t})},e.mapToInstrumentPayload=function(){var t,e,n,o,a=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},u=a.providerName,s=a.defaultInstrument,c=(0,r.omitNil)({name:u});return(0,r.omitNil)({provider:c,credit_card:(t=a,e=t.creditCard,n=void 0===e?{}:e,o=(0,r.omitNil)(n.threeDSecure),(0,r.omitNil)({cardholder_name:n.cardholderName,number:n.number,month:n.month,year:n.year,verification_code:n.verificationCode,issue_month:n.issueMonth,issue_year:n.issueYear,issue_number:n.issueNumber,track_data:n.trackData,is_manual_entry:n.isManualEntry,icc_data:n.iccData,fallback_reason:n.fallbackReason,is_contactless:n.isContactless,encrypted_pin_cryptogram:n.encryptedPinCryptogram,encrypted_pin_ksn:n.encryptedPinKsn,three_d_secure:o})),billing_address:i(a.billingAddress),default_instrument:s})},e.mapToTrustedShippingAddressPayload=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Array.isArray(t.shippingAddress)?(0,r.omitNil)({shipping_addresses:t.shippingAddress.map((function(t){return i(t)}))}):(0,r.omitNil)({shipping_address:i(t.shippingAddress)})};var r=n(60301);function i(){var t,e,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=(t=n.provinceCode,e=n.province,(0,r.omitNil)({code:t,name:e}));return(0,r.omitNil)({address_line_1:n.addressLine1,address_line_2:n.addressLine2,city:n.city,company:n.company,country_code:n.countryCode,email:n.email,first_name:n.firstName,last_name:n.lastName,phone:n.phone,postal_code:n.postCode,state:i})}},119:(t,e,n)=>{"use strict";n(13722),Object.defineProperty(e,"__esModule",{value:!0});var r=n(87275),i=n(10874);e.default=function(t,e){var n=(e||{}).equalityCheck,o=void 0===n?i:n;return function(e,n){return Object.keys(t).reduce((function(i,a){var u,s=t[a],c=e?e[a]:void 0,d=s(c,n);return o(c,d)&&i?i:r.assign({},i,((u={})[a]=d,u))}),e||{})}}},50538:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(51725),n(38490),n(95412),n(16516),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0});var i=n(61699),o=n(87275),a=n(10874);e.default=function(){for(var t=[],e=0;e{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(61699),i=n(87275);e.default=function(t,e,n){if("string"!=typeof t||""===t)throw new Error("`type` must be a string");return r.__assign({type:t},i.omitBy({payload:e,meta:n},(function(t){return void 0===t})))}},17372:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(119),i=n(58941);e.default=function(t,e,n){return"function"==typeof t?new i.default(t,e,n):new i.default(r.default(t,{equalityCheck:n&&n.equalityCheck}),e,n)}},13304:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(61699),i=n(10520);e.default=function(t,e,n){return r.__assign({},i.default(t,e,n),{error:!0})}},58941:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(51725),n(38490),n(95412),n(40737),n(83823),n(10951),n(71806),n(5193),Object.defineProperty(e,"__esModule",{value:!0});var i=n(61699),o=n(87275),a=n(57469),u=n(11065),s=n(10874),c=n(35580),d=n(35643),l=n(25151),f=n(32168),p=function(){function t(t,e,n){void 0===e&&(e={});var r=this;this._reducer=t,this._options=i.__assign({actionTransformer:l.default,equalityCheck:s,shouldWarnMutation:!0,stateTransformer:f.default},n),this._state$=new a.BehaviorSubject(this._options.stateTransformer(e)),this._notification$=new a.Subject,this._dispatchers={},this._dispatchQueue$=new a.Subject,this._errors={},this._dispatchQueue$.pipe(u.mergeMap((function(t){return t.pipe(u.concatMap((function(t){return t})))})),u.filter((function(t){return!!t.type})),u.scan((function(t,e){return r._transformStates(t,e)}),{state:e,transformedState:this._state$.getValue()}),u.distinctUntilChanged((function(t,e){var n=t.state,i=e.state;return r._options.equalityCheck(n,i)})),u.map((function(t){return t.transformedState}))).subscribe(this._state$),this.dispatch({type:"INIT"})}return t.prototype.dispatch=function(t,e){return d.default(t)?this._dispatchObservableAction(t,e):"function"==typeof t?this._dispatchThunkAction(t,e):this._dispatchAction(t)},t.prototype.getState=function(){return this._state$.getValue()},t.prototype.notifyState=function(){this._notification$.next(this.getState())},t.prototype.subscribe=function(t){for(var e=this,n=[],i=1;i0&&(s=s.pipe(u.distinctUntilChanged((function(t,n){return a.every((function(r){return e._options.equalityCheck(r(t),r(n))}))})))),o&&!1===o.initial&&(s=s.pipe(u.skip(1)));var c=[s.subscribe(t),this._notification$.subscribe(t)];return function(){return c.forEach((function(t){return t.unsubscribe()}))}},t.prototype._transformStates=function(t,e){try{var n=!1===this._options.shouldWarnMutation?this._reducer(t.state,e):c.default(this._reducer(t.state,e),{equalityCheck:this._options.equalityCheck,previousValue:t.state});return{state:n,transformedState:this._options.stateTransformer(n)}}catch(n){return this._getDispatchError(e.meta&&e.meta.queueId).next(n),{state:t.state,transformedState:t.transformedState}}},t.prototype._dispatchAction=function(t){return this._dispatchObservableAction(t.error?a.throwError(t):a.of(t))},t.prototype._dispatchObservableAction=function(t,e){var n=this;return void 0===e&&(e={}),new Promise((function(r,i){var s=n._getDispatchError(e.queueId),c=n._options.actionTransformer(a.from(t).pipe(u.map((function(t){return e.queueId?o.merge({},t,{meta:{queueId:e.queueId}}):t}))));n._getDispatcher(e.queueId).next(a.from(c).pipe(u.map((function(t,e){return 0===e&&s.pipe(u.first()).subscribe(i),t.error&&i(t.payload),t})),u.catchError((function(t){return i(t instanceof Error?t:t.payload),a.of(t)})),u.tap({complete:function(){r(n.getState())}})))}))},t.prototype._dispatchThunkAction=function(t,e){var n=this;return void 0===e&&(e={}),this._dispatchObservableAction(a.defer((function(){return t(n)})),e)},t.prototype._getDispatcher=function(t){return void 0===t&&(t="default"),this._dispatchers[t]||(this._dispatchers[t]=new a.Subject,this._dispatchQueue$.next(this._dispatchers[t])),this._dispatchers[t]},t.prototype._getDispatchError=function(t){return void 0===t&&(t="default"),this._errors[t]||(this._errors[t]=new a.Subject),this._errors[t]},t}();e.default=p},35580:(t,e,n)=>{"use strict";n(95412),n(33409),n(60678),n(97814),Object.defineProperty(e,"__esModule",{value:!0});var r=n(87275),i=n(10874);e.default=function t(e,n){try{var o=n||{},a=o.equalityCheck,u=void 0===a?i:a,s=o.previousValue,c=void 0===s?null:s;return u(e,c)&&Object.isFrozen(c)?c:Object.isFrozen(e)||!Array.isArray(e)&&!r.isPlainObject(e)?e:Array.isArray(e)?Object.freeze(e.map((function(e,n){return t(e,{equalityCheck:u,previousValue:Array.isArray(c)?c[n]:void 0})}))):Object.freeze(Object.getOwnPropertyNames(e).reduce((function(n,r){return n[r]=t(e[r],{equalityCheck:u,previousValue:c&&c.hasOwnProperty(r)?c[r]:void 0}),n}),{}))}catch(t){if(t instanceof TypeError)return e;throw t}}},45346:(t,e,n)=>{"use strict";n(58941).default;var r=n(119);e.UY=r.default;var i=n(50538);e.g0=i.default;var o=n(10520);e.PH=o.default;var a=n(17372);e.Mg=a.default;var u=n(13304);e.bR=u.default;var s=n(35580);e._A=s.default},35643:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return"function"==typeof t.subscribe||"function"==typeof t.then}},25151:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return t}},32168:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return t}},78545:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(11077),i=n(51243);e.default=function(t){var e=new r.default;return new i.default(e,t)}},11077:(t,e,n)=>{"use strict";n(13722),n(71806),Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(){}return t.prototype.build=function(t,e,n){var r=this,i=document.createElement("form");return i.style.display="none",i.setAttribute("action",t),i.setAttribute("method","POST"),i.setAttribute("target",n||"_top"),Object.keys(e).forEach((function(t){var n=e[t];i.appendChild(r._createInput(n,t))})),i},t.prototype._createInput=function(t,e){var n=document.createElement("input");return n.setAttribute("name",e),n.setAttribute("type","hidden"),n.setAttribute("value",t),n},t}();e.default=r},51243:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(73543),i=function(){function t(t,e){this._formBuilder=t,this._options=e}return t.prototype.postForm=function(t,e,n,r){var i=this._formBuilder.build(this._prependHost(t),e,r);window.addEventListener("unload",(function t(){window.removeEventListener("unload",t),n&&n()})),document.body.appendChild(i),i.submit(),document.body.removeChild(i)},t.prototype._prependHost=function(t){return this._options&&this._options.host&&!r.isAbsoluteUrl(t)?r.joinPaths(this._options.host,t):t},t}();e.default=i},13751:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(78545);e.createFormPoster=r.default;var i=n(51243);e.FormPoster=i.default},73543:(t,e,n)=>{"use strict";n(58443),Object.defineProperty(e,"__esModule",{value:!0}),e.isAbsoluteUrl=function(t){return/^https?:\/\//.test(t)},e.joinPaths=function(t,e){return t.replace(/\/$/,"")+"/"+e.replace(/^\//,"")}},65934:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.isTerminalCacheKeyMap=function(t){return t.hasOwnProperty("cacheKey")},e.isRootCacheKeyMap=function(t){return t.hasOwnProperty("parentMap")}},67959:(t,e,n)=>{"use strict";n(6550),n(95412),n(16516),n(32345),Object.defineProperty(e,"__esModule",{value:!0});var r=n(61699),i=n(87275),o=r.__importDefault(n(10874)),a=n(65934),u=function(){function t(t){this._lastId=0,this._map={maps:[]},this._usedMaps=[],this._options=r.__assign({isEqual:o.default,maxSize:0,onExpire:i.noop},t)}return t.prototype.getKey=function(){for(var t=[],e=0;e{"use strict";var r=n(78497);e.HP=r.default,e.qe=r.memoizeOne},78497:(t,e,n)=>{"use strict";n(38490),n(34897),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0});var r=n(61699),i=r.__importDefault(n(84026)),o=r.__importDefault(n(10874)),a=r.__importDefault(n(67959));function u(t,e){var n=r.__assign({maxSize:0,isEqual:o.default},e),u=n.maxSize,s=n.isEqual,c=new Map,d=new a.default({isEqual:s,maxSize:u,onExpire:function(t){return c.delete(t)}}),l=i.default(t,(function(){for(var t=[],e=0;e{"use strict";n.d(e,{v:()=>i}),n(13722);var r=n(52163),i=function(){function t(){this._cache={}}return t.prototype.read=function(t,e){var n=this.getKey(t,e.params);return this._cache[n]||null},t.prototype.write=function(t,e,n){var r=this.getKey(t,e.params);this._cache[r]=n},t.prototype.getKey=function(t,e){return void 0===e&&(e={}),0===Object.keys(e).length?t:t+"?"+r.Pz(e)},t}()},78128:(t,e,n)=>{"use strict";n.d(e,{Z:()=>u});var r=n(53028),i=n(70613),o=n(44169),a=n(73185);function u(t){return new a.Z(new o.Z,new i.Z,r,t)}},98215:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i});var r=n(88287);function i(t){return new r.Z(t)}},14121:(t,e,n)=>{"use strict";n.r(e),n.d(e,{RequestSender:()=>o.Z,Timeout:()=>a.Z,createRequestSender:()=>r.Z,createTimeout:()=>i.Z});var r=n(78128),i=n(98215),o=n(73185),a=n(88287)},16927:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function i(t){return!!t&&("object"===r(t)||"function"==typeof t)&&"function"==typeof t.then}n.d(e,{Z:()=>i}),n(93942),n(70472),n(93270),n(38490),n(40737),n(10951),n(5193)},70613:(t,e,n)=>{"use strict";n.d(e,{Z:()=>u}),n(64668),n(58443),n(34500),n(25959);var r=n(61699),i=n(75457),o=/application\/(\w+\+)?json/,a=/application\/x-www-form-urlencoded/;const u=function(){function t(){}return t.prototype.toRequestBody=function(t){var e=t.headers?this._getHeader(t.headers,"Content-Type"):"";if(t.body){if(o.test(e))return JSON.stringify(t.body);if(a.test(e))return(0,i.Z)(t.body)}return t.body},t.prototype.toResponse=function(t){var e=this._parseResponseHeaders(t.getAllResponseHeaders());return{body:this._parseResponseBody("response"in t?t.response:t.responseText,e),headers:e,status:t.status,statusText:t.statusText}},t.prototype._parseResponseBody=function(t,e){var n=this._getHeader(e,"Content-Type");return t&&o.test(n)?JSON.parse(t):t},t.prototype._parseResponseHeaders=function(t){return(t?t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/):[]).reduce((function(t,e){var n,i=e.split(":"),o=(i.shift()||"").trim();return o?(0,r.__assign)((0,r.__assign)({},t),((n={})[o.toLowerCase()]=i.join(":").trim(),n)):t}),{})},t.prototype._getHeader=function(t,e){return t&&e&&(t[e]||t[e.toLowerCase()])||""},t}()},44169:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i}),n(51725),n(13722),n(71806);var r=n(52163);const i=function(){function t(){}return t.prototype.createRequest=function(t,e){var n=new XMLHttpRequest;return this._configureRequest(n,t,e),n},t.prototype._configureRequest=function(t,e,n){void 0===n&&(n={}),t.open(n.method||"GET",this._formatUrl(e,n.params,n.encodeParams),!0),n.headers&&this._configureRequestHeaders(t,n.headers),"boolean"==typeof n.credentials&&(t.withCredentials=n.credentials),"number"==typeof n.timeout&&(t.timeout=n.timeout)},t.prototype._configureRequestHeaders=function(t,e){Object.keys(e).filter((function(t){return null!==e[t]})).forEach((function(n){t.setRequestHeader(n,e[n])}))},t.prototype._formatUrl=function(t,e,n){return void 0===n&&(n=!0),e&&0!==Object.keys(e).length?t+"?"+r.Pz(e,{encode:n}):t},t}()},73185:(t,e,n)=>{"use strict";n.d(e,{Z:()=>c}),n(40737),n(83823),n(58443),n(34500);var r=n(61699),i=n(59947),o=n.n(i),a=n(90956),u=n(16927),s=n(88287);const c=function(){function t(t,e,n,r){void 0===r&&(r={}),this._requestFactory=t,this._payloadTransformer=e,this._cookie=n,this._options=r,this._cache=this._options.cache||new a.v}return t.prototype.sendRequest=function(t,e){var n=this,r=this._mergeDefaultOptions(t,e),i=this._getCachedRequest(t,r);if(i)return Promise.resolve(i);var o=this._requestFactory.createRequest(this._prependHost(t),r);return new Promise((function(e,i){var a=function(){var a=n._payloadTransformer.toResponse(o);a.status>=200&&a.status<300?(n._cacheRequest(t,r,a),e(a)):i(a)};o.onload=a,o.onerror=a,o.onabort=a,o.ontimeout=a,r.timeout instanceof s.Z&&(r.timeout.onComplete((function(){return o.abort()})),r.timeout.start()),(0,u.Z)(r.timeout)&&r.timeout.then((function(){return o.abort()})),o.send(n._payloadTransformer.toRequestBody(r))}))},t.prototype.get=function(t,e){return this.sendRequest(t,(0,r.__assign)((0,r.__assign)({},e),{method:"GET"}))},t.prototype.post=function(t,e){return this.sendRequest(t,(0,r.__assign)((0,r.__assign)({},e),{method:"POST"}))},t.prototype.put=function(t,e){return this.sendRequest(t,(0,r.__assign)((0,r.__assign)({},e),{method:"PUT"}))},t.prototype.patch=function(t,e){return this.sendRequest(t,(0,r.__assign)((0,r.__assign)({},e),{method:"PATCH"}))},t.prototype.delete=function(t,e){return this.sendRequest(t,(0,r.__assign)((0,r.__assign)({},e),{method:"DELETE"}))},t.prototype._mergeDefaultOptions=function(t,e){var n={credentials:!0,encodeParams:!0,headers:{Accept:"application/json, text/plain, */*"},method:"GET"},r=this._cookie.get("XSRF-TOKEN");return r&&n.headers&&!this._isAssetRequest(t,e)&&(n.headers["X-XSRF-TOKEN"]=r),e&&e.body&&n.headers&&(n.headers["Content-Type"]="application/json"),o()({},n,e)},t.prototype._prependHost=function(t){return!this._options.host||/^https?:\/\//.test(t)?t:this._options.host.replace(/\/$/,"")+"/"+t.replace(/^\//,"")},t.prototype._shouldCacheRequest=function(t){return"GET"===(t.method||"GET").toUpperCase()&&Boolean(t.cache)},t.prototype._getCachedRequest=function(t,e){return this._shouldCacheRequest(e)?this._cache.read(t,e):null},t.prototype._cacheRequest=function(t,e,n){this._shouldCacheRequest(e)&&this._cache.write(t,e,n)},t.prototype._isAssetRequest=function(t,e){return(!e||!e.method||"GET"===e.method.toUpperCase())&&/\.(png|gif|jpe?g|css|js|json|svg|html?)$/.test(t.split("?")[0])},t}()},88287:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r}),n(40737),n(83823);const r=function(){function t(t){var e=this;this._delay=t,this._resolve=function(){},this._promise=new Promise((function(t){e._resolve=t}))}return t.prototype.onComplete=function(t){this._promise.then(t)},t.prototype.complete=function(){this._resolve(),this._timeoutToken&&window.clearTimeout(this._timeoutToken)},t.prototype.start=function(){var t=this;this._delay&&(this._timeoutToken=window.setTimeout((function(){return t.complete()}),this._delay))},t}()},75457:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function i(t){return"object"!==r(t)||null===t?t:Object.keys(t).filter((function(e){return void 0!==t[e]})).map((function(e){var n=t[e];return"string"==typeof n?e+"="+encodeURIComponent(n):e+"="+encodeURIComponent(JSON.stringify(n)||"")})).join("&")}n.d(e,{Z:()=>i}),n(93942),n(70472),n(93270),n(51725),n(38490),n(64668),n(95412),n(13722),n(40737),n(10951),n(5193)},52163:(t,e,n)=>{"use strict";n(93942),n(70472),n(93270),n(88033),n(51725),n(6550),n(38490),n(64668),n(95412),n(16516),n(2934),n(99023),n(13722),n(40737),n(10951),n(58443),n(34500),n(25959),n(71806),n(5193);var r=n(29590),i=n(66534);n(99684);function o(t,e){return e.encode?e.strict?r(t):encodeURIComponent(t):t}e.Pz=function(t,e){!1===(e=i({encode:!0,strict:!0,arrayFormat:"none"},e)).sort&&(e.sort=function(){});var n=function(t){switch(t.arrayFormat){case"index":return function(e,n,r){return null===n?[o(e,t),"[",r,"]"].join(""):[o(e,t),"[",o(r,t),"]=",o(n,t)].join("")};case"bracket":return function(e,n){return null===n?o(e,t):[o(e,t),"[]=",o(n,t)].join("")};default:return function(e,n){return null===n?o(e,t):[o(e,t),"=",o(n,t)].join("")}}}(e);return t?Object.keys(t).sort(e.sort).map((function(r){var i=t[r];if(void 0===i)return"";if(null===i)return o(r,e);if(Array.isArray(i)){var a=[];return i.slice().forEach((function(t){void 0!==t&&a.push(n(r,t,a.length))})),a.join("&")}return o(r,e)+"="+o(i,e)})).filter((function(t){return t.length>0})).join("&"):""}},42372:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(){}return t.prototype.canSupportRel=function(t){var e=document.createElement("link");return!!(e.relList&&e.relList.supports&&e.relList.supports(t))},t}();e.default=n},30799:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(14121),i=n(42372),o=n(89379);e.default=function(){return new o.default(new i.default,r.createRequestSender())}},83116:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(14121),i=n(42372),o=n(41583);e.default=function(){return new o.default(new i.default,r.createRequestSender())}},57537:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=n(30799);e.default=function(){return r||(r=i.default()),r}},59136:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=n(83116);e.default=function(){return r||(r=i.default()),r}},56046:(t,e,n)=>{"use strict";n(89379).default;var r=n(30799);e.VD=r.default;var i=n(57537);e.Vr=i.default,n(41583).default,n(83116).default,n(59136).default},89379:(t,e,n)=>{"use strict";n(38490),n(95412),n(13722),n(40737),n(83823),n(10951),n(71806),n(5193),Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){this._browserSupport=t,this._requestSender=e,this._scripts={},this._preloadedScripts={}}return t.prototype.loadScript=function(t,e){var n=this;return this._scripts[t]||(this._scripts[t]=new Promise((function(r,i){var o=document.createElement("script"),a=e||{},u=a.async,s=void 0!==u&&u,c=a.attributes,d=void 0===c?{}:c;Object.keys(d).forEach((function(t){o.setAttribute(t,d[t])})),o.onload=function(){return r()},o.onreadystatechange=function(){return r()},o.onerror=function(e){delete n._scripts[t],i(e)},o.async=s,o.src=t,document.body.appendChild(o)}))),this._scripts[t]},t.prototype.loadScripts=function(t,e){var n=this;return Promise.all(t.map((function(t){return n.loadScript(t,e)}))).then((function(){}))},t.prototype.preloadScript=function(t,e){var n=this;return this._preloadedScripts[t]||(this._preloadedScripts[t]=new Promise((function(r,i){var o=(e||{}).prefetch,a=void 0!==o&&o?"prefetch":"preload";if(n._browserSupport.canSupportRel(a)){var u=document.createElement("link");u.as="script",u.rel=a,u.href=t,u.onload=function(){r()},u.onerror=function(){delete n._preloadedScripts[t],i()},document.head.appendChild(u)}else n._requestSender.get(t,{credentials:!1,headers:{Accept:"application/javascript"}}).then((function(){return r()})).catch(i)}))),this._preloadedScripts[t]},t.prototype.preloadScripts=function(t,e){var n=this;return Promise.all(t.map((function(t){return n.preloadScript(t,e)}))).then((function(){}))},t}();e.default=r},41583:(t,e,n)=>{"use strict";n(38490),n(95412),n(13722),n(40737),n(83823),n(10951),n(71806),n(5193),Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){this._browserSupport=t,this._requestSender=e,this._stylesheets={},this._preloadedStylesheets={}}return t.prototype.loadStylesheet=function(t,e){var n=this;return this._stylesheets[t]||(this._stylesheets[t]=new Promise((function(r,i){var o=document.createElement("link"),a=e||{},u=a.prepend,s=void 0!==u&&u,c=a.attributes,d=void 0===c?{}:c;Object.keys(d).forEach((function(t){o.setAttribute(t,d[t])})),o.onload=function(){return r()},o.onerror=function(e){delete n._stylesheets[t],i(e)},o.rel="stylesheet",o.href=t,s&&document.head.children[0]?document.head.insertBefore(o,document.head.children[0]):document.head.appendChild(o)}))),this._stylesheets[t]},t.prototype.loadStylesheets=function(t,e){var n=this;return Promise.all(t.map((function(t){return n.loadStylesheet(t,e)}))).then((function(){}))},t.prototype.preloadStylesheet=function(t,e){var n=this;return this._preloadedStylesheets[t]||(this._preloadedStylesheets[t]=new Promise((function(r,i){var o=(e||{}).prefetch,a=void 0!==o&&o,u=a?"prefetch":"preload";if(n._browserSupport.canSupportRel(u)){var s=document.createElement("link");s.as="style",s.rel=a?"prefetch":"preload",s.href=t,s.onload=function(){r()},s.onerror=function(e){delete n._preloadedStylesheets[t],i(e)},document.head.appendChild(s)}else n._requestSender.get(t,{credentials:!1,headers:{Accept:"text/css"}}).then((function(){return r()})).catch(i)}))),this._preloadedStylesheets[t]},t.prototype.preloadStylesheets=function(t,e){var n=this;return Promise.all(t.map((function(t){return n.preloadStylesheet(t,e)}))).then((function(){}))},t}();e.default=r},67061:(t,e,n)=>{"use strict";t.exports={number:n(9428),expirationDate:n(10370),expirationMonth:n(86075),expirationYear:n(34005),cvv:n(56348),postalCode:n(46887),creditCardType:n(56897)}},9428:(t,e,n)=>{"use strict";n(58443);var r=n(54442),i=n(56897);function o(t,e,n){return{card:t,isPotentiallyValid:e,isValid:n}}t.exports=function(t,e){var n,a,u,s,c;if(e=e||{},"number"==typeof t&&(t=String(t)),"string"!=typeof t)return o(null,!1,!1);if(t=t.replace(/\-|\s/g,""),!/^\d*$/.test(t))return o(null,!1,!1);if(0===(n=i(t)).length)return o(null,!1,!1);if(1!==n.length)return o(null,!0,!1);if(a=n[0],e.maxLength&&t.length>e.maxLength)return o(a,!1,!1);for(u=a.type===i.types.UNIONPAY&&!0!==e.luhnValidateUnionPay||r(t),c=Math.max.apply(null,a.lengths),e.maxLength&&(c=Math.min(e.maxLength,c)),s=0;s{"use strict";function e(t,e){return{isValid:t,isPotentiallyValid:e}}t.exports=function(t,n){return n=(n=n||3)instanceof Array?n:[n],"string"!=typeof t?e(!1,!1):/^\d*$/.test(t)?function(t,e){for(var n=0;nfunction(t){for(var e=3,n=0;ne?t[n]:e;return e}(n)?e(!1,!1):e(!0,!0):e(!1,!1)}},10370:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(38490),n(40737),n(10951),n(58443),n(5193);var i=n(30443),o=n(86075),a=n(34005);function u(t,e,n,r){return{isValid:t,isPotentiallyValid:e,month:n,year:r}}t.exports=function(t,e){var n,s,c,d;if("string"==typeof t)t=t.replace(/^(\d\d) (\d\d(\d\d)?)$/,"$1/$2"),n=i(t);else{if(null===t||"object"!==r(t))return u(!1,!1,null,null);n={month:String(t.month),year:String(t.year)}}if(s=o(n.month),c=a(n.year,e),s.isValid){if(c.isCurrentYear)return u(d=s.isValidForThisYear,d,n.month,n.year);if(c.isValid)return u(!0,!0,n.month,n.year)}return s.isPotentiallyValid&&c.isPotentiallyValid?u(!1,!0,null,null):u(!1,!1,null,null)}},86075:(t,e,n)=>{"use strict";function r(t,e,n){return{isValid:t,isPotentiallyValid:e,isValidForThisYear:n||!1}}n(50633),n(58443),t.exports=function(t){var e,n,i=(new Date).getMonth()+1;return"string"!=typeof t?r(!1,!1):""===t.replace(/\s/g,"")||"0"===t?r(!1,!0):/^\d*$/.test(t)?(e=parseInt(t,10),isNaN(t)?r(!1,!1):r(n=e>0&&e<13,n,n&&e>=i)):r(!1,!1)}},34005:(t,e,n)=>{"use strict";n(16516),n(99023),n(50633),n(58443);function r(t,e,n){return{isValid:t,isPotentiallyValid:e,isCurrentYear:n||!1}}t.exports=function(t,e){var n,i,o,a,u;return e=e||19,"string"!=typeof t?r(!1,!1):""===t.replace(/\s/g,"")?r(!1,!0):/^\d*$/.test(t)?(i=t.length)<2?r(!1,!0):(n=(new Date).getFullYear(),3===i?r(!1,t.slice(0,2)===String(n).slice(0,2)):i>4?r(!1,!1):(t=parseInt(t,10),o=Number(String(n).substr(2,2)),2===i?(u=o===t,a=t>=o&&t<=o+e):4===i&&(u=n===t,a=t>=n&&t<=n+e),r(a,a,u))):r(!1,!1)}},16108:(t,e,n)=>{"use strict";n(40737),n(26667),t.exports=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},54442:(t,e,n)=>{"use strict";n(50633),t.exports=function(t){for(var e,n=0,r=!1,i=t.length-1;i>=0;)e=parseInt(t.charAt(i),10),r&&(e*=2)>9&&(e=e%10+1),r=!r,n+=e,i--;return n%10==0}},30443:(t,e,n)=>{"use strict";n(64668),n(72590),n(16516),n(99023),n(34500);var r=n(34005),i=n(16108);t.exports=function(t){var e,n,o,a,u;return/^\d{4}-\d{1,2}$/.test(t)?t=t.split("-").reverse():/\//.test(t)?t=t.split(/\s*\/\s*/g):/\s/.test(t)&&(t=t.split(/ +/g)),i(t)?{month:t[0]||"",year:t.slice(1).join()}:(o=t,n=0===(u=Number(o[0]))?2:u>1||1===u&&Number(o[1])>2?1:1===u?(a=o.substr(1),r(a).isPotentiallyValid?1:2):5===o.length?1:o.length>5?2:1,{month:e=t.substr(0,n),year:t.substr(e.length)})}},46887:t=>{"use strict";function e(t,e){return{isValid:t,isPotentiallyValid:e}}t.exports=function(t,n){var r;return r=(n=n||{}).minLength||3,"string"!=typeof t?e(!1,!1):t.length{"use strict";n(6550),n(95412),n(32345),n(13722),n(71806);var r,i=n(18906),o=n(80826),a=n(16538),u=n(76754),s=n(25578),c={},d={VISA:"visa",MASTERCARD:"mastercard",AMERICAN_EXPRESS:"american-express",DINERS_CLUB:"diners-club",DISCOVER:"discover",JCB:"jcb",UNIONPAY:"unionpay",MAESTRO:"maestro",ELO:"elo",MIR:"mir",HIPER:"hiper",HIPERCARD:"hipercard"},l=[d.VISA,d.MASTERCARD,d.AMERICAN_EXPRESS,d.DINERS_CLUB,d.DISCOVER,d.JCB,d.UNIONPAY,d.MAESTRO,d.ELO,d.MIR,d.HIPER,d.HIPERCARD];function f(t){return c[t]||i[t]}function p(t,e){var n=r.indexOf(t);if(!e&&-1===n)throw new Error('"'+t+'" is not a supported card type.');return n}function h(t){var e,n=[];return u(t)?0===t.length?r.map((function(t){return o(f(t))})):(r.forEach((function(e){var r=f(e);s(t,r,n)})),(e=a(n))?[e]:n):[]}r=o(l),h.getTypeInfo=function(t){return o(f(t))},h.removeCard=function(t){var e=p(t);r.splice(e,1)},h.addCard=function(t){var e=p(t.type,!0);c[t.type]=t,-1===e&&r.push(t.type)},h.updateCard=function(t,e){var n,r=c[t]||i[t];if(!r)throw new Error('"'+t+'" is not a recognized type. Use `addCard` instead.');if(e.type&&r.type!==e.type)throw new Error("Cannot overwrite type parameter.");n=o(r,!0),Object.keys(n).forEach((function(t){e[t]&&(n[t]=e[t])})),c[n.type]=n},h.changeOrder=function(t,e){var n=p(t);r.splice(n,1),r.splice(e,0,t)},h.resetModifications=function(){r=o(l),c={}},h.types=d,t.exports=h},25578:(t,e,n)=>{"use strict";var r=n(80826),i=n(90013);t.exports=function(t,e,n){var o,a,u,s;for(o=0;o=u&&(s.matchStrength=u),n.push(s);break}}},18906:t=>{"use strict";t.exports={visa:{niceType:"Visa",type:"visa",patterns:[4],gaps:[4,8,12],lengths:[16,18,19],code:{name:"CVV",size:3}},mastercard:{niceType:"Mastercard",type:"mastercard",patterns:[[51,55],[2221,2229],[223,229],[23,26],[270,271],2720],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},"american-express":{niceType:"American Express",type:"american-express",patterns:[34,37],gaps:[4,10],lengths:[15],code:{name:"CID",size:4}},"diners-club":{niceType:"Diners Club",type:"diners-club",patterns:[[300,305],36,38,39],gaps:[4,10],lengths:[14,16,19],code:{name:"CVV",size:3}},discover:{niceType:"Discover",type:"discover",patterns:[6011,[644,649],65],gaps:[4,8,12],lengths:[16,19],code:{name:"CID",size:3}},jcb:{niceType:"JCB",type:"jcb",patterns:[2131,1800,[3528,3589]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVV",size:3}},unionpay:{niceType:"UnionPay",type:"unionpay",patterns:[620,[624,626],[62100,62182],[62184,62187],[62185,62197],[62200,62205],[622010,622999],622018,[622019,622999],[62207,62209],[622126,622925],[623,626],6270,6272,6276,[627700,627779],[627781,627799],[6282,6289],6291,6292,810,[8110,8131],[8132,8151],[8152,8163],[8164,8171]],gaps:[4,8,12],lengths:[14,15,16,17,18,19],code:{name:"CVN",size:3}},maestro:{niceType:"Maestro",type:"maestro",patterns:[493698,[5e5,506698],[506779,508999],[56,59],63,67,6],gaps:[4,8,12],lengths:[12,13,14,15,16,17,18,19],code:{name:"CVC",size:3}},elo:{niceType:"Elo",type:"elo",patterns:[401178,401179,438935,457631,457632,431274,451416,457393,504175,[506699,506778],[509e3,509999],627780,636297,636368,[650031,650033],[650035,650051],[650405,650439],[650485,650538],[650541,650598],[650700,650718],[650720,650727],[650901,650978],[651652,651679],[655e3,655019],[655021,655058]],gaps:[4,8,12],lengths:[16],code:{name:"CVE",size:3}},mir:{niceType:"Mir",type:"mir",patterns:[[2200,2204]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVP2",size:3}},hiper:{niceType:"Hiper",type:"hiper",patterns:[637095,637568,637599,637609,637612],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},hipercard:{niceType:"Hipercard",type:"hipercard",patterns:[606282],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}}}},80826:t=>{"use strict";t.exports=function(t){return t?JSON.parse(JSON.stringify(t)):null}},16538:(t,e,n)=>{"use strict";n(51725),t.exports=function(t){if(function(t){var e=t.filter((function(t){return t.matchStrength})).length;return e>0&&e===t.length}(t))return t.reduce((function(t,e){return t?t.matchStrength{"use strict";t.exports=function(t){return"string"==typeof t||t instanceof String}},90013:(t,e,n)=>{"use strict";n(50633),t.exports=function(t,e){return Array.isArray(e)?function(t,e,n){var r=String(e).length,i=t.substr(0,r),o=parseInt(i,10);return e=parseInt(String(e).substr(0,i.length),10),n=parseInt(String(n).substr(0,i.length),10),o>=e&&o<=n}(t,e[0],e[1]):function(t,e){return(e=String(e)).substring(0,t.length)===t.substring(0,e.length)}(t,e)}},99684:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(88033),n(38490),n(64668),n(16516),n(13722),n(40737),n(84868),n(26667),n(10951),n(15483),n(58443),n(5193);var i="%[a-f0-9]{2}",o=new RegExp("("+i+")|([^%]+?)","gi"),a=new RegExp("("+i+")+","gi");function u(t,e){try{return[decodeURIComponent(t.join(""))]}catch(t){}if(1===t.length)return t;e=e||1;var n=t.slice(0,e),r=t.slice(e);return Array.prototype.concat.call([],u(n),u(r))}function s(t){try{return decodeURIComponent(t)}catch(r){for(var e=t.match(o)||[],n=1;n{"use strict";n(93942);var r=n(59788),i=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable;function a(t,e,n){var o=e[n];if(null!=o){if(i.call(t,n)&&(void 0===t[n]||null===t[n]))throw new TypeError("Cannot convert undefined or null to object ("+n+")");i.call(t,n)&&r(o)?t[n]=u(Object(t[n]),e[n]):t[n]=o}}function u(t,e){if(t===e)return t;for(var n in e=Object(e))i.call(e,n)&&a(t,e,n);if(Object.getOwnPropertySymbols)for(var r=Object.getOwnPropertySymbols(e),u=0;u{"use strict";n(6550),n(13722),t.exports=function(t,e){for(var n={},r=Object.keys(t),i=Array.isArray(e),o=0;o{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(38490),n(40737),n(10951),n(5193),t.exports=function(t){var e=r(t);return null!==t&&("object"===e||"function"===e)}},53028:(t,e,n)=>{function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(38490),n(64668),n(16516),n(40737),n(10951),n(58443),n(34500),n(5193),function(n){var i;if("function"==typeof define&&define.amd&&(define(n),i=!0),"object"===r(e)&&(t.exports=n(),i=!0),!i){var o=window.Cookies,a=window.Cookies=n();a.noConflict=function(){return window.Cookies=o,a}}}((function(){function t(){for(var t=0,e={};t{function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(38490),n(95412),n(32345),n(40737),n(84868),n(26667),n(10951),n(58443),n(5193);var i,o="Expected a function",a="__lodash_hash_undefined__",u="[object Function]",s="[object GeneratorFunction]",c=/^\[object .+?Constructor\]$/,d="object"==(void 0===n.g?"undefined":r(n.g))&&n.g&&n.g.Object===Object&&n.g,l="object"==("undefined"==typeof self?"undefined":r(self))&&self&&self.Object===Object&&self,f=d||l||Function("return this")(),p=Array.prototype,h=Function.prototype,y=Object.prototype,m=f["__core-js_shared__"],v=(i=/[^.]+$/.exec(m&&m.keys&&m.keys.IE_PROTO||""))?"Symbol(src)_1."+i:"",g=h.toString,_=y.hasOwnProperty,b=y.toString,S=RegExp("^"+g.call(_).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),w=p.splice,C=x(f,"Map"),E=x(Object,"create");function I(t){var e=-1,n=t?t.length:0;for(this.clear();++e-1},P.prototype.set=function(t,e){var n=this.__data__,r=O(n,t);return r<0?n.push([t,e]):n[r][1]=e,this},A.prototype.clear=function(){this.__data__={hash:new I,map:new(C||P),string:new I}},A.prototype.delete=function(t){return T(this,t).delete(t)},A.prototype.get=function(t){return T(this,t).get(t)},A.prototype.has=function(t){return T(this,t).has(t)},A.prototype.set=function(t,e){return T(this,t).set(t,e),this},R.Cache=A,t.exports=R},59947:(t,e,n)=>{function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}t=n.nmd(t),n(93942),n(70472),n(93270),n(38490),n(95412),n(16516),n(32345),n(71582),n(40737),n(84868),n(26667),n(10951),n(58443),n(5193);var i="__lodash_hash_undefined__",o=9007199254740991,a="[object Arguments]",u="[object AsyncFunction]",s="[object Function]",c="[object GeneratorFunction]",d="[object Null]",l="[object Object]",f="[object Proxy]",p="[object Undefined]",h=/^\[object .+?Constructor\]$/,y=/^(?:0|[1-9]\d*)$/,m={};m["[object Float32Array]"]=m["[object Float64Array]"]=m["[object Int8Array]"]=m["[object Int16Array]"]=m["[object Int32Array]"]=m["[object Uint8Array]"]=m["[object Uint8ClampedArray]"]=m["[object Uint16Array]"]=m["[object Uint32Array]"]=!0,m[a]=m["[object Array]"]=m["[object ArrayBuffer]"]=m["[object Boolean]"]=m["[object DataView]"]=m["[object Date]"]=m["[object Error]"]=m[s]=m["[object Map]"]=m["[object Number]"]=m[l]=m["[object RegExp]"]=m["[object Set]"]=m["[object String]"]=m["[object WeakMap]"]=!1;var v,g,_,b="object"==(void 0===n.g?"undefined":r(n.g))&&n.g&&n.g.Object===Object&&n.g,S="object"==("undefined"==typeof self?"undefined":r(self))&&self&&self.Object===Object&&self,w=b||S||Function("return this")(),C="object"==r(e)&&e&&!e.nodeType&&e,E=C&&"object"==r(t)&&t&&!t.nodeType&&t,I=E&&E.exports===C,P=I&&b.process,A=function(){try{return E&&E.require&&E.require("util").types||P&&P.binding&&P.binding("util")}catch(t){}}(),O=A&&A.isTypedArray,T=Array.prototype,x=Function.prototype,R=Object.prototype,k=w["__core-js_shared__"],M=x.toString,N=R.hasOwnProperty,D=(v=/[^.]+$/.exec(k&&k.keys&&k.keys.IE_PROTO||""))?"Symbol(src)_1."+v:"",L=R.toString,z=M.call(Object),j=RegExp("^"+M.call(N).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),U=I?w.Buffer:void 0,F=w.Symbol,q=w.Uint8Array,B=(U&&U.allocUnsafe,g=Object.getPrototypeOf,_=Object,function(t){return g(_(t))}),G=Object.create,V=R.propertyIsEnumerable,Y=T.splice,H=F?F.toStringTag:void 0,W=function(){try{var t=ht(Object,"defineProperty");return t({},"",{}),t}catch(t){}}(),K=U?U.isBuffer:void 0,Z=Math.max,$=Date.now,J=ht(w,"Map"),Q=ht(Object,"create"),X=function(){function t(){}return function(e){if(!Pt(e))return{};if(G)return G(e);t.prototype=e;var n=new t;return t.prototype=void 0,n}}();function tt(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e-1},et.prototype.set=function(t,e){var n=this.__data__,r=at(n,t);return r<0?(++this.size,n.push([t,e])):n[r][1]=e,this},nt.prototype.clear=function(){this.size=0,this.__data__={hash:new tt,map:new(J||et),string:new tt}},nt.prototype.delete=function(t){var e=pt(this,t).delete(t);return this.size-=e?1:0,e},nt.prototype.get=function(t){return pt(this,t).get(t)},nt.prototype.has=function(t){return pt(this,t).has(t)},nt.prototype.set=function(t,e){var n=pt(this,t),r=n.size;return n.set(t,e),this.size+=n.size==r?0:1,this},rt.prototype.clear=function(){this.__data__=new et,this.size=0},rt.prototype.delete=function(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n},rt.prototype.get=function(t){return this.__data__.get(t)},rt.prototype.has=function(t){return this.__data__.has(t)},rt.prototype.set=function(t,e){var n=this.__data__;if(n instanceof et){var r=n.__data__;if(!J||r.length<199)return r.push([t,e]),this.size=++n.size,this;n=this.__data__=new nt(r)}return n.set(t,e),this.size=n.size,this};var st=function(t,e,n){for(var r=-1,i=Object(t),o=n(t),a=o.length;a--;){var u=o[++r];if(!1===e(i[u],u,i))break}return t};function ct(t){return null==t?void 0===t?p:d:H&&H in Object(t)?function(t){var e=N.call(t,H),n=t[H];try{t[H]=void 0;var r=!0}catch(t){}var i=L.call(t);return r&&(e?t[H]=n:delete t[H]),i}(t):function(t){return L.call(t)}(t)}function dt(t){return At(t)&&ct(t)==a}function lt(t,e,n,r,i){t!==e&&st(e,(function(o,a){if(i||(i=new rt),Pt(o))!function(t,e,n,r,i,o,a){var u=vt(t,n),s=vt(e,n),c=a.get(s);if(c)it(t,n,c);else{var d,f,p,h,y,m=o?o(u,s,n+"",t,e,a):void 0,v=void 0===m;if(v){var g=St(s),_=!g&&Ct(s),b=!g&&!_&&Ot(s);m=s,g||_||b?St(u)?m=u:At(y=u)&&wt(y)?m=function(t,e){var n=-1,r=t.length;for(e||(e=Array(r));++n-1&&t%1==0&&t0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}(ft);function _t(t,e){return t===e||t!=t&&e!=e}var bt=dt(function(){return arguments}())?dt:function(t){return At(t)&&N.call(t,"callee")&&!V.call(t,"callee")},St=Array.isArray;function wt(t){return null!=t&&It(t.length)&&!Et(t)}var Ct=K||function(){return!1};function Et(t){if(!Pt(t))return!1;var e=ct(t);return e==s||e==c||e==u||e==f}function It(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=o}function Pt(t){var e=r(t);return null!=t&&("object"==e||"function"==e)}function At(t){return null!=t&&"object"==r(t)}var Ot=O?function(t){return function(e){return t(e)}}(O):function(t){return At(t)&&It(t.length)&&!!m[ct(t)]};function Tt(t){return wt(t)?function(t,e){var n=St(t),r=!n&&bt(t),i=!n&&!r&&Ct(t),o=!n&&!r&&!i&&Ot(t),a=n||r||i||o,u=a?function(t,e){for(var n=-1,r=Array(t);++n1?e[i-1]:void 0,a=i>2?e[2]:void 0;for(o=xt.length>3&&"function"==typeof o?(i--,o):void 0,a&&function(t,e,n){if(!Pt(n))return!1;var i=r(e);return!!("number"==i?wt(n)&&yt(e,n.length):"string"==i&&e in n)&&_t(n[e],t)}(e[0],e[1],a)&&(o=i<3?void 0:o,i=1),t=Object(t);++n"']/g,W=RegExp(Y.source),K=RegExp(H.source),Z=/<%-([\s\S]+?)%>/g,$=/<%([\s\S]+?)%>/g,J=/<%=([\s\S]+?)%>/g,Q=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,X=/^\w*$/,tt=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,et=/[\\^$.*+?()[\]{}|]/g,nt=RegExp(et.source),rt=/^\s+/,it=/\s/,ot=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,at=/\{\n\/\* \[wrapped with (.+)\] \*/,ut=/,? & /,st=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,ct=/[()=,{}\[\]\/\s]/,dt=/\\(\\)?/g,lt=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,ft=/\w*$/,pt=/^[-+]0x[0-9a-f]+$/i,ht=/^0b[01]+$/i,yt=/^\[object .+?Constructor\]$/,mt=/^0o[0-7]+$/i,vt=/^(?:0|[1-9]\d*)$/,gt=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,_t=/($^)/,bt=/['\n\r\u2028\u2029\\]/g,St="\\ud800-\\udfff",wt="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",Ct="\\u2700-\\u27bf",Et="a-z\\xdf-\\xf6\\xf8-\\xff",It="A-Z\\xc0-\\xd6\\xd8-\\xde",Pt="\\ufe0e\\ufe0f",At="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",Ot="["+St+"]",Tt="["+At+"]",xt="["+wt+"]",Rt="\\d+",kt="["+Ct+"]",Mt="["+Et+"]",Nt="[^"+St+At+Rt+Ct+Et+It+"]",Dt="\\ud83c[\\udffb-\\udfff]",Lt="[^"+St+"]",zt="(?:\\ud83c[\\udde6-\\uddff]){2}",jt="[\\ud800-\\udbff][\\udc00-\\udfff]",Ut="["+It+"]",Ft="\\u200d",qt="(?:"+Mt+"|"+Nt+")",Bt="(?:"+Ut+"|"+Nt+")",Gt="(?:['’](?:d|ll|m|re|s|t|ve))?",Vt="(?:['’](?:D|LL|M|RE|S|T|VE))?",Yt="(?:"+xt+"|"+Dt+")?",Ht="["+Pt+"]?",Wt=Ht+Yt+"(?:"+Ft+"(?:"+[Lt,zt,jt].join("|")+")"+Ht+Yt+")*",Kt="(?:"+[kt,zt,jt].join("|")+")"+Wt,Zt="(?:"+[Lt+xt+"?",xt,zt,jt,Ot].join("|")+")",$t=RegExp("['’]","g"),Jt=RegExp(xt,"g"),Qt=RegExp(Dt+"(?="+Dt+")|"+Zt+Wt,"g"),Xt=RegExp([Ut+"?"+Mt+"+"+Gt+"(?="+[Tt,Ut,"$"].join("|")+")",Bt+"+"+Vt+"(?="+[Tt,Ut+qt,"$"].join("|")+")",Ut+"?"+qt+"+"+Gt,Ut+"+"+Vt,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",Rt,Kt].join("|"),"g"),te=RegExp("["+Ft+St+wt+Pt+"]"),ee=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,ne=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],re=-1,ie={};ie[M]=ie[N]=ie[D]=ie[L]=ie[z]=ie[j]=ie[U]=ie[F]=ie[q]=!0,ie[y]=ie[m]=ie[R]=ie[v]=ie[k]=ie[g]=ie[_]=ie[b]=ie[w]=ie[C]=ie[E]=ie[P]=ie[A]=ie[O]=ie[x]=!1;var oe={};oe[y]=oe[m]=oe[R]=oe[k]=oe[v]=oe[g]=oe[M]=oe[N]=oe[D]=oe[L]=oe[z]=oe[w]=oe[C]=oe[E]=oe[P]=oe[A]=oe[O]=oe[T]=oe[j]=oe[U]=oe[F]=oe[q]=!0,oe[_]=oe[b]=oe[x]=!1;var ae={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},ue=parseFloat,se=parseInt,ce="object"==(void 0===n.g?"undefined":r(n.g))&&n.g&&n.g.Object===Object&&n.g,de="object"==("undefined"==typeof self?"undefined":r(self))&&self&&self.Object===Object&&self,le=ce||de||Function("return this")(),fe="object"==r(e)&&e&&!e.nodeType&&e,pe=fe&&"object"==r(t)&&t&&!t.nodeType&&t,he=pe&&pe.exports===fe,ye=he&&ce.process,me=function(){try{return pe&&pe.require&&pe.require("util").types||ye&&ye.binding&&ye.binding("util")}catch(t){}}(),ve=me&&me.isArrayBuffer,ge=me&&me.isDate,_e=me&&me.isMap,be=me&&me.isRegExp,Se=me&&me.isSet,we=me&&me.isTypedArray;function Ce(t,e,n){switch(n.length){case 0:return t.call(e);case 1:return t.call(e,n[0]);case 2:return t.call(e,n[0],n[1]);case 3:return t.call(e,n[0],n[1],n[2])}return t.apply(e,n)}function Ee(t,e,n,r){for(var i=-1,o=null==t?0:t.length;++i-1}function xe(t,e,n){for(var r=-1,i=null==t?0:t.length;++r-1;);return n}function Xe(t,e){for(var n=t.length;n--&&Ue(e,t[n],0)>-1;);return n}var tn=Ve({À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"}),en=Ve({"&":"&","<":"<",">":">",'"':""","'":"'"});function nn(t){return"\\"+ae[t]}function rn(t){return te.test(t)}function on(t){var e=-1,n=Array(t.size);return t.forEach((function(t,r){n[++e]=[r,t]})),n}function an(t,e){return function(n){return t(e(n))}}function un(t,e){for(var n=-1,r=t.length,i=0,o=[];++n",""":'"',"'":"'"}),hn=function t(e){var n,it=(e=null==e?le:hn.defaults(le.Object(),e,hn.pick(le,ne))).Array,St=e.Date,wt=e.Error,Ct=e.Function,Et=e.Math,It=e.Object,Pt=e.RegExp,At=e.String,Ot=e.TypeError,Tt=it.prototype,xt=Ct.prototype,Rt=It.prototype,kt=e["__core-js_shared__"],Mt=xt.toString,Nt=Rt.hasOwnProperty,Dt=0,Lt=(n=/[^.]+$/.exec(kt&&kt.keys&&kt.keys.IE_PROTO||""))?"Symbol(src)_1."+n:"",zt=Rt.toString,jt=Mt.call(It),Ut=le._,Ft=Pt("^"+Mt.call(Nt).replace(et,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),qt=he?e.Buffer:i,Bt=e.Symbol,Gt=e.Uint8Array,Vt=qt?qt.allocUnsafe:i,Yt=an(It.getPrototypeOf,It),Ht=It.create,Wt=Rt.propertyIsEnumerable,Kt=Tt.splice,Zt=Bt?Bt.isConcatSpreadable:i,Qt=Bt?Bt.iterator:i,te=Bt?Bt.toStringTag:i,ae=function(){try{var t=co(It,"defineProperty");return t({},"",{}),t}catch(t){}}(),ce=e.clearTimeout!==le.clearTimeout&&e.clearTimeout,de=St&&St.now!==le.Date.now&&St.now,fe=e.setTimeout!==le.setTimeout&&e.setTimeout,pe=Et.ceil,ye=Et.floor,me=It.getOwnPropertySymbols,Le=qt?qt.isBuffer:i,Ve=e.isFinite,yn=Tt.join,mn=an(It.keys,It),vn=Et.max,gn=Et.min,_n=St.now,bn=e.parseInt,Sn=Et.random,wn=Tt.reverse,Cn=co(e,"DataView"),En=co(e,"Map"),In=co(e,"Promise"),Pn=co(e,"Set"),An=co(e,"WeakMap"),On=co(It,"create"),Tn=An&&new An,xn={},Rn=jo(Cn),kn=jo(En),Mn=jo(In),Nn=jo(Pn),Dn=jo(An),Ln=Bt?Bt.prototype:i,zn=Ln?Ln.valueOf:i,jn=Ln?Ln.toString:i;function Un(t){if(eu(t)&&!Va(t)&&!(t instanceof Gn)){if(t instanceof Bn)return t;if(Nt.call(t,"__wrapped__"))return Uo(t)}return new Bn(t)}var Fn=function(){function t(){}return function(e){if(!tu(e))return{};if(Ht)return Ht(e);t.prototype=e;var n=new t;return t.prototype=i,n}}();function qn(){}function Bn(t,e){this.__wrapped__=t,this.__actions__=[],this.__chain__=!!e,this.__index__=0,this.__values__=i}function Gn(t){this.__wrapped__=t,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=p,this.__views__=[]}function Vn(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e=e?t:e)),t}function ur(t,e,n,r,o,a){var u,s=1&e,c=2&e,d=4&e;if(n&&(u=o?n(t,r,o,a):n(t)),u!==i)return u;if(!tu(t))return t;var l=Va(t);if(l){if(u=function(t){var e=t.length,n=new t.constructor(e);return e&&"string"==typeof t[0]&&Nt.call(t,"index")&&(n.index=t.index,n.input=t.input),n}(t),!s)return Ai(t,u)}else{var f=po(t),p=f==b||f==S;if(Ka(t))return Si(t,s);if(f==E||f==y||p&&!o){if(u=c||p?{}:yo(t),!s)return c?function(t,e){return Oi(t,fo(t),e)}(t,function(t,e){return t&&Oi(e,ku(e),t)}(u,t)):function(t,e){return Oi(t,lo(t),e)}(t,rr(u,t))}else{if(!oe[f])return o?t:{};u=function(t,e,n){var r,i=t.constructor;switch(e){case R:return wi(t);case v:case g:return new i(+t);case k:return function(t,e){var n=e?wi(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.byteLength)}(t,n);case M:case N:case D:case L:case z:case j:case U:case F:case q:return Ci(t,n);case w:return new i;case C:case O:return new i(t);case P:return function(t){var e=new t.constructor(t.source,ft.exec(t));return e.lastIndex=t.lastIndex,e}(t);case A:return new i;case T:return r=t,zn?It(zn.call(r)):{}}}(t,f,s)}}a||(a=new Kn);var h=a.get(t);if(h)return h;a.set(t,u),au(t)?t.forEach((function(r){u.add(ur(r,e,n,r,t,a))})):nu(t)&&t.forEach((function(r,i){u.set(i,ur(r,e,n,i,t,a))}));var m=l?i:(d?c?no:eo:c?ku:Ru)(t);return Ie(m||t,(function(r,i){m&&(r=t[i=r]),tr(u,i,ur(r,e,n,i,t,a))})),u}function sr(t,e,n){var r=n.length;if(null==t)return!r;for(t=It(t);r--;){var o=n[r],a=e[o],u=t[o];if(u===i&&!(o in t)||!a(u))return!1}return!0}function cr(t,e,n){if("function"!=typeof t)throw new Ot(o);return To((function(){t.apply(i,n)}),e)}function dr(t,e,n,r){var i=-1,o=Te,a=!0,u=t.length,s=[],c=e.length;if(!u)return s;n&&(e=Re(e,Ze(n))),r?(o=xe,a=!1):e.length>=200&&(o=Je,a=!1,e=new Wn(e));t:for(;++i-1},Yn.prototype.set=function(t,e){var n=this.__data__,r=er(n,t);return r<0?(++this.size,n.push([t,e])):n[r][1]=e,this},Hn.prototype.clear=function(){this.size=0,this.__data__={hash:new Vn,map:new(En||Yn),string:new Vn}},Hn.prototype.delete=function(t){var e=uo(this,t).delete(t);return this.size-=e?1:0,e},Hn.prototype.get=function(t){return uo(this,t).get(t)},Hn.prototype.has=function(t){return uo(this,t).has(t)},Hn.prototype.set=function(t,e){var n=uo(this,t),r=n.size;return n.set(t,e),this.size+=n.size==r?0:1,this},Wn.prototype.add=Wn.prototype.push=function(t){return this.__data__.set(t,a),this},Wn.prototype.has=function(t){return this.__data__.has(t)},Kn.prototype.clear=function(){this.__data__=new Yn,this.size=0},Kn.prototype.delete=function(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n},Kn.prototype.get=function(t){return this.__data__.get(t)},Kn.prototype.has=function(t){return this.__data__.has(t)},Kn.prototype.set=function(t,e){var n=this.__data__;if(n instanceof Yn){var r=n.__data__;if(!En||r.length<199)return r.push([t,e]),this.size=++n.size,this;n=this.__data__=new Hn(r)}return n.set(t,e),this.size=n.size,this};var lr=Ri(_r),fr=Ri(br,!0);function pr(t,e){var n=!0;return lr(t,(function(t,r,i){return n=!!e(t,r,i)})),n}function hr(t,e,n){for(var r=-1,o=t.length;++r0&&n(u)?e>1?mr(u,e-1,n,r,i):ke(i,u):r||(i[i.length]=u)}return i}var vr=ki(),gr=ki(!0);function _r(t,e){return t&&vr(t,e,Ru)}function br(t,e){return t&&gr(t,e,Ru)}function Sr(t,e){return Oe(e,(function(e){return Ja(t[e])}))}function wr(t,e){for(var n=0,r=(e=vi(e,t)).length;null!=t&&ne}function Pr(t,e){return null!=t&&Nt.call(t,e)}function Ar(t,e){return null!=t&&e in It(t)}function Or(t,e,n){for(var r=n?xe:Te,o=t[0].length,a=t.length,u=a,s=it(a),c=1/0,d=[];u--;){var l=t[u];u&&e&&(l=Re(l,Ze(e))),c=gn(l.length,c),s[u]=!n&&(e||o>=120&&l.length>=120)?new Wn(u&&l):i}l=t[0];var f=-1,p=s[0];t:for(;++f=u?s:s*("desc"==n[r]?-1:1)}return t.index-e.index}(t,e,n)}));r--;)t[r]=t[r].value;return t}(i)}function Gr(t,e,n){for(var r=-1,i=e.length,o={};++r-1;)u!==t&&Kt.call(u,s,1),Kt.call(t,s,1);return t}function Yr(t,e){for(var n=t?e.length:0,r=n-1;n--;){var i=e[n];if(n==r||i!==o){var o=i;vo(i)?Kt.call(t,i,1):ci(t,i)}}return t}function Hr(t,e){return t+ye(Sn()*(e-t+1))}function Wr(t,e){var n="";if(!t||e<1||e>l)return n;do{e%2&&(n+=t),(e=ye(e/2))&&(t+=t)}while(e);return n}function Kr(t,e){return xo(Io(t,e,rs),t+"")}function Zr(t){return $n(Fu(t))}function $r(t,e){var n=Fu(t);return Mo(n,ar(e,0,n.length))}function Jr(t,e,n,r){if(!tu(t))return t;for(var o=-1,a=(e=vi(e,t)).length,u=a-1,s=t;null!=s&&++oi?0:i+e),(n=n>i?i:n)<0&&(n+=i),i=e>n?0:n-e>>>0,e>>>=0;for(var o=it(i);++r>>1,a=t[o];null!==a&&!su(a)&&(n?a<=e:a=200){var c=e?null:Wi(t);if(c)return sn(c);a=!1,i=Je,s=new Wn}else s=e?[]:u;t:for(;++r=r?t:ei(t,e,n)}var bi=ce||function(t){return le.clearTimeout(t)};function Si(t,e){if(e)return t.slice();var n=t.length,r=Vt?Vt(n):new t.constructor(n);return t.copy(r),r}function wi(t){var e=new t.constructor(t.byteLength);return new Gt(e).set(new Gt(t)),e}function Ci(t,e){var n=e?wi(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.length)}function Ei(t,e){if(t!==e){var n=t!==i,r=null===t,o=t==t,a=su(t),u=e!==i,s=null===e,c=e==e,d=su(e);if(!s&&!d&&!a&&t>e||a&&u&&c&&!s&&!d||r&&u&&c||!n&&c||!o)return 1;if(!r&&!a&&!d&&t1?n[o-1]:i,u=o>2?n[2]:i;for(a=t.length>3&&"function"==typeof a?(o--,a):i,u&&go(n[0],n[1],u)&&(a=o<3?i:a,o=1),e=It(e);++r-1?o[a?e[u]:u]:i}}function zi(t){return to((function(e){var n=e.length,r=n,a=Bn.prototype.thru;for(t&&e.reverse();r--;){var u=e[r];if("function"!=typeof u)throw new Ot(o);if(a&&!s&&"wrapper"==io(u))var s=new Bn([],!0)}for(r=s?r:n;++r1&&_.reverse(),f&&ds))return!1;var d=a.get(t),l=a.get(e);if(d&&l)return d==e&&l==t;var f=-1,p=!0,h=2&n?new Wn:i;for(a.set(t,e),a.set(e,t);++f-1&&t%1==0&&t1?"& ":"")+e[r],e=e.join(n>2?", ":" "),t.replace(ot,"{\n/* [wrapped with "+e+"] */\n")}(r,function(t,e){return Ie(h,(function(n){var r="_."+n[0];e&n[1]&&!Te(t,r)&&t.push(r)})),t.sort()}(function(t){var e=t.match(at);return e?e[1].split(ut):[]}(r),n)))}function ko(t){var e=0,n=0;return function(){var r=_n(),o=16-(r-n);if(n=r,o>0){if(++e>=800)return arguments[0]}else e=0;return t.apply(i,arguments)}}function Mo(t,e){var n=-1,r=t.length,o=r-1;for(e=e===i?r:e;++n1?t[e-1]:i;return n="function"==typeof n?(t.pop(),n):i,oa(t,n)}));function fa(t){var e=Un(t);return e.__chain__=!0,e}function pa(t,e){return e(t)}var ha=to((function(t){var e=t.length,n=e?t[0]:0,r=this.__wrapped__,o=function(e){return or(e,t)};return!(e>1||this.__actions__.length)&&r instanceof Gn&&vo(n)?((r=r.slice(n,+n+(e?1:0))).__actions__.push({func:pa,args:[o],thisArg:i}),new Bn(r,this.__chain__).thru((function(t){return e&&!t.length&&t.push(i),t}))):this.thru(o)})),ya=Ti((function(t,e,n){Nt.call(t,n)?++t[n]:ir(t,n,1)})),ma=Li(Go),va=Li(Vo);function ga(t,e){return(Va(t)?Ie:lr)(t,ao(e,3))}function _a(t,e){return(Va(t)?Pe:fr)(t,ao(e,3))}var ba=Ti((function(t,e,n){Nt.call(t,n)?t[n].push(e):ir(t,n,[e])})),Sa=Kr((function(t,e,n){var r=-1,i="function"==typeof e,o=Ha(t)?it(t.length):[];return lr(t,(function(t){o[++r]=i?Ce(e,t,n):Tr(t,e,n)})),o})),wa=Ti((function(t,e,n){ir(t,n,e)}));function Ca(t,e){return(Va(t)?Re:zr)(t,ao(e,3))}var Ea=Ti((function(t,e,n){t[n?0:1].push(e)}),(function(){return[[],[]]})),Ia=Kr((function(t,e){if(null==t)return[];var n=e.length;return n>1&&go(t,e[0],e[1])?e=[]:n>2&&go(e[0],e[1],e[2])&&(e=[e[0]]),Br(t,mr(e,1),[])})),Pa=de||function(){return le.Date.now()};function Aa(t,e,n){return e=n?i:e,e=t&&null==e?t.length:e,Zi(t,c,i,i,i,i,e)}function Oa(t,e){var n;if("function"!=typeof e)throw new Ot(o);return t=hu(t),function(){return--t>0&&(n=e.apply(this,arguments)),t<=1&&(e=i),n}}var Ta=Kr((function(t,e,n){var r=1;if(n.length){var i=un(n,oo(Ta));r|=s}return Zi(t,r,e,n,i)})),xa=Kr((function(t,e,n){var r=3;if(n.length){var i=un(n,oo(xa));r|=s}return Zi(e,r,t,n,i)}));function Ra(t,e,n){var r,a,u,s,c,d,l=0,f=!1,p=!1,h=!0;if("function"!=typeof t)throw new Ot(o);function y(e){var n=r,o=a;return r=a=i,l=e,s=t.apply(o,n)}function m(t){var n=t-d;return d===i||n>=e||n<0||p&&t-l>=u}function v(){var t=Pa();if(m(t))return g(t);c=To(v,function(t){var n=e-(t-d);return p?gn(n,u-(t-l)):n}(t))}function g(t){return c=i,h&&r?y(t):(r=a=i,s)}function _(){var t=Pa(),n=m(t);if(r=arguments,a=this,d=t,n){if(c===i)return function(t){return l=t,c=To(v,e),f?y(t):s}(d);if(p)return bi(c),c=To(v,e),y(d)}return c===i&&(c=To(v,e)),s}return e=mu(e)||0,tu(n)&&(f=!!n.leading,u=(p="maxWait"in n)?vn(mu(n.maxWait)||0,e):u,h="trailing"in n?!!n.trailing:h),_.cancel=function(){c!==i&&bi(c),l=0,r=d=a=c=i},_.flush=function(){return c===i?s:g(Pa())},_}var ka=Kr((function(t,e){return cr(t,1,e)})),Ma=Kr((function(t,e,n){return cr(t,mu(e)||0,n)}));function Na(t,e){if("function"!=typeof t||null!=e&&"function"!=typeof e)throw new Ot(o);var n=function n(){var r=arguments,i=e?e.apply(this,r):r[0],o=n.cache;if(o.has(i))return o.get(i);var a=t.apply(this,r);return n.cache=o.set(i,a)||o,a};return n.cache=new(Na.Cache||Hn),n}function Da(t){if("function"!=typeof t)throw new Ot(o);return function(){var e=arguments;switch(e.length){case 0:return!t.call(this);case 1:return!t.call(this,e[0]);case 2:return!t.call(this,e[0],e[1]);case 3:return!t.call(this,e[0],e[1],e[2])}return!t.apply(this,e)}}Na.Cache=Hn;var La=gi((function(t,e){var n=(e=1==e.length&&Va(e[0])?Re(e[0],Ze(ao())):Re(mr(e,1),Ze(ao()))).length;return Kr((function(r){for(var i=-1,o=gn(r.length,n);++i=e})),Ga=xr(function(){return arguments}())?xr:function(t){return eu(t)&&Nt.call(t,"callee")&&!Wt.call(t,"callee")},Va=it.isArray,Ya=ve?Ze(ve):function(t){return eu(t)&&Er(t)==R};function Ha(t){return null!=t&&Xa(t.length)&&!Ja(t)}function Wa(t){return eu(t)&&Ha(t)}var Ka=Le||ms,Za=ge?Ze(ge):function(t){return eu(t)&&Er(t)==g};function $a(t){if(!eu(t))return!1;var e=Er(t);return e==_||"[object DOMException]"==e||"string"==typeof t.message&&"string"==typeof t.name&&!iu(t)}function Ja(t){if(!tu(t))return!1;var e=Er(t);return e==b||e==S||"[object AsyncFunction]"==e||"[object Proxy]"==e}function Qa(t){return"number"==typeof t&&t==hu(t)}function Xa(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=l}function tu(t){var e=r(t);return null!=t&&("object"==e||"function"==e)}function eu(t){return null!=t&&"object"==r(t)}var nu=_e?Ze(_e):function(t){return eu(t)&&po(t)==w};function ru(t){return"number"==typeof t||eu(t)&&Er(t)==C}function iu(t){if(!eu(t)||Er(t)!=E)return!1;var e=Yt(t);if(null===e)return!0;var n=Nt.call(e,"constructor")&&e.constructor;return"function"==typeof n&&n instanceof n&&Mt.call(n)==jt}var ou=be?Ze(be):function(t){return eu(t)&&Er(t)==P},au=Se?Ze(Se):function(t){return eu(t)&&po(t)==A};function uu(t){return"string"==typeof t||!Va(t)&&eu(t)&&Er(t)==O}function su(t){return"symbol"==r(t)||eu(t)&&Er(t)==T}var cu=we?Ze(we):function(t){return eu(t)&&Xa(t.length)&&!!ie[Er(t)]},du=Vi(Lr),lu=Vi((function(t,e){return t<=e}));function fu(t){if(!t)return[];if(Ha(t))return uu(t)?ln(t):Ai(t);if(Qt&&t[Qt])return function(t){for(var e,n=[];!(e=t.next()).done;)n.push(e.value);return n}(t[Qt]());var e=po(t);return(e==w?on:e==A?sn:Fu)(t)}function pu(t){return t?(t=mu(t))===d||t===-1/0?17976931348623157e292*(t<0?-1:1):t==t?t:0:0===t?t:0}function hu(t){var e=pu(t),n=e%1;return e==e?n?e-n:e:0}function yu(t){return t?ar(hu(t),0,p):0}function mu(t){if("number"==typeof t)return t;if(su(t))return f;if(tu(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=tu(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=Ke(t);var n=ht.test(t);return n||mt.test(t)?se(t.slice(2),n?2:8):pt.test(t)?f:+t}function vu(t){return Oi(t,ku(t))}function gu(t){return null==t?"":ui(t)}var _u=xi((function(t,e){if(wo(e)||Ha(e))Oi(e,Ru(e),t);else for(var n in e)Nt.call(e,n)&&tr(t,n,e[n])})),bu=xi((function(t,e){Oi(e,ku(e),t)})),Su=xi((function(t,e,n,r){Oi(e,ku(e),t,r)})),wu=xi((function(t,e,n,r){Oi(e,Ru(e),t,r)})),Cu=to(or),Eu=Kr((function(t,e){t=It(t);var n=-1,r=e.length,o=r>2?e[2]:i;for(o&&go(e[0],e[1],o)&&(r=1);++n1),e})),Oi(t,no(t),n),r&&(n=ur(n,7,Qi));for(var i=e.length;i--;)ci(n,e[i]);return n})),Lu=to((function(t,e){return null==t?{}:function(t,e){return Gr(t,e,(function(e,n){return Au(t,n)}))}(t,e)}));function zu(t,e){if(null==t)return{};var n=Re(no(t),(function(t){return[t]}));return e=ao(e),Gr(t,n,(function(t,n){return e(t,n[0])}))}var ju=Ki(Ru),Uu=Ki(ku);function Fu(t){return null==t?[]:$e(t,Ru(t))}var qu=Ni((function(t,e,n){return e=e.toLowerCase(),t+(n?Bu(e):e)}));function Bu(t){return $u(gu(t).toLowerCase())}function Gu(t){return(t=gu(t))&&t.replace(gt,tn).replace(Jt,"")}var Vu=Ni((function(t,e,n){return t+(n?"-":"")+e.toLowerCase()})),Yu=Ni((function(t,e,n){return t+(n?" ":"")+e.toLowerCase()})),Hu=Mi("toLowerCase"),Wu=Ni((function(t,e,n){return t+(n?"_":"")+e.toLowerCase()})),Ku=Ni((function(t,e,n){return t+(n?" ":"")+$u(e)})),Zu=Ni((function(t,e,n){return t+(n?" ":"")+e.toUpperCase()})),$u=Mi("toUpperCase");function Ju(t,e,n){return t=gu(t),(e=n?i:e)===i?function(t){return ee.test(t)}(t)?function(t){return t.match(Xt)||[]}(t):function(t){return t.match(st)||[]}(t):t.match(e)||[]}var Qu=Kr((function(t,e){try{return Ce(t,i,e)}catch(t){return $a(t)?t:new wt(t)}})),Xu=to((function(t,e){return Ie(e,(function(e){e=zo(e),ir(t,e,Ta(t[e],t))})),t}));function ts(t){return function(){return t}}var es=zi(),ns=zi(!0);function rs(t){return t}function is(t){return Nr("function"==typeof t?t:ur(t,1))}var os=Kr((function(t,e){return function(n){return Tr(n,t,e)}})),as=Kr((function(t,e){return function(n){return Tr(t,n,e)}}));function us(t,e,n){var r=Ru(e),i=Sr(e,r);null!=n||tu(e)&&(i.length||!r.length)||(n=e,e=t,t=this,i=Sr(e,Ru(e)));var o=!(tu(n)&&"chain"in n&&!n.chain),a=Ja(t);return Ie(i,(function(n){var r=e[n];t[n]=r,a&&(t.prototype[n]=function(){var e=this.__chain__;if(o||e){var n=t(this.__wrapped__);return(n.__actions__=Ai(this.__actions__)).push({func:r,args:arguments,thisArg:t}),n.__chain__=e,n}return r.apply(t,ke([this.value()],arguments))})})),t}function ss(){}var cs=qi(Re),ds=qi(Ae),ls=qi(De);function fs(t){return _o(t)?Ge(zo(t)):function(t){return function(e){return wr(e,t)}}(t)}var ps=Gi(),hs=Gi(!0);function ys(){return[]}function ms(){return!1}var vs,gs=Fi((function(t,e){return t+e}),0),_s=Hi("ceil"),bs=Fi((function(t,e){return t/e}),1),Ss=Hi("floor"),ws=Fi((function(t,e){return t*e}),1),Cs=Hi("round"),Es=Fi((function(t,e){return t-e}),0);return Un.after=function(t,e){if("function"!=typeof e)throw new Ot(o);return t=hu(t),function(){if(--t<1)return e.apply(this,arguments)}},Un.ary=Aa,Un.assign=_u,Un.assignIn=bu,Un.assignInWith=Su,Un.assignWith=wu,Un.at=Cu,Un.before=Oa,Un.bind=Ta,Un.bindAll=Xu,Un.bindKey=xa,Un.castArray=function(){if(!arguments.length)return[];var t=arguments[0];return Va(t)?t:[t]},Un.chain=fa,Un.chunk=function(t,e,n){e=(n?go(t,e,n):e===i)?1:vn(hu(e),0);var r=null==t?0:t.length;if(!r||e<1)return[];for(var o=0,a=0,u=it(pe(r/e));oo?0:o+n),(r=r===i||r>o?o:hu(r))<0&&(r+=o),r=n>r?0:yu(r);n>>0)?(t=gu(t))&&("string"==typeof e||null!=e&&!ou(e))&&!(e=ui(e))&&rn(t)?_i(ln(t),0,n):t.split(e,n):[]},Un.spread=function(t,e){if("function"!=typeof t)throw new Ot(o);return e=null==e?0:vn(hu(e),0),Kr((function(n){var r=n[e],i=_i(n,0,e);return r&&ke(i,r),Ce(t,this,i)}))},Un.tail=function(t){var e=null==t?0:t.length;return e?ei(t,1,e):[]},Un.take=function(t,e,n){return t&&t.length?ei(t,0,(e=n||e===i?1:hu(e))<0?0:e):[]},Un.takeRight=function(t,e,n){var r=null==t?0:t.length;return r?ei(t,(e=r-(e=n||e===i?1:hu(e)))<0?0:e,r):[]},Un.takeRightWhile=function(t,e){return t&&t.length?li(t,ao(e,3),!1,!0):[]},Un.takeWhile=function(t,e){return t&&t.length?li(t,ao(e,3)):[]},Un.tap=function(t,e){return e(t),t},Un.throttle=function(t,e,n){var r=!0,i=!0;if("function"!=typeof t)throw new Ot(o);return tu(n)&&(r="leading"in n?!!n.leading:r,i="trailing"in n?!!n.trailing:i),Ra(t,e,{leading:r,maxWait:e,trailing:i})},Un.thru=pa,Un.toArray=fu,Un.toPairs=ju,Un.toPairsIn=Uu,Un.toPath=function(t){return Va(t)?Re(t,zo):su(t)?[t]:Ai(Lo(gu(t)))},Un.toPlainObject=vu,Un.transform=function(t,e,n){var r=Va(t),i=r||Ka(t)||cu(t);if(e=ao(e,4),null==n){var o=t&&t.constructor;n=i?r?new o:[]:tu(t)&&Ja(o)?Fn(Yt(t)):{}}return(i?Ie:_r)(t,(function(t,r,i){return e(n,t,r,i)})),n},Un.unary=function(t){return Aa(t,1)},Un.union=ea,Un.unionBy=na,Un.unionWith=ra,Un.uniq=function(t){return t&&t.length?si(t):[]},Un.uniqBy=function(t,e){return t&&t.length?si(t,ao(e,2)):[]},Un.uniqWith=function(t,e){return e="function"==typeof e?e:i,t&&t.length?si(t,i,e):[]},Un.unset=function(t,e){return null==t||ci(t,e)},Un.unzip=ia,Un.unzipWith=oa,Un.update=function(t,e,n){return null==t?t:di(t,e,mi(n))},Un.updateWith=function(t,e,n,r){return r="function"==typeof r?r:i,null==t?t:di(t,e,mi(n),r)},Un.values=Fu,Un.valuesIn=function(t){return null==t?[]:$e(t,ku(t))},Un.without=aa,Un.words=Ju,Un.wrap=function(t,e){return za(mi(e),t)},Un.xor=ua,Un.xorBy=sa,Un.xorWith=ca,Un.zip=da,Un.zipObject=function(t,e){return hi(t||[],e||[],tr)},Un.zipObjectDeep=function(t,e){return hi(t||[],e||[],Jr)},Un.zipWith=la,Un.entries=ju,Un.entriesIn=Uu,Un.extend=bu,Un.extendWith=Su,us(Un,Un),Un.add=gs,Un.attempt=Qu,Un.camelCase=qu,Un.capitalize=Bu,Un.ceil=_s,Un.clamp=function(t,e,n){return n===i&&(n=e,e=i),n!==i&&(n=(n=mu(n))==n?n:0),e!==i&&(e=(e=mu(e))==e?e:0),ar(mu(t),e,n)},Un.clone=function(t){return ur(t,4)},Un.cloneDeep=function(t){return ur(t,5)},Un.cloneDeepWith=function(t,e){return ur(t,5,e="function"==typeof e?e:i)},Un.cloneWith=function(t,e){return ur(t,4,e="function"==typeof e?e:i)},Un.conformsTo=function(t,e){return null==e||sr(t,e,Ru(e))},Un.deburr=Gu,Un.defaultTo=function(t,e){return null==t||t!=t?e:t},Un.divide=bs,Un.endsWith=function(t,e,n){t=gu(t),e=ui(e);var r=t.length,o=n=n===i?r:ar(hu(n),0,r);return(n-=e.length)>=0&&t.slice(n,o)==e},Un.eq=Fa,Un.escape=function(t){return(t=gu(t))&&K.test(t)?t.replace(H,en):t},Un.escapeRegExp=function(t){return(t=gu(t))&&nt.test(t)?t.replace(et,"\\$&"):t},Un.every=function(t,e,n){var r=Va(t)?Ae:pr;return n&&go(t,e,n)&&(e=i),r(t,ao(e,3))},Un.find=ma,Un.findIndex=Go,Un.findKey=function(t,e){return ze(t,ao(e,3),_r)},Un.findLast=va,Un.findLastIndex=Vo,Un.findLastKey=function(t,e){return ze(t,ao(e,3),br)},Un.floor=Ss,Un.forEach=ga,Un.forEachRight=_a,Un.forIn=function(t,e){return null==t?t:vr(t,ao(e,3),ku)},Un.forInRight=function(t,e){return null==t?t:gr(t,ao(e,3),ku)},Un.forOwn=function(t,e){return t&&_r(t,ao(e,3))},Un.forOwnRight=function(t,e){return t&&br(t,ao(e,3))},Un.get=Pu,Un.gt=qa,Un.gte=Ba,Un.has=function(t,e){return null!=t&&ho(t,e,Pr)},Un.hasIn=Au,Un.head=Ho,Un.identity=rs,Un.includes=function(t,e,n,r){t=Ha(t)?t:Fu(t),n=n&&!r?hu(n):0;var i=t.length;return n<0&&(n=vn(i+n,0)),uu(t)?n<=i&&t.indexOf(e,n)>-1:!!i&&Ue(t,e,n)>-1},Un.indexOf=function(t,e,n){var r=null==t?0:t.length;if(!r)return-1;var i=null==n?0:hu(n);return i<0&&(i=vn(r+i,0)),Ue(t,e,i)},Un.inRange=function(t,e,n){return e=pu(e),n===i?(n=e,e=0):n=pu(n),function(t,e,n){return t>=gn(e,n)&&t=-9007199254740991&&t<=l},Un.isSet=au,Un.isString=uu,Un.isSymbol=su,Un.isTypedArray=cu,Un.isUndefined=function(t){return t===i},Un.isWeakMap=function(t){return eu(t)&&po(t)==x},Un.isWeakSet=function(t){return eu(t)&&"[object WeakSet]"==Er(t)},Un.join=function(t,e){return null==t?"":yn.call(t,e)},Un.kebabCase=Vu,Un.last=$o,Un.lastIndexOf=function(t,e,n){var r=null==t?0:t.length;if(!r)return-1;var o=r;return n!==i&&(o=(o=hu(n))<0?vn(r+o,0):gn(o,r-1)),e==e?function(t,e,n){for(var r=n+1;r--;)if(t[r]===e)return r;return r}(t,e,o):je(t,qe,o,!0)},Un.lowerCase=Yu,Un.lowerFirst=Hu,Un.lt=du,Un.lte=lu,Un.max=function(t){return t&&t.length?hr(t,rs,Ir):i},Un.maxBy=function(t,e){return t&&t.length?hr(t,ao(e,2),Ir):i},Un.mean=function(t){return Be(t,rs)},Un.meanBy=function(t,e){return Be(t,ao(e,2))},Un.min=function(t){return t&&t.length?hr(t,rs,Lr):i},Un.minBy=function(t,e){return t&&t.length?hr(t,ao(e,2),Lr):i},Un.stubArray=ys,Un.stubFalse=ms,Un.stubObject=function(){return{}},Un.stubString=function(){return""},Un.stubTrue=function(){return!0},Un.multiply=ws,Un.nth=function(t,e){return t&&t.length?qr(t,hu(e)):i},Un.noConflict=function(){return le._===this&&(le._=Ut),this},Un.noop=ss,Un.now=Pa,Un.pad=function(t,e,n){t=gu(t);var r=(e=hu(e))?dn(t):0;if(!e||r>=e)return t;var i=(e-r)/2;return Bi(ye(i),n)+t+Bi(pe(i),n)},Un.padEnd=function(t,e,n){t=gu(t);var r=(e=hu(e))?dn(t):0;return e&&re){var r=t;t=e,e=r}if(n||t%1||e%1){var o=Sn();return gn(t+o*(e-t+ue("1e-"+((o+"").length-1))),e)}return Hr(t,e)},Un.reduce=function(t,e,n){var r=Va(t)?Me:Ye,i=arguments.length<3;return r(t,ao(e,4),n,i,lr)},Un.reduceRight=function(t,e,n){var r=Va(t)?Ne:Ye,i=arguments.length<3;return r(t,ao(e,4),n,i,fr)},Un.repeat=function(t,e,n){return e=(n?go(t,e,n):e===i)?1:hu(e),Wr(gu(t),e)},Un.replace=function(){var t=arguments,e=gu(t[0]);return t.length<3?e:e.replace(t[1],t[2])},Un.result=function(t,e,n){var r=-1,o=(e=vi(e,t)).length;for(o||(o=1,t=i);++rl)return[];var n=p,r=gn(t,p);e=ao(e),t-=p;for(var i=We(r,e);++n=a)return t;var s=n-dn(r);if(s<1)return r;var c=u?_i(u,0,s).join(""):t.slice(0,s);if(o===i)return c+r;if(u&&(s+=c.length-s),ou(o)){if(t.slice(s).search(o)){var d,l=c;for(o.global||(o=Pt(o.source,gu(ft.exec(o))+"g")),o.lastIndex=0;d=o.exec(l);)var f=d.index;c=c.slice(0,f===i?s:f)}}else if(t.indexOf(ui(o),s)!=s){var p=c.lastIndexOf(o);p>-1&&(c=c.slice(0,p))}return c+r},Un.unescape=function(t){return(t=gu(t))&&W.test(t)?t.replace(Y,pn):t},Un.uniqueId=function(t){var e=++Dt;return gu(t)+e},Un.upperCase=Zu,Un.upperFirst=$u,Un.each=ga,Un.eachRight=_a,Un.first=Ho,us(Un,(vs={},_r(Un,(function(t,e){Nt.call(Un.prototype,e)||(vs[e]=t)})),vs),{chain:!1}),Un.VERSION="4.17.21",Ie(["bind","bindKey","curry","curryRight","partial","partialRight"],(function(t){Un[t].placeholder=Un})),Ie(["drop","take"],(function(t,e){Gn.prototype[t]=function(n){n=n===i?1:vn(hu(n),0);var r=this.__filtered__&&!e?new Gn(this):this.clone();return r.__filtered__?r.__takeCount__=gn(n,r.__takeCount__):r.__views__.push({size:gn(n,p),type:t+(r.__dir__<0?"Right":"")}),r},Gn.prototype[t+"Right"]=function(e){return this.reverse()[t](e).reverse()}})),Ie(["filter","map","takeWhile"],(function(t,e){var n=e+1,r=1==n||3==n;Gn.prototype[t]=function(t){var e=this.clone();return e.__iteratees__.push({iteratee:ao(t,3),type:n}),e.__filtered__=e.__filtered__||r,e}})),Ie(["head","last"],(function(t,e){var n="take"+(e?"Right":"");Gn.prototype[t]=function(){return this[n](1).value()[0]}})),Ie(["initial","tail"],(function(t,e){var n="drop"+(e?"":"Right");Gn.prototype[t]=function(){return this.__filtered__?new Gn(this):this[n](1)}})),Gn.prototype.compact=function(){return this.filter(rs)},Gn.prototype.find=function(t){return this.filter(t).head()},Gn.prototype.findLast=function(t){return this.reverse().find(t)},Gn.prototype.invokeMap=Kr((function(t,e){return"function"==typeof t?new Gn(this):this.map((function(n){return Tr(n,t,e)}))})),Gn.prototype.reject=function(t){return this.filter(Da(ao(t)))},Gn.prototype.slice=function(t,e){t=hu(t);var n=this;return n.__filtered__&&(t>0||e<0)?new Gn(n):(t<0?n=n.takeRight(-t):t&&(n=n.drop(t)),e!==i&&(n=(e=hu(e))<0?n.dropRight(-e):n.take(e-t)),n)},Gn.prototype.takeRightWhile=function(t){return this.reverse().takeWhile(t).reverse()},Gn.prototype.toArray=function(){return this.take(p)},_r(Gn.prototype,(function(t,e){var n=/^(?:filter|find|map|reject)|While$/.test(e),r=/^(?:head|last)$/.test(e),o=Un[r?"take"+("last"==e?"Right":""):e],a=r||/^find/.test(e);o&&(Un.prototype[e]=function(){var e=this.__wrapped__,u=r?[1]:arguments,s=e instanceof Gn,c=u[0],d=s||Va(e),l=function(t){var e=o.apply(Un,ke([t],u));return r&&f?e[0]:e};d&&n&&"function"==typeof c&&1!=c.length&&(s=d=!1);var f=this.__chain__,p=!!this.__actions__.length,h=a&&!f,y=s&&!p;if(!a&&d){e=y?e:new Gn(this);var m=t.apply(e,u);return m.__actions__.push({func:pa,args:[l],thisArg:i}),new Bn(m,f)}return h&&y?t.apply(this,u):(m=this.thru(l),h?r?m.value()[0]:m.value():m)})})),Ie(["pop","push","shift","sort","splice","unshift"],(function(t){var e=Tt[t],n=/^(?:push|sort|unshift)$/.test(t)?"tap":"thru",r=/^(?:pop|shift)$/.test(t);Un.prototype[t]=function(){var t=arguments;if(r&&!this.__chain__){var i=this.value();return e.apply(Va(i)?i:[],t)}return this[n]((function(n){return e.apply(Va(n)?n:[],t)}))}})),_r(Gn.prototype,(function(t,e){var n=Un[e];if(n){var r=n.name+"";Nt.call(xn,r)||(xn[r]=[]),xn[r].push({name:e,func:n})}})),xn[ji(i,2).name]=[{name:"wrapper",func:i}],Gn.prototype.clone=function(){var t=new Gn(this.__wrapped__);return t.__actions__=Ai(this.__actions__),t.__dir__=this.__dir__,t.__filtered__=this.__filtered__,t.__iteratees__=Ai(this.__iteratees__),t.__takeCount__=this.__takeCount__,t.__views__=Ai(this.__views__),t},Gn.prototype.reverse=function(){if(this.__filtered__){var t=new Gn(this);t.__dir__=-1,t.__filtered__=!0}else(t=this.clone()).__dir__*=-1;return t},Gn.prototype.value=function(){var t=this.__wrapped__.value(),e=this.__dir__,n=Va(t),r=e<0,i=n?t.length:0,o=function(t,e,n){for(var r=-1,i=n.length;++r=this.__values__.length;return{done:t,value:t?i:this.__values__[this.__index__++]}},Un.prototype.plant=function(t){for(var e,n=this;n instanceof qn;){var r=Uo(n);r.__index__=0,r.__values__=i,e?o.__wrapped__=r:e=r;var o=r;n=n.__wrapped__}return o.__wrapped__=t,e},Un.prototype.reverse=function(){var t=this.__wrapped__;if(t instanceof Gn){var e=t;return this.__actions__.length&&(e=new Gn(this)),(e=e.reverse()).__actions__.push({func:pa,args:[ta],thisArg:i}),new Bn(e,this.__chain__)}return this.thru(ta)},Un.prototype.toJSON=Un.prototype.valueOf=Un.prototype.value=function(){return fi(this.__wrapped__,this.__actions__)},Un.prototype.first=Un.prototype.head,Qt&&(Un.prototype[Qt]=function(){return this}),Un}();"function"==typeof define&&"object"==r(define.amd)&&define.amd?(le._=hn,define((function(){return hn}))):pe?((pe.exports=hn)._=hn,fe._=hn):le._=hn}.call(this)},66534:(t,e,n)=>{"use strict";n(93942),n(64668),n(95412),n(27835),n(60678),n(13722),n(34500);var r=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable;t.exports=function(){try{if(!Object.assign)return!1;var t=new String("abc");if(t[5]="de","5"===Object.getOwnPropertyNames(t)[0])return!1;for(var e={},n=0;n<10;n++)e["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(e).map((function(t){return e[t]})).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach((function(t){r[t]=t})),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(t){return!1}}()?Object.assign:function(t,e){for(var n,a,u=function(t){if(null==t)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}(t),s=1;s{"use strict";function r(t,e,n){return(e=function(t){var e=function(t,e){if("object"!==o(t)||null===t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,"string");if("object"!==o(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"===o(e)?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function i(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,i,o,a,u=[],s=!0,c=!1;try{if(o=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;s=!1}else for(;!(s=(r=o.call(n)).done)&&(u.push(r.value),u.length!==e);s=!0);}catch(t){c=!0,i=t}finally{try{if(!s&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(c)throw i}}return u}}(t,e)||u(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function o(t){return o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},o(t)}function a(t){return function(t){if(Array.isArray(t))return s(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||u(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function u(t,e){if(t){if("string"==typeof t)return s(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?s(t,e):void 0}}function s(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n0})).join("&")},e.parseUrl=function(t,e){e=Object.assign({decode:!0},e);var n=i(l(t,"#"),2),r=n[0],o=n[1];return Object.assign({url:r.split("?")[0]||"",query:S(_(t),e)},e&&e.parseFragmentIdentifier&&o?{fragmentIdentifier:m(o,e)}:{})},e.stringifyUrl=function(t,n){n=Object.assign(r({encode:!0,strict:!0},p,!0),n);var i=g(t.url).split("?")[0]||"",o=e.extract(t.url),a=e.parse(o,{sort:!1}),u=Object.assign(a,t.query),s=e.stringify(u,n);s&&(s="?".concat(s));var c=function(t){var e="",n=t.indexOf("#");return-1!==n&&(e=t.slice(n)),e}(t.url);return t.fragmentIdentifier&&(c="#".concat(n[p]?y(t.fragmentIdentifier,n):t.fragmentIdentifier)),"".concat(i).concat(s).concat(c)},e.pick=function(t,n,i){i=Object.assign(r({parseFragmentIdentifier:!0},p,!1),i);var o=e.parseUrl(t,i),a=o.url,u=o.query,s=o.fragmentIdentifier;return e.stringifyUrl({url:a,query:f(u,n),fragmentIdentifier:s},i)},e.exclude=function(t,n,r){var i=Array.isArray(n)?function(t){return!n.includes(t)}:function(t,e){return!n(t,e)};return e.pick(t,i,r)}},89311:(t,e,n)=>{"use strict";n(40737),n(26667),n(58443),t.exports=function(t){return encodeURIComponent(t).replace(/[!'()*]/g,(function(t){return"%".concat(t.charCodeAt(0).toString(16).toUpperCase())}))}},57469:(t,e,n)=>{"use strict";n.r(e),n.d(e,{ArgumentOutOfRangeError:()=>x.W,AsyncSubject:()=>d.c,BehaviorSubject:()=>s.X,ConnectableObservable:()=>i.c,EMPTY:()=>Z.E,EmptyError:()=>R.K,GroupedObservable:()=>o.T,NEVER:()=>dt,Notification:()=>I.P,NotificationKind:()=>I.W,ObjectUnsubscribedError:()=>k.N,Observable:()=>r.y,ReplaySubject:()=>c.t,Scheduler:()=>w.b,Subject:()=>u.xQ,Subscriber:()=>E.L,Subscription:()=>C.w,TimeoutError:()=>N.W,UnsubscriptionError:()=>M.B,VirtualAction:()=>S,VirtualTimeScheduler:()=>b,animationFrame:()=>_,animationFrameScheduler:()=>g,asap:()=>l.e,asapScheduler:()=>l.E,async:()=>f.P,asyncScheduler:()=>f.z,bindCallback:()=>U,bindNodeCallback:()=>B,combineLatest:()=>H.aj,concat:()=>W.z,config:()=>Ot.v,defer:()=>K.P,empty:()=>Z.c,forkJoin:()=>Q,from:()=>J.D,fromEvent:()=>tt.R,fromEventPattern:()=>nt,generate:()=>rt,identity:()=>O.y,iif:()=>ot,interval:()=>ut,isObservable:()=>T,merge:()=>ct.T,never:()=>lt,noop:()=>A.Z,observable:()=>a.L,of:()=>ft.of,onErrorResumeNext:()=>pt,pairs:()=>ht,partition:()=>_t,pipe:()=>P.z,queue:()=>p.c,queueScheduler:()=>p.N,race:()=>bt.S3,range:()=>St,scheduled:()=>At.x,throwError:()=>Ct._,timer:()=>Et.H,using:()=>It,zip:()=>Pt.$R});var r=n(64074),i=n(46700),o=n(82727),a=n(86916),u=n(99357),s=n(41735),c=n(28646),d=n(2503),l=n(18420),f=n(26858),p=n(30396),h=n(61699),y=n(674),m=function(t){function e(e,n){var r=t.call(this,e,n)||this;return r.scheduler=e,r.work=n,r}return h.__extends(e,t),e.prototype.requestAsyncId=function(e,n,r){return void 0===r&&(r=0),null!==r&&r>0?t.prototype.requestAsyncId.call(this,e,n,r):(e.actions.push(this),e.scheduled||(e.scheduled=requestAnimationFrame((function(){return e.flush(null)}))))},e.prototype.recycleAsyncId=function(e,n,r){if(void 0===r&&(r=0),null!==r&&r>0||null===r&&this.delay>0)return t.prototype.recycleAsyncId.call(this,e,n,r);0===e.actions.length&&(cancelAnimationFrame(n),e.scheduled=void 0)},e}(y.o),v=n(41978),g=new(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return h.__extends(e,t),e.prototype.flush=function(t){this.active=!0,this.scheduled=void 0;var e,n=this.actions,r=-1,i=n.length;t=t||n.shift();do{if(e=t.execute(t.state,t.delay))break}while(++re.index?1:-1:t.delay>e.delay?1:-1},e}(y.o),w=n(78379),C=n(75838),E=n(90782),I=n(48811),P=n(76252),A=n(38375),O=n(16726);function T(t){return!!t&&(t instanceof r.y||"function"==typeof t.lift&&"function"==typeof t.subscribe)}var x=n(4069),R=n(2246),k=n(42046),M=n(42135),N=n(76960),D=(n(88033),n(92160)),L=n(12411),z=n(24937),j=n(79917);function U(t,e,n){if(e){if(!(0,j.K)(e))return function(){for(var r=[],i=0;i=e){r.complete();break}if(r.next(o++),r.closed)break}}))}function wt(t){var e=t.start,n=t.index,r=t.count,i=t.subscriber;n>=r?i.complete():(i.next(e),i.closed||(t.index=n+1,t.start=e+1,this.schedule(t)))}var Ct=n(78665),Et=n(12670);function It(t,e){return new r.y((function(n){var r,i;try{r=t()}catch(t){return void n.error(t)}try{i=e(r)}catch(t){return void n.error(t)}var o=(i?(0,J.D)(i):Z.E).subscribe(n);return function(){o.unsubscribe(),r&&r.unsubscribe()}}))}var Pt=n(66436),At=n(77488),Ot=n(84850)},2503:(t,e,n)=>{"use strict";n.d(e,{c:()=>a});var r=n(61699),i=n(99357),o=n(75838),a=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.value=null,e.hasNext=!1,e.hasCompleted=!1,e}return r.__extends(e,t),e.prototype._subscribe=function(e){return this.hasError?(e.error(this.thrownError),o.w.EMPTY):this.hasCompleted&&this.hasNext?(e.next(this.value),e.complete(),o.w.EMPTY):t.prototype._subscribe.call(this,e)},e.prototype.next=function(t){this.hasCompleted||(this.value=t,this.hasNext=!0)},e.prototype.error=function(e){this.hasCompleted||t.prototype.error.call(this,e)},e.prototype.complete=function(){this.hasCompleted=!0,this.hasNext&&t.prototype.next.call(this,this.value),t.prototype.complete.call(this)},e}(i.xQ)},41735:(t,e,n)=>{"use strict";n.d(e,{X:()=>a});var r=n(61699),i=n(99357),o=n(42046),a=function(t){function e(e){var n=t.call(this)||this;return n._value=e,n}return r.__extends(e,t),Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!0,configurable:!0}),e.prototype._subscribe=function(e){var n=t.prototype._subscribe.call(this,e);return n&&!n.closed&&e.next(this._value),n},e.prototype.getValue=function(){if(this.hasError)throw this.thrownError;if(this.closed)throw new o.N;return this._value},e.prototype.next=function(e){t.prototype.next.call(this,this._value=e)},e}(i.xQ)},48811:(t,e,n)=>{"use strict";n.d(e,{P:()=>u,W:()=>r});var r,i=n(14585),o=n(12309),a=n(78665);r||(r={});var u=function(){function t(t,e,n){this.kind=t,this.value=e,this.error=n,this.hasValue="N"===t}return t.prototype.observe=function(t){switch(this.kind){case"N":return t.next&&t.next(this.value);case"E":return t.error&&t.error(this.error);case"C":return t.complete&&t.complete()}},t.prototype.do=function(t,e,n){switch(this.kind){case"N":return t&&t(this.value);case"E":return e&&e(this.error);case"C":return n&&n()}},t.prototype.accept=function(t,e,n){return t&&"function"==typeof t.next?this.observe(t):this.do(t,e,n)},t.prototype.toObservable=function(){switch(this.kind){case"N":return(0,o.of)(this.value);case"E":return(0,a._)(this.error);case"C":return(0,i.c)()}throw new Error("unexpected notification kind value")},t.createNext=function(e){return void 0!==e?new t("N",e):t.undefinedValueNotification},t.createError=function(e){return new t("E",void 0,e)},t.createComplete=function(){return t.completeNotification},t.completeNotification=new t("C"),t.undefinedValueNotification=new t("N",void 0),t}()},64074:(t,e,n)=>{"use strict";n.d(e,{y:()=>s}),n(40737),n(83823),n(71806);var r=n(12411),i=n(54752),o=n(86916),a=n(76252),u=n(84850),s=function(){function t(t){this._isScalar=!1,t&&(this._subscribe=t)}return t.prototype.lift=function(e){var n=new t;return n.source=this,n.operator=e,n},t.prototype.subscribe=function(t,e,n){var r=this.operator,o=(0,i.Y)(t,e,n);if(r?o.add(r.call(o,this.source)):o.add(this.source||u.v.useDeprecatedSynchronousErrorHandling&&!o.syncErrorThrowable?this._subscribe(o):this._trySubscribe(o)),u.v.useDeprecatedSynchronousErrorHandling&&o.syncErrorThrowable&&(o.syncErrorThrowable=!1,o.syncErrorThrown))throw o.syncErrorValue;return o},t.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(e){u.v.useDeprecatedSynchronousErrorHandling&&(t.syncErrorThrown=!0,t.syncErrorValue=e),(0,r._)(t)?t.error(e):console.warn(e)}},t.prototype.forEach=function(t,e){var n=this;return new(e=c(e))((function(e,r){var i;i=n.subscribe((function(e){try{t(e)}catch(t){r(t),i&&i.unsubscribe()}}),r,e)}))},t.prototype._subscribe=function(t){var e=this.source;return e&&e.subscribe(t)},t.prototype[o.L]=function(){return this},t.prototype.pipe=function(){for(var t=[],e=0;e{"use strict";n.d(e,{c:()=>o});var r=n(84850),i=n(61554),o={closed:!0,next:function(t){},error:function(t){if(r.v.useDeprecatedSynchronousErrorHandling)throw t;(0,i.z)(t)},complete:function(){}}},64809:(t,e,n)=>{"use strict";n.d(e,{L:()=>i});var r=n(61699),i=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return r.__extends(e,t),e.prototype.notifyNext=function(t,e,n,r,i){this.destination.next(e)},e.prototype.notifyError=function(t,e){this.destination.error(t)},e.prototype.notifyComplete=function(t){this.destination.complete()},e}(n(90782).L)},28646:(t,e,n)=>{"use strict";n.d(e,{t:()=>d}),n(32345),n(99023);var r=n(61699),i=n(99357),o=n(30396),a=n(75838),u=n(9202),s=n(42046),c=n(17630),d=function(t){function e(e,n,r){void 0===e&&(e=Number.POSITIVE_INFINITY),void 0===n&&(n=Number.POSITIVE_INFINITY);var i=t.call(this)||this;return i.scheduler=r,i._events=[],i._infiniteTimeWindow=!1,i._bufferSize=e<1?1:e,i._windowTime=n<1?1:n,n===Number.POSITIVE_INFINITY?(i._infiniteTimeWindow=!0,i.next=i.nextInfiniteTimeWindow):i.next=i.nextTimeWindow,i}return r.__extends(e,t),e.prototype.nextInfiniteTimeWindow=function(e){if(!this.isStopped){var n=this._events;n.push(e),n.length>this._bufferSize&&n.shift()}t.prototype.next.call(this,e)},e.prototype.nextTimeWindow=function(e){this.isStopped||(this._events.push(new l(this._getNow(),e)),this._trimBufferThenGetEvents()),t.prototype.next.call(this,e)},e.prototype._subscribe=function(t){var e,n=this._infiniteTimeWindow,r=n?this._events:this._trimBufferThenGetEvents(),i=this.scheduler,o=r.length;if(this.closed)throw new s.N;if(this.isStopped||this.hasError?e=a.w.EMPTY:(this.observers.push(t),e=new c.W(this,t)),i&&t.add(t=new u.ht(t,i)),n)for(var d=0;de&&(o=Math.max(o,i-e)),o>0&&r.splice(0,o),r},e}(i.xQ),l=function(){return function(t,e){this.time=t,this.value=e}}()},78379:(t,e,n)=>{"use strict";n.d(e,{b:()=>r});var r=function(){function t(e,n){void 0===n&&(n=t.now),this.SchedulerAction=e,this.now=n}return t.prototype.schedule=function(t,e,n){return void 0===e&&(e=0),new this.SchedulerAction(this,t).schedule(n,e)},t.now=function(){return Date.now()},t}()},99357:(t,e,n)=>{"use strict";n.d(e,{Yc:()=>d,xQ:()=>l}),n(16516);var r=n(61699),i=n(64074),o=n(90782),a=n(75838),u=n(42046),s=n(17630),c=n(70239),d=function(t){function e(e){var n=t.call(this,e)||this;return n.destination=e,n}return r.__extends(e,t),e}(o.L),l=function(t){function e(){var e=t.call(this)||this;return e.observers=[],e.closed=!1,e.isStopped=!1,e.hasError=!1,e.thrownError=null,e}return r.__extends(e,t),e.prototype[c.b]=function(){return new d(this)},e.prototype.lift=function(t){var e=new f(this,this);return e.operator=t,e},e.prototype.next=function(t){if(this.closed)throw new u.N;if(!this.isStopped)for(var e=this.observers,n=e.length,r=e.slice(),i=0;i{"use strict";n.d(e,{W:()=>i}),n(6550),n(32345);var r=n(61699),i=function(t){function e(e,n){var r=t.call(this)||this;return r.subject=e,r.subscriber=n,r.closed=!1,r}return r.__extends(e,t),e.prototype.unsubscribe=function(){if(!this.closed){this.closed=!0;var t=this.subject,e=t.observers;if(this.subject=null,e&&0!==e.length&&!t.isStopped&&!t.closed){var n=e.indexOf(this.subscriber);-1!==n&&e.splice(n,1)}}},e}(n(75838).w)},90782:(t,e,n)=>{"use strict";n.d(e,{L:()=>l}),n(93942),n(70472),n(93270),n(38490),n(40737),n(10951),n(5193);var r=n(61699),i=n(11169),o=n(43610),a=n(75838),u=n(70239),s=n(84850),c=n(61554);function d(t){return d="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},d(t)}var l=function(t){function e(n,r,i){var a=t.call(this)||this;switch(a.syncErrorValue=null,a.syncErrorThrown=!1,a.syncErrorThrowable=!1,a.isStopped=!1,arguments.length){case 0:a.destination=o.c;break;case 1:if(!n){a.destination=o.c;break}if("object"===d(n)){n instanceof e?(a.syncErrorThrowable=n.syncErrorThrowable,a.destination=n,n.add(a)):(a.syncErrorThrowable=!0,a.destination=new f(a,n));break}default:a.syncErrorThrowable=!0,a.destination=new f(a,n,r,i)}return a}return r.__extends(e,t),e.prototype[u.b]=function(){return this},e.create=function(t,n,r){var i=new e(t,n,r);return i.syncErrorThrowable=!1,i},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this))},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){this.destination.error(t),this.unsubscribe()},e.prototype._complete=function(){this.destination.complete(),this.unsubscribe()},e.prototype._unsubscribeAndRecycle=function(){var t=this._parentOrParents;return this._parentOrParents=null,this.unsubscribe(),this.closed=!1,this.isStopped=!1,this._parentOrParents=t,this},e}(a.w),f=function(t){function e(e,n,r,a){var u,s=t.call(this)||this;s._parentSubscriber=e;var c=s;return(0,i.m)(n)?u=n:n&&(u=n.next,r=n.error,a=n.complete,n!==o.c&&(c=Object.create(n),(0,i.m)(c.unsubscribe)&&s.add(c.unsubscribe.bind(c)),c.unsubscribe=s.unsubscribe.bind(s))),s._context=c,s._next=u,s._error=r,s._complete=a,s}return r.__extends(e,t),e.prototype.next=function(t){if(!this.isStopped&&this._next){var e=this._parentSubscriber;s.v.useDeprecatedSynchronousErrorHandling&&e.syncErrorThrowable?this.__tryOrSetError(e,this._next,t)&&this.unsubscribe():this.__tryOrUnsub(this._next,t)}},e.prototype.error=function(t){if(!this.isStopped){var e=this._parentSubscriber,n=s.v.useDeprecatedSynchronousErrorHandling;if(this._error)n&&e.syncErrorThrowable?(this.__tryOrSetError(e,this._error,t),this.unsubscribe()):(this.__tryOrUnsub(this._error,t),this.unsubscribe());else if(e.syncErrorThrowable)n?(e.syncErrorValue=t,e.syncErrorThrown=!0):(0,c.z)(t),this.unsubscribe();else{if(this.unsubscribe(),n)throw t;(0,c.z)(t)}}},e.prototype.complete=function(){var t=this;if(!this.isStopped){var e=this._parentSubscriber;if(this._complete){var n=function(){return t._complete.call(t._context)};s.v.useDeprecatedSynchronousErrorHandling&&e.syncErrorThrowable?(this.__tryOrSetError(e,n),this.unsubscribe()):(this.__tryOrUnsub(n),this.unsubscribe())}else this.unsubscribe()}},e.prototype.__tryOrUnsub=function(t,e){try{t.call(this._context,e)}catch(t){if(this.unsubscribe(),s.v.useDeprecatedSynchronousErrorHandling)throw t;(0,c.z)(t)}},e.prototype.__tryOrSetError=function(t,e,n){if(!s.v.useDeprecatedSynchronousErrorHandling)throw new Error("bad call");try{e.call(this._context,n)}catch(e){return s.v.useDeprecatedSynchronousErrorHandling?(t.syncErrorValue=e,t.syncErrorThrown=!0,!0):((0,c.z)(e),!0)}return!1},e.prototype._unsubscribe=function(){var t=this._parentSubscriber;this._context=null,this._parentSubscriber=null,t.unsubscribe()},e}(l)},75838:(t,e,n)=>{"use strict";n.d(e,{w:()=>s}),n(93942),n(70472),n(93270),n(88033),n(6550),n(38490),n(32345),n(40737),n(10951),n(5193);var r=n(24937),i=n(46308),o=n(11169),a=n(42135);function u(t){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},u(t)}var s=function(){function t(t){this.closed=!1,this._parentOrParents=null,this._subscriptions=null,t&&(this._ctorUnsubscribe=!0,this._unsubscribe=t)}var e;return t.prototype.unsubscribe=function(){var e;if(!this.closed){var n=this,u=n._parentOrParents,s=n._ctorUnsubscribe,d=n._unsubscribe,l=n._subscriptions;if(this.closed=!0,this._parentOrParents=null,this._subscriptions=null,u instanceof t)u.remove(this);else if(null!==u)for(var f=0;f{"use strict";n.d(e,{v:()=>i});var r=!1,i={Promise:void 0,set useDeprecatedSynchronousErrorHandling(t){t&&(new Error).stack,r=t},get useDeprecatedSynchronousErrorHandling(){return r}}},56431:(t,e,n)=>{"use strict";n.d(e,{Ds:()=>s,IY:()=>u,ft:()=>c});var r=n(61699),i=n(90782),o=n(64074),a=n(28817),u=function(t){function e(e){var n=t.call(this)||this;return n.parent=e,n}return r.__extends(e,t),e.prototype._next=function(t){this.parent.notifyNext(t)},e.prototype._error=function(t){this.parent.notifyError(t),this.unsubscribe()},e.prototype._complete=function(){this.parent.notifyComplete(),this.unsubscribe()},e}(i.L),s=(i.L,function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return r.__extends(e,t),e.prototype.notifyNext=function(t){this.destination.next(t)},e.prototype.notifyError=function(t){this.destination.error(t)},e.prototype.notifyComplete=function(){this.destination.complete()},e}(i.L));function c(t,e){if(!e.closed){if(t instanceof o.y)return t.subscribe(e);var n;try{n=(0,a.s)(t)(e)}catch(t){e.error(t)}return n}}i.L},46700:(t,e,n)=>{"use strict";n.d(e,{N:()=>d,c:()=>c});var r=n(61699),i=n(99357),o=n(64074),a=n(90782),u=n(75838),s=n(16807),c=function(t){function e(e,n){var r=t.call(this)||this;return r.source=e,r.subjectFactory=n,r._refCount=0,r._isComplete=!1,r}return r.__extends(e,t),e.prototype._subscribe=function(t){return this.getSubject().subscribe(t)},e.prototype.getSubject=function(){var t=this._subject;return t&&!t.isStopped||(this._subject=this.subjectFactory()),this._subject},e.prototype.connect=function(){var t=this._connection;return t||(this._isComplete=!1,(t=this._connection=new u.w).add(this.source.subscribe(new l(this.getSubject(),this))),t.closed&&(this._connection=null,t=u.w.EMPTY)),t},e.prototype.refCount=function(){return(0,s.x)()(this)},e}(o.y),d=function(){var t=c.prototype;return{operator:{value:null},_refCount:{value:0,writable:!0},_subject:{value:null,writable:!0},_connection:{value:null,writable:!0},_subscribe:{value:t._subscribe},_isComplete:{value:t._isComplete,writable:!0},getSubject:{value:t.getSubject},connect:{value:t.connect},refCount:{value:t.refCount}}}(),l=function(t){function e(e,n){var r=t.call(this,e)||this;return r.connectable=n,r}return r.__extends(e,t),e.prototype._error=function(e){this._unsubscribe(),t.prototype._error.call(this,e)},e.prototype._complete=function(){this.connectable._isComplete=!0,this._unsubscribe(),t.prototype._complete.call(this)},e.prototype._unsubscribe=function(){var t=this.connectable;if(t){this.connectable=null;var e=t._connection;t._refCount=0,t._subject=null,t._connection=null,e&&e.unsubscribe()}},e}(i.Yc);a.L},12206:(t,e,n)=>{"use strict";n.d(e,{Ms:()=>l,aj:()=>d}),n(38490),n(16516),n(40737),n(5193);var r=n(61699),i=n(79917),o=n(24937),a=n(64809),u=n(30121),s=n(42178),c={};function d(){for(var t=[],e=0;e{"use strict";n.d(e,{z:()=>o});var r=n(12309),i=n(54110);function o(){for(var t=[],e=0;e{"use strict";n.d(e,{P:()=>a});var r=n(64074),i=n(73531),o=n(14585);function a(t){return new r.y((function(e){var n;try{n=t()}catch(t){return void e.error(t)}return(n?(0,i.D)(n):(0,o.c)()).subscribe(e)}))}},14585:(t,e,n)=>{"use strict";n.d(e,{E:()=>i,c:()=>o});var r=n(64074),i=new r.y((function(t){return t.complete()}));function o(t){return t?function(t){return new r.y((function(e){return t.schedule((function(){return e.complete()}))}))}(t):i}},73531:(t,e,n)=>{"use strict";n.d(e,{D:()=>a});var r=n(64074),i=n(28817),o=n(77488);function a(t,e){return e?(0,o.x)(t,e):t instanceof r.y?t:new r.y((0,i.s)(t))}},42178:(t,e,n)=>{"use strict";n.d(e,{n:()=>a});var r=n(64074),i=n(97327),o=n(75077);function a(t,e){return e?(0,o.r)(t,e):new r.y((0,i.V)(t))}},55343:(t,e,n)=>{"use strict";n.d(e,{R:()=>u}),n(16516),n(40737),n(26667);var r=n(64074),i=n(24937),o=n(11169),a=n(92160);function u(t,e,n,c){return(0,o.m)(n)&&(c=n,n=void 0),c?u(t,e,n).pipe((0,a.U)((function(t){return(0,i.k)(t)?c.apply(void 0,t):c(t)}))):new r.y((function(r){s(t,e,(function(t){arguments.length>1?r.next(Array.prototype.slice.call(arguments)):r.next(t)}),r,n)}))}function s(t,e,n,r,i){var o;if(function(t){return t&&"function"==typeof t.addEventListener&&"function"==typeof t.removeEventListener}(t)){var a=t;t.addEventListener(e,n,i),o=function(){return a.removeEventListener(e,n,i)}}else if(function(t){return t&&"function"==typeof t.on&&"function"==typeof t.off}(t)){var u=t;t.on(e,n),o=function(){return u.off(e,n)}}else if(function(t){return t&&"function"==typeof t.addListener&&"function"==typeof t.removeListener}(t)){var c=t;t.addListener(e,n),o=function(){return c.removeListener(e,n)}}else{if(!t||!t.length)throw new TypeError("Invalid event target");for(var d=0,l=t.length;d{"use strict";n.d(e,{T:()=>u}),n(99023);var r=n(64074),i=n(79917),o=n(64688),a=n(42178);function u(){for(var t=[],e=0;e1&&"number"==typeof t[t.length-1]&&(n=t.pop())):"number"==typeof s&&(n=t.pop()),null===u&&1===t.length&&t[0]instanceof r.y?t[0]:(0,o.J)(n)((0,a.n)(t,u))}},12309:(t,e,n)=>{"use strict";n.d(e,{of:()=>a});var r=n(79917),i=n(42178),o=n(75077);function a(){for(var t=[],e=0;e{"use strict";n.d(e,{S3:()=>s});var r=n(61699),i=n(24937),o=n(42178),a=n(64809),u=n(30121);function s(){for(var t=[],e=0;e{"use strict";n.d(e,{_:()=>i});var r=n(64074);function i(t,e){return e?new r.y((function(n){return e.schedule(o,0,{error:t,subscriber:n})})):new r.y((function(e){return e.error(t)}))}function o(t){var e=t.error;t.subscriber.error(e)}},12670:(t,e,n)=>{"use strict";n.d(e,{H:()=>u}),n(99023);var r=n(64074),i=n(26858),o=n(13491),a=n(79917);function u(t,e,n){void 0===t&&(t=0);var u=-1;return(0,o.k)(e)?u=Number(e)<1?1:Number(e):(0,a.K)(e)&&(n=e),(0,a.K)(n)||(n=i.P),new r.y((function(e){var r=(0,o.k)(t)?t:+t-n.now();return n.schedule(s,r,{index:0,period:u,subscriber:e})}))}function s(t){var e=t.index,n=t.period,r=t.subscriber;if(r.next(e),!r.closed){if(-1===n)return r.complete();t.index=e+1,this.schedule(t,n)}}},66436:(t,e,n)=>{"use strict";n.d(e,{$R:()=>c,mx:()=>d});var r=n(61699),i=n(42178),o=n(24937),a=n(90782),u=n(42e3),s=n(56431);function c(){for(var t=[],e=0;ethis.index},t.prototype.hasCompleted=function(){return this.array.length===this.index},t}(),h=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.parent=n,i.observable=r,i.stillUnsubscribed=!0,i.buffer=[],i.isComplete=!1,i}return r.__extends(e,t),e.prototype[u.hZ]=function(){return this},e.prototype.next=function(){var t=this.buffer;return 0===t.length&&this.isComplete?{value:null,done:!0}:{value:t.shift(),done:!1}},e.prototype.hasValue=function(){return this.buffer.length>0},e.prototype.hasCompleted=function(){return 0===this.buffer.length&&this.isComplete},e.prototype.notifyComplete=function(){this.buffer.length>0?(this.isComplete=!0,this.parent.notifyInactive()):this.destination.complete()},e.prototype.notifyNext=function(t){this.buffer.push(t),this.parent.checkIterators()},e.prototype.subscribe=function(){return(0,s.ft)(this.observable,new s.IY(this))},e}(s.Ds)},63660:(t,e,n)=>{"use strict";n.d(e,{K:()=>o});var r=n(61699),i=n(56431);function o(t){return function(e){var n=new a(t),r=e.lift(n);return n.caught=r}}var a=function(){function t(t){this.selector=t}return t.prototype.call=function(t,e){return e.subscribe(new u(t,this.selector,this.caught))},t}(),u=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.selector=n,i.caught=r,i}return r.__extends(e,t),e.prototype.error=function(e){if(!this.isStopped){var n=void 0;try{n=this.selector(e,this.caught)}catch(e){return void t.prototype.error.call(this,e)}this._unsubscribeAndRecycle();var r=new i.IY(this);this.add(r);var o=(0,i.ft)(n,r);o!==r&&this.add(o)}},e}(i.Ds)},54110:(t,e,n)=>{"use strict";n.d(e,{u:()=>i});var r=n(64688);function i(){return(0,r.J)(1)}},5026:(t,e,n)=>{"use strict";n.d(e,{g:()=>s});var r=n(61699),i=n(26858),o=n(79903),a=n(90782),u=n(48811);function s(t,e){void 0===e&&(e=i.P);var n=(0,o.J)(t)?+t-e.now():Math.abs(t);return function(t){return t.lift(new c(n,e))}}var c=function(){function t(t,e){this.delay=t,this.scheduler=e}return t.prototype.call=function(t,e){return e.subscribe(new d(t,this.delay,this.scheduler))},t}(),d=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.delay=n,i.scheduler=r,i.queue=[],i.active=!1,i.errored=!1,i}return r.__extends(e,t),e.dispatch=function(t){for(var e=t.source,n=e.queue,r=t.scheduler,i=t.destination;n.length>0&&n[0].time-r.now()<=0;)n.shift().notification.observe(i);if(n.length>0){var o=Math.max(0,n[0].time-r.now());this.schedule(t,o)}else this.unsubscribe(),e.active=!1},e.prototype._schedule=function(t){this.active=!0,this.destination.add(t.schedule(e.dispatch,this.delay,{source:this,destination:this.destination,scheduler:t}))},e.prototype.scheduleNotification=function(t){if(!0!==this.errored){var e=this.scheduler,n=new l(e.now()+this.delay,t);this.queue.push(n),!1===this.active&&this._schedule(e)}},e.prototype._next=function(t){this.scheduleNotification(u.P.createNext(t))},e.prototype._error=function(t){this.errored=!0,this.queue=[],this.destination.error(t),this.unsubscribe()},e.prototype._complete=function(){this.scheduleNotification(u.P.createComplete()),this.unsubscribe()},e}(a.L),l=function(){return function(t,e){this.time=t,this.notification=e}}()},57603:(t,e,n)=>{"use strict";n.d(e,{x:()=>o});var r=n(61699),i=n(90782);function o(t,e){return function(n){return n.lift(new a(t,e))}}var a=function(){function t(t,e){this.compare=t,this.keySelector=e}return t.prototype.call=function(t,e){return e.subscribe(new u(t,this.compare,this.keySelector))},t}(),u=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.keySelector=r,i.hasKey=!1,"function"==typeof n&&(i.compare=n),i}return r.__extends(e,t),e.prototype.compare=function(t,e){return t===e},e.prototype._next=function(t){var e;try{var n=this.keySelector;e=n?n(t):t}catch(t){return this.destination.error(t)}var r=!1;if(this.hasKey)try{r=(0,this.compare)(this.key,e)}catch(t){return this.destination.error(t)}else this.hasKey=!0;r||(this.key=e,this.destination.next(t))},e}(i.L)},20239:(t,e,n)=>{"use strict";n.d(e,{h:()=>o});var r=n(61699),i=n(90782);function o(t,e){return function(n){return n.lift(new a(t,e))}}var a=function(){function t(t,e){this.predicate=t,this.thisArg=e}return t.prototype.call=function(t,e){return e.subscribe(new u(t,this.predicate,this.thisArg))},t}(),u=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.predicate=n,i.thisArg=r,i.count=0,i}return r.__extends(e,t),e.prototype._next=function(t){var e;try{e=this.predicate.call(this.thisArg,t,this.count++)}catch(t){return void this.destination.error(t)}e&&this.destination.next(t)},e}(i.L)},82727:(t,e,n)=>{"use strict";n.d(e,{T:()=>f,v:()=>s}),n(38490),n(34897),n(40737),n(10951),n(71806),n(5193);var r=n(61699),i=n(90782),o=n(75838),a=n(64074),u=n(99357);function s(t,e,n,r){return function(i){return i.lift(new c(t,e,n,r))}}var c=function(){function t(t,e,n,r){this.keySelector=t,this.elementSelector=e,this.durationSelector=n,this.subjectSelector=r}return t.prototype.call=function(t,e){return e.subscribe(new d(t,this.keySelector,this.elementSelector,this.durationSelector,this.subjectSelector))},t}(),d=function(t){function e(e,n,r,i,o){var a=t.call(this,e)||this;return a.keySelector=n,a.elementSelector=r,a.durationSelector=i,a.subjectSelector=o,a.groups=null,a.attemptedToUnsubscribe=!1,a.count=0,a}return r.__extends(e,t),e.prototype._next=function(t){var e;try{e=this.keySelector(t)}catch(t){return void this.error(t)}this._group(t,e)},e.prototype._group=function(t,e){var n=this.groups;n||(n=this.groups=new Map);var r,i=n.get(e);if(this.elementSelector)try{r=this.elementSelector(t)}catch(t){this.error(t)}else r=t;if(!i){i=this.subjectSelector?this.subjectSelector():new u.xQ,n.set(e,i);var o=new f(e,i,this);if(this.destination.next(o),this.durationSelector){var a=void 0;try{a=this.durationSelector(new f(e,i))}catch(t){return void this.error(t)}this.add(a.subscribe(new l(e,i,this)))}}i.closed||i.next(r)},e.prototype._error=function(t){var e=this.groups;e&&(e.forEach((function(e,n){e.error(t)})),e.clear()),this.destination.error(t)},e.prototype._complete=function(){var t=this.groups;t&&(t.forEach((function(t,e){t.complete()})),t.clear()),this.destination.complete()},e.prototype.removeGroup=function(t){this.groups.delete(t)},e.prototype.unsubscribe=function(){this.closed||(this.attemptedToUnsubscribe=!0,0===this.count&&t.prototype.unsubscribe.call(this))},e}(i.L),l=function(t){function e(e,n,r){var i=t.call(this,n)||this;return i.key=e,i.group=n,i.parent=r,i}return r.__extends(e,t),e.prototype._next=function(t){this.complete()},e.prototype._unsubscribe=function(){var t=this.parent,e=this.key;this.key=this.parent=null,t&&t.removeGroup(e)},e}(i.L),f=function(t){function e(e,n,r){var i=t.call(this)||this;return i.key=e,i.groupSubject=n,i.refCountSubscription=r,i}return r.__extends(e,t),e.prototype._subscribe=function(t){var e=new o.w,n=this.refCountSubscription,r=this.groupSubject;return n&&!n.closed&&e.add(new p(n)),e.add(r.subscribe(t)),e},e}(a.y),p=function(t){function e(e){var n=t.call(this)||this;return n.parent=e,e.count++,n}return r.__extends(e,t),e.prototype.unsubscribe=function(){var e=this.parent;e.closed||this.closed||(t.prototype.unsubscribe.call(this),e.count-=1,0===e.count&&e.attemptedToUnsubscribe&&e.unsubscribe())},e}(o.w)},92160:(t,e,n)=>{"use strict";n.d(e,{U:()=>o});var r=n(61699),i=n(90782);function o(t,e){return function(n){if("function"!=typeof t)throw new TypeError("argument is not a function. Are you looking for `mapTo()`?");return n.lift(new a(t,e))}}var a=function(){function t(t,e){this.project=t,this.thisArg=e}return t.prototype.call=function(t,e){return e.subscribe(new u(t,this.project,this.thisArg))},t}(),u=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.project=n,i.count=0,i.thisArg=r||i,i}return r.__extends(e,t),e.prototype._next=function(t){var e;try{e=this.project.call(this.thisArg,t,this.count++)}catch(t){return void this.destination.error(t)}this.destination.next(e)},e}(i.L)},64688:(t,e,n)=>{"use strict";n.d(e,{J:()=>o}),n(99023);var r=n(61693),i=n(16726);function o(t){return void 0===t&&(t=Number.POSITIVE_INFINITY),(0,r.zg)(i.y,t)}},61693:(t,e,n)=>{"use strict";n.d(e,{VS:()=>d,zg:()=>u}),n(99023);var r=n(61699),i=n(92160),o=n(73531),a=n(56431);function u(t,e,n){return void 0===n&&(n=Number.POSITIVE_INFINITY),"function"==typeof e?function(r){return r.pipe(u((function(n,r){return(0,o.D)(t(n,r)).pipe((0,i.U)((function(t,i){return e(n,t,r,i)})))}),n))}:("number"==typeof e&&(n=e),function(e){return e.lift(new s(t,n))})}var s=function(){function t(t,e){void 0===e&&(e=Number.POSITIVE_INFINITY),this.project=t,this.concurrent=e}return t.prototype.call=function(t,e){return e.subscribe(new c(t,this.project,this.concurrent))},t}(),c=function(t){function e(e,n,r){void 0===r&&(r=Number.POSITIVE_INFINITY);var i=t.call(this,e)||this;return i.project=n,i.concurrent=r,i.hasCompleted=!1,i.buffer=[],i.active=0,i.index=0,i}return r.__extends(e,t),e.prototype._next=function(t){this.active0?this._next(t.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()},e}(a.Ds),d=u},9202:(t,e,n)=>{"use strict";n.d(e,{QV:()=>a,ht:()=>s});var r=n(61699),i=n(90782),o=n(48811);function a(t,e){return void 0===e&&(e=0),function(n){return n.lift(new u(t,e))}}var u=function(){function t(t,e){void 0===e&&(e=0),this.scheduler=t,this.delay=e}return t.prototype.call=function(t,e){return e.subscribe(new s(t,this.scheduler,this.delay))},t}(),s=function(t){function e(e,n,r){void 0===r&&(r=0);var i=t.call(this,e)||this;return i.scheduler=n,i.delay=r,i}return r.__extends(e,t),e.dispatch=function(t){var e=t.notification,n=t.destination;e.observe(n),this.unsubscribe()},e.prototype.scheduleMessage=function(t){this.destination.add(this.scheduler.schedule(e.dispatch,this.delay,new c(t,this.destination)))},e.prototype._next=function(t){this.scheduleMessage(o.P.createNext(t))},e.prototype._error=function(t){this.scheduleMessage(o.P.createError(t)),this.unsubscribe()},e.prototype._complete=function(){this.scheduleMessage(o.P.createComplete()),this.unsubscribe()},e}(i.L),c=function(){return function(t,e){this.notification=t,this.destination=e}}()},16807:(t,e,n)=>{"use strict";n.d(e,{x:()=>o});var r=n(61699),i=n(90782);function o(){return function(t){return t.lift(new a(t))}}var a=function(){function t(t){this.connectable=t}return t.prototype.call=function(t,e){var n=this.connectable;n._refCount++;var r=new u(t,n),i=e.subscribe(r);return r.closed||(r.connection=n.connect()),i},t}(),u=function(t){function e(e,n){var r=t.call(this,e)||this;return r.connectable=n,r}return r.__extends(e,t),e.prototype._unsubscribe=function(){var t=this.connectable;if(t){this.connectable=null;var e=t._refCount;if(e<=0)this.connection=null;else if(t._refCount=e-1,e>1)this.connection=null;else{var n=this.connection,r=t._connection;this.connection=null,!r||n&&r!==n||r.unsubscribe()}}else this.connection=null},e}(i.L)},62156:(t,e,n)=>{"use strict";n.d(e,{a:()=>a});var r=n(61699),i=n(99357),o=n(56431);function a(t){return function(e){return e.lift(new u(t,e))}}var u=function(){function t(t,e){this.notifier=t,this.source=e}return t.prototype.call=function(t,e){return e.subscribe(new s(t,this.notifier,this.source))},t}(),s=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.notifier=n,i.source=r,i}return r.__extends(e,t),e.prototype.error=function(e){if(!this.isStopped){var n=this.errors,r=this.retries,a=this.retriesSubscription;if(r)this.errors=void 0,this.retriesSubscription=void 0;else{n=new i.xQ;try{r=(0,this.notifier)(n)}catch(e){return t.prototype.error.call(this,e)}a=(0,o.ft)(r,new o.IY(this))}this._unsubscribeAndRecycle(),this.errors=n,this.retries=r,this.retriesSubscription=a,n.next(e)}},e.prototype._unsubscribe=function(){var t=this.errors,e=this.retriesSubscription;t&&(t.unsubscribe(),this.errors=void 0),e&&(e.unsubscribe(),this.retriesSubscription=void 0),this.retries=void 0},e.prototype.notifyNext=function(){var t=this._unsubscribe;this._unsubscribe=null,this._unsubscribeAndRecycle(),this._unsubscribe=t,this.source.subscribe(this)},e}(o.Ds)},7263:(t,e,n)=>{"use strict";n.d(e,{d:()=>o}),n(93942),n(70472),n(93270),n(38490),n(99023),n(40737),n(10951),n(5193);var r=n(28646);function i(t){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i(t)}function o(t,e,n){var o;return o=t&&"object"===i(t)?t:{bufferSize:t,windowTime:e,refCount:!1,scheduler:n},function(t){return t.lift(function(t){var e,n,i=t.bufferSize,o=void 0===i?Number.POSITIVE_INFINITY:i,a=t.windowTime,u=void 0===a?Number.POSITIVE_INFINITY:a,s=t.refCount,c=t.scheduler,d=0,l=!1,f=!1;return function(t){var i;d++,!e||l?(l=!1,e=new r.t(o,u,c),i=e.subscribe(this),n=t.subscribe({next:function(t){e.next(t)},error:function(t){l=!0,e.error(t)},complete:function(){f=!0,n=void 0,e.complete()}}),f&&(n=void 0)):i=e.subscribe(this),this.add((function(){d--,i.unsubscribe(),i=void 0,n&&!f&&s&&0===d&&(n.unsubscribe(),n=void 0,e=void 0)}))}}(o))}}},64440:(t,e,n)=>{"use strict";n.d(e,{w:()=>u});var r=n(61699),i=n(92160),o=n(73531),a=n(56431);function u(t,e){return"function"==typeof e?function(n){return n.pipe(u((function(n,r){return(0,o.D)(t(n,r)).pipe((0,i.U)((function(t,i){return e(n,t,r,i)})))})))}:function(e){return e.lift(new s(t))}}var s=function(){function t(t){this.project=t}return t.prototype.call=function(t,e){return e.subscribe(new c(t,this.project))},t}(),c=function(t){function e(e,n){var r=t.call(this,e)||this;return r.project=n,r.index=0,r}return r.__extends(e,t),e.prototype._next=function(t){var e,n=this.index++;try{e=this.project(t,n)}catch(t){return void this.destination.error(t)}this._innerSub(e)},e.prototype._innerSub=function(t){var e=this.innerSubscription;e&&e.unsubscribe();var n=new a.IY(this),r=this.destination;r.add(n),this.innerSubscription=(0,a.ft)(t,n),this.innerSubscription!==n&&r.add(this.innerSubscription)},e.prototype._complete=function(){var e=this.innerSubscription;e&&!e.closed||t.prototype._complete.call(this),this.unsubscribe()},e.prototype._unsubscribe=function(){this.innerSubscription=void 0},e.prototype.notifyComplete=function(){this.innerSubscription=void 0,this.isStopped&&t.prototype._complete.call(this)},e.prototype.notifyNext=function(t){this.destination.next(t)},e}(a.Ds)},31407:(t,e,n)=>{"use strict";n.d(e,{q:()=>u});var r=n(61699),i=n(90782),o=n(4069),a=n(14585);function u(t){return function(e){return 0===t?(0,a.c)():e.lift(new s(t))}}var s=function(){function t(t){if(this.total=t,this.total<0)throw new o.W}return t.prototype.call=function(t,e){return e.subscribe(new c(t,this.total))},t}(),c=function(t){function e(e,n){var r=t.call(this,e)||this;return r.total=n,r.count=0,r}return r.__extends(e,t),e.prototype._next=function(t){var e=this.total,n=++this.count;n<=e&&(this.destination.next(t),n===e&&(this.destination.complete(),this.unsubscribe()))},e}(i.L)},75077:(t,e,n)=>{"use strict";n.d(e,{r:()=>o});var r=n(64074),i=n(75838);function o(t,e){return new r.y((function(n){var r=new i.w,o=0;return r.add(e.schedule((function(){o!==t.length?(n.next(t[o++]),n.closed||r.add(this.schedule())):n.complete()}))),r}))}},77488:(t,e,n)=>{"use strict";n.d(e,{x:()=>l}),n(93942),n(70472),n(93270),n(38490),n(40737),n(10951),n(5193);var r=n(64074),i=n(75838),o=n(86916),a=n(75077),u=n(42e3),s=n(18316),c=n(56554);function d(t){return d="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},d(t)}function l(t,e){if(null!=t){if(function(t){return t&&"function"==typeof t[o.L]}(t))return function(t,e){return new r.y((function(n){var r=new i.w;return r.add(e.schedule((function(){var i=t[o.L]();r.add(i.subscribe({next:function(t){r.add(e.schedule((function(){return n.next(t)})))},error:function(t){r.add(e.schedule((function(){return n.error(t)})))},complete:function(){r.add(e.schedule((function(){return n.complete()})))}}))}))),r}))}(t,e);if((0,s.t)(t))return function(t,e){return new r.y((function(n){var r=new i.w;return r.add(e.schedule((function(){return t.then((function(t){r.add(e.schedule((function(){n.next(t),r.add(e.schedule((function(){return n.complete()})))})))}),(function(t){r.add(e.schedule((function(){return n.error(t)})))}))}))),r}))}(t,e);if((0,c.z)(t))return(0,a.r)(t,e);if(function(t){return t&&"function"==typeof t[u.hZ]}(t)||"string"==typeof t)return function(t,e){if(!t)throw new Error("Iterable cannot be null");return new r.y((function(n){var r,o=new i.w;return o.add((function(){r&&"function"==typeof r.return&&r.return()})),o.add(e.schedule((function(){r=t[u.hZ](),o.add(e.schedule((function(){if(!n.closed){var t,e;try{var i=r.next();t=i.value,e=i.done}catch(t){return void n.error(t)}e?n.complete():(n.next(t),this.schedule())}})))}))),o}))}(t,e)}throw new TypeError((null!==t&&d(t)||t)+" is not observable")}},674:(t,e,n)=>{"use strict";n.d(e,{o:()=>i}),n(6550),n(32345);var r=n(61699),i=function(t){function e(e,n){var r=t.call(this,e,n)||this;return r.scheduler=e,r.work=n,r.pending=!1,r}return r.__extends(e,t),e.prototype.schedule=function(t,e){if(void 0===e&&(e=0),this.closed)return this;this.state=t;var n=this.id,r=this.scheduler;return null!=n&&(this.id=this.recycleAsyncId(r,n,e)),this.pending=!0,this.delay=e,this.id=this.id||this.requestAsyncId(r,this.id,e),this},e.prototype.requestAsyncId=function(t,e,n){return void 0===n&&(n=0),setInterval(t.flush.bind(t,this),n)},e.prototype.recycleAsyncId=function(t,e,n){if(void 0===n&&(n=0),null!==n&&this.delay===n&&!1===this.pending)return e;clearInterval(e)},e.prototype.execute=function(t,e){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var n=this._execute(t,e);if(n)return n;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,e){var n=!1,r=void 0;try{this.work(t)}catch(t){n=!0,r=!!t&&t||new Error(t)}if(n)return this.unsubscribe(),r},e.prototype._unsubscribe=function(){var t=this.id,e=this.scheduler,n=e.actions,r=n.indexOf(this);this.work=null,this.state=null,this.pending=!1,this.scheduler=null,-1!==r&&n.splice(r,1),null!=t&&(this.id=this.recycleAsyncId(e,t,null)),this.delay=null},e}(function(t){function e(e,n){return t.call(this)||this}return r.__extends(e,t),e.prototype.schedule=function(t,e){return void 0===e&&(e=0),this},e}(n(75838).w))},41978:(t,e,n)=>{"use strict";n.d(e,{v:()=>o});var r=n(61699),i=n(78379),o=function(t){function e(n,r){void 0===r&&(r=i.b.now);var o=t.call(this,n,(function(){return e.delegate&&e.delegate!==o?e.delegate.now():r()}))||this;return o.actions=[],o.active=!1,o.scheduled=void 0,o}return r.__extends(e,t),e.prototype.schedule=function(n,r,i){return void 0===r&&(r=0),e.delegate&&e.delegate!==this?e.delegate.schedule(n,r,i):t.prototype.schedule.call(this,n,r,i)},e.prototype.flush=function(t){var e=this.actions;if(this.active)e.push(t);else{var n;this.active=!0;do{if(n=t.execute(t.state,t.delay))break}while(t=e.shift());if(this.active=!1,n){for(;t=e.shift();)t.unsubscribe();throw n}}},e}(i.b)},18420:(t,e,n)=>{"use strict";n.d(e,{e:()=>d,E:()=>c});var r=n(61699),i=(n(13722),n(40737),n(83823),1),o=function(){return Promise.resolve()}(),a={};function u(t){return t in a&&(delete a[t],!0)}var s=function(t){function e(e,n){var r=t.call(this,e,n)||this;return r.scheduler=e,r.work=n,r}return r.__extends(e,t),e.prototype.requestAsyncId=function(e,n,r){return void 0===r&&(r=0),null!==r&&r>0?t.prototype.requestAsyncId.call(this,e,n,r):(e.actions.push(this),e.scheduled||(e.scheduled=(s=e.flush.bind(e,null),c=i++,a[c]=!0,o.then((function(){return u(c)&&s()})),c)));var s,c},e.prototype.recycleAsyncId=function(e,n,r){if(void 0===r&&(r=0),null!==r&&r>0||null===r&&this.delay>0)return t.prototype.recycleAsyncId.call(this,e,n,r);0===e.actions.length&&(u(n),e.scheduled=void 0)},e}(n(674).o),c=new(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return r.__extends(e,t),e.prototype.flush=function(t){this.active=!0,this.scheduled=void 0;var e,n=this.actions,r=-1,i=n.length;t=t||n.shift();do{if(e=t.execute(t.state,t.delay))break}while(++r{"use strict";n.d(e,{P:()=>o,z:()=>i});var r=n(674),i=new(n(41978).v)(r.o),o=i},30396:(t,e,n)=>{"use strict";n.d(e,{c:()=>a,N:()=>o});var r=n(61699),i=function(t){function e(e,n){var r=t.call(this,e,n)||this;return r.scheduler=e,r.work=n,r}return r.__extends(e,t),e.prototype.schedule=function(e,n){return void 0===n&&(n=0),n>0?t.prototype.schedule.call(this,e,n):(this.delay=n,this.state=e,this.scheduler.flush(this),this)},e.prototype.execute=function(e,n){return n>0||this.closed?t.prototype.execute.call(this,e,n):this._execute(e,n)},e.prototype.requestAsyncId=function(e,n,r){return void 0===r&&(r=0),null!==r&&r>0||null===r&&this.delay>0?t.prototype.requestAsyncId.call(this,e,n,r):e.flush(this)},e}(n(674).o),o=new(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return r.__extends(e,t),e}(n(41978).v))(i),a=o},42e3:(t,e,n)=>{"use strict";function r(){return"function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator"}n.d(e,{hZ:()=>i}),n(93942),n(70472),n(93270),n(38490),n(40737),n(10951),n(5193);var i=r()},86916:(t,e,n)=>{"use strict";n.d(e,{L:()=>r}),n(93942),n(70472),n(40737);var r=function(){return"function"==typeof Symbol&&Symbol.observable||"@@observable"}()},70239:(t,e,n)=>{"use strict";n.d(e,{b:()=>r}),n(93942),n(70472),n(40737);var r=function(){return"function"==typeof Symbol?Symbol("rxSubscriber"):"@@rxSubscriber_"+Math.random()}()},4069:(t,e,n)=>{"use strict";n.d(e,{W:()=>r}),n(34745);var r=function(){function t(){return Error.call(this),this.message="argument out of range",this.name="ArgumentOutOfRangeError",this}return t.prototype=Object.create(Error.prototype),t}()},2246:(t,e,n)=>{"use strict";n.d(e,{K:()=>r}),n(34745);var r=function(){function t(){return Error.call(this),this.message="no elements in sequence",this.name="EmptyError",this}return t.prototype=Object.create(Error.prototype),t}()},42046:(t,e,n)=>{"use strict";n.d(e,{N:()=>r}),n(34745);var r=function(){function t(){return Error.call(this),this.message="object unsubscribed",this.name="ObjectUnsubscribedError",this}return t.prototype=Object.create(Error.prototype),t}()},76960:(t,e,n)=>{"use strict";n.d(e,{W:()=>r}),n(34745);var r=function(){function t(){return Error.call(this),this.message="Timeout has occurred",this.name="TimeoutError",this}return t.prototype=Object.create(Error.prototype),t}()},42135:(t,e,n)=>{"use strict";n.d(e,{B:()=>r}),n(64668),n(95412),n(34745),n(40737),n(26667);var r=function(){function t(t){return Error.call(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(t,e){return e+1+") "+t.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t,this}return t.prototype=Object.create(Error.prototype),t}()},12411:(t,e,n)=>{"use strict";n.d(e,{_:()=>i});var r=n(90782);function i(t){for(;t;){var e=t,n=e.closed,i=e.destination,o=e.isStopped;if(n||o)return!1;t=i&&i instanceof r.L?i:null}return!0}},61554:(t,e,n)=>{"use strict";function r(t){setTimeout((function(){throw t}),0)}n.d(e,{z:()=>r})},16726:(t,e,n)=>{"use strict";function r(t){return t}n.d(e,{y:()=>r})},24937:(t,e,n)=>{"use strict";n.d(e,{k:()=>r});var r=function(){return Array.isArray||function(t){return t&&"number"==typeof t.length}}()},56554:(t,e,n)=>{"use strict";n.d(e,{z:()=>r});var r=function(t){return t&&"number"==typeof t.length&&"function"!=typeof t}},79903:(t,e,n)=>{"use strict";function r(t){return t instanceof Date&&!isNaN(+t)}n.d(e,{J:()=>r})},11169:(t,e,n)=>{"use strict";function r(t){return"function"==typeof t}n.d(e,{m:()=>r})},13491:(t,e,n)=>{"use strict";n.d(e,{k:()=>i}),n(83681);var r=n(24937);function i(t){return!(0,r.k)(t)&&t-parseFloat(t)+1>=0}},46308:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function i(t){return null!==t&&"object"===r(t)}n.d(e,{K:()=>i}),n(93942),n(70472),n(93270),n(38490),n(40737),n(10951),n(5193)},18316:(t,e,n)=>{"use strict";function r(t){return!!t&&"function"!=typeof t.subscribe&&"function"==typeof t.then}n.d(e,{t:()=>r})},79917:(t,e,n)=>{"use strict";function r(t){return t&&"function"==typeof t.schedule}n.d(e,{K:()=>r})},38375:(t,e,n)=>{"use strict";function r(){}n.d(e,{Z:()=>r})},70696:(t,e,n)=>{"use strict";function r(t,e){function n(){return!n.pred.apply(n.thisArg,arguments)}return n.pred=t,n.thisArg=e,n}n.d(e,{f:()=>r})},76252:(t,e,n)=>{"use strict";n.d(e,{U:()=>o,z:()=>i});var r=n(16726);function i(){for(var t=[],e=0;e{"use strict";n.d(e,{s:()=>d});var r=n(97327),i=n(61554),o=n(42e3),a=n(86916),u=n(56554),s=n(18316),c=n(46308),d=function(t){if(t&&"function"==typeof t[a.L])return d=t,function(t){var e=d[a.L]();if("function"!=typeof e.subscribe)throw new TypeError("Provided object does not correctly implement Symbol.observable");return e.subscribe(t)};if((0,u.z)(t))return(0,r.V)(t);if((0,s.t)(t))return n=t,function(t){return n.then((function(e){t.closed||(t.next(e),t.complete())}),(function(e){return t.error(e)})).then(null,i.z),t};if(t&&"function"==typeof t[o.hZ])return e=t,function(t){for(var n=e[o.hZ]();;){var r=void 0;try{r=n.next()}catch(e){return t.error(e),t}if(r.done){t.complete();break}if(t.next(r.value),t.closed)break}return"function"==typeof n.return&&t.add((function(){n.return&&n.return()})),t};var e,n,d,l=(0,c.K)(t)?"an invalid object":"'"+t+"'";throw new TypeError("You provided "+l+" where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.")}},97327:(t,e,n)=>{"use strict";n.d(e,{V:()=>r});var r=function(t){return function(e){for(var n=0,r=t.length;n{"use strict";n.d(e,{D:()=>u});var r=n(61699),i=function(t){function e(e,n,r){var i=t.call(this)||this;return i.parent=e,i.outerValue=n,i.outerIndex=r,i.index=0,i}return r.__extends(e,t),e.prototype._next=function(t){this.parent.notifyNext(this.outerValue,t,this.outerIndex,this.index++,this)},e.prototype._error=function(t){this.parent.notifyError(t,this),this.unsubscribe()},e.prototype._complete=function(){this.parent.notifyComplete(this),this.unsubscribe()},e}(n(90782).L),o=n(28817),a=n(64074);function u(t,e,n,r,u){if(void 0===u&&(u=new i(t,n,r)),!u.closed)return e instanceof a.y?e.subscribe(u):(0,o.s)(e)(u)}},54752:(t,e,n)=>{"use strict";n.d(e,{Y:()=>a});var r=n(90782),i=n(70239),o=n(43610);function a(t,e,n){if(t){if(t instanceof r.L)return t;if(t[i.b])return t[i.b]()}return t||e||n?new r.L(t,e,n):new r.L(o.c)}},11065:(t,e,n)=>{"use strict";n.r(e),n.d(e,{audit:()=>o,auditTime:()=>d,buffer:()=>l,bufferCount:()=>y,bufferTime:()=>b,bufferToggle:()=>x,bufferWhen:()=>M,catchError:()=>L.K,combineAll:()=>j,combineLatest:()=>q,concat:()=>G,concatAll:()=>V.u,concatMap:()=>H,concatMapTo:()=>W,count:()=>K,debounce:()=>J,debounceTime:()=>tt,defaultIfEmpty:()=>it,delay:()=>ut.g,delayWhen:()=>ct,dematerialize:()=>ht,distinct:()=>vt,distinctUntilChanged:()=>bt.x,distinctUntilKeyChanged:()=>St,elementAt:()=>xt,endWith:()=>kt,every:()=>Mt,exhaust:()=>Lt,exhaustMap:()=>Ft,expand:()=>Gt,filter:()=>Ct.h,finalize:()=>Ht,find:()=>Zt,findIndex:()=>Qt,first:()=>te,flatMap:()=>Y.VS,groupBy:()=>ee.v,ignoreElements:()=>ne,isEmpty:()=>oe,last:()=>fe,map:()=>Ut.U,mapTo:()=>pe,materialize:()=>ve,max:()=>Ie,merge:()=>Ae,mergeAll:()=>Oe.J,mergeMap:()=>Y.zg,mergeMapTo:()=>Te,mergeScan:()=>xe,min:()=>Me,multicast:()=>De,observeOn:()=>ze.QV,onErrorResumeNext:()=>je,pairwise:()=>qe,partition:()=>Ye,pluck:()=>He,publish:()=>Ke,publishBehavior:()=>$e,publishLast:()=>Qe,publishReplay:()=>tn,race:()=>nn,reduce:()=>Ee,refCount:()=>hn.x,repeat:()=>rn,repeatWhen:()=>un,retry:()=>dn,retryWhen:()=>pn.a,sample:()=>yn,sampleTime:()=>gn,scan:()=>be,sequenceEqual:()=>wn,share:()=>An,shareReplay:()=>On.d,single:()=>Tn,skip:()=>kn,skipLast:()=>Dn,skipUntil:()=>jn,skipWhile:()=>qn,startWith:()=>Vn,subscribeOn:()=>Kn,switchAll:()=>Jn,switchMap:()=>$n.w,switchMapTo:()=>Qn,take:()=>Tt.q,takeLast:()=>ce,takeUntil:()=>Xn,takeWhile:()=>nr,tap:()=>ur,throttle:()=>lr,throttleTime:()=>hr,throwIfEmpty:()=>It,timeInterval:()=>_r,timeout:()=>Ar,timeoutWith:()=>Cr,timestamp:()=>Or,toArray:()=>Rr,window:()=>kr,windowCount:()=>Dr,windowTime:()=>jr,windowToggle:()=>Yr,windowWhen:()=>Kr,withLatestFrom:()=>Jr,zip:()=>ei,zipAll:()=>ni});var r=n(61699),i=n(56431);function o(t){return function(e){return e.lift(new a(t))}}var a=function(){function t(t){this.durationSelector=t}return t.prototype.call=function(t,e){return e.subscribe(new u(t,this.durationSelector))},t}(),u=function(t){function e(e,n){var r=t.call(this,e)||this;return r.durationSelector=n,r.hasValue=!1,r}return r.__extends(e,t),e.prototype._next=function(t){if(this.value=t,this.hasValue=!0,!this.throttled){var e=void 0;try{e=(0,this.durationSelector)(t)}catch(t){return this.destination.error(t)}var n=(0,i.ft)(e,new i.IY(this));!n||n.closed?this.clearThrottle():this.add(this.throttled=n)}},e.prototype.clearThrottle=function(){var t=this,e=t.value,n=t.hasValue,r=t.throttled;r&&(this.remove(r),this.throttled=void 0,r.unsubscribe()),n&&(this.value=void 0,this.hasValue=!1,this.destination.next(e))},e.prototype.notifyNext=function(){this.clearThrottle()},e.prototype.notifyComplete=function(){this.clearThrottle()},e}(i.Ds),s=n(26858),c=n(12670);function d(t,e){return void 0===e&&(e=s.P),o((function(){return(0,c.H)(t,e)}))}function l(t){return function(e){return e.lift(new f(t))}}var f=function(){function t(t){this.closingNotifier=t}return t.prototype.call=function(t,e){return e.subscribe(new p(t,this.closingNotifier))},t}(),p=function(t){function e(e,n){var r=t.call(this,e)||this;return r.buffer=[],r.add((0,i.ft)(n,new i.IY(r))),r}return r.__extends(e,t),e.prototype._next=function(t){this.buffer.push(t)},e.prototype.notifyNext=function(){var t=this.buffer;this.buffer=[],this.destination.next(t)},e}(i.Ds),h=(n(32345),n(90782));function y(t,e){return void 0===e&&(e=null),function(n){return n.lift(new m(t,e))}}var m=function(){function t(t,e){this.bufferSize=t,this.startBufferEvery=e,this.subscriberClass=e&&t!==e?g:v}return t.prototype.call=function(t,e){return e.subscribe(new this.subscriberClass(t,this.bufferSize,this.startBufferEvery))},t}(),v=function(t){function e(e,n){var r=t.call(this,e)||this;return r.bufferSize=n,r.buffer=[],r}return r.__extends(e,t),e.prototype._next=function(t){var e=this.buffer;e.push(t),e.length==this.bufferSize&&(this.destination.next(e),this.buffer=[])},e.prototype._complete=function(){var e=this.buffer;e.length>0&&this.destination.next(e),t.prototype._complete.call(this)},e}(h.L),g=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.bufferSize=n,i.startBufferEvery=r,i.buffers=[],i.count=0,i}return r.__extends(e,t),e.prototype._next=function(t){var e=this,n=e.bufferSize,r=e.startBufferEvery,i=e.buffers,o=e.count;this.count++,o%r==0&&i.push([]);for(var a=i.length;a--;){var u=i[a];u.push(t),u.length===n&&(i.splice(a,1),this.destination.next(u))}},e.prototype._complete=function(){for(var e=this.buffers,n=this.destination;e.length>0;){var r=e.shift();r.length>0&&n.next(r)}t.prototype._complete.call(this)},e}(h.L),_=(n(6550),n(99023),n(79917));function b(t){var e=arguments.length,n=s.P;(0,_.K)(arguments[arguments.length-1])&&(n=arguments[arguments.length-1],e--);var r=null;e>=2&&(r=arguments[1]);var i=Number.POSITIVE_INFINITY;return e>=3&&(i=arguments[2]),function(e){return e.lift(new S(t,r,i,n))}}var S=function(){function t(t,e,n,r){this.bufferTimeSpan=t,this.bufferCreationInterval=e,this.maxBufferSize=n,this.scheduler=r}return t.prototype.call=function(t,e){return e.subscribe(new C(t,this.bufferTimeSpan,this.bufferCreationInterval,this.maxBufferSize,this.scheduler))},t}(),w=function(){return function(){this.buffer=[]}}(),C=function(t){function e(e,n,r,i,o){var a=t.call(this,e)||this;a.bufferTimeSpan=n,a.bufferCreationInterval=r,a.maxBufferSize=i,a.scheduler=o,a.contexts=[];var u=a.openContext();if(a.timespanOnly=null==r||r<0,a.timespanOnly){var s={subscriber:a,context:u,bufferTimeSpan:n};a.add(u.closeAction=o.schedule(E,n,s))}else{var c={subscriber:a,context:u},d={bufferTimeSpan:n,bufferCreationInterval:r,subscriber:a,scheduler:o};a.add(u.closeAction=o.schedule(P,n,c)),a.add(o.schedule(I,r,d))}return a}return r.__extends(e,t),e.prototype._next=function(t){for(var e,n=this.contexts,r=n.length,i=0;i0;){var r=e.shift();n.next(r.buffer)}t.prototype._complete.call(this)},e.prototype._unsubscribe=function(){this.contexts=null},e.prototype.onBufferFull=function(t){this.closeContext(t);var e=t.closeAction;if(e.unsubscribe(),this.remove(e),!this.closed&&this.timespanOnly){t=this.openContext();var n=this.bufferTimeSpan,r={subscriber:this,context:t,bufferTimeSpan:n};this.add(t.closeAction=this.scheduler.schedule(E,n,r))}},e.prototype.openContext=function(){var t=new w;return this.contexts.push(t),t},e.prototype.closeContext=function(t){this.destination.next(t.buffer);var e=this.contexts;(e?e.indexOf(t):-1)>=0&&e.splice(e.indexOf(t),1)},e}(h.L);function E(t){var e=t.subscriber,n=t.context;n&&e.closeContext(n),e.closed||(t.context=e.openContext(),t.context.closeAction=this.schedule(t,t.bufferTimeSpan))}function I(t){var e=t.bufferCreationInterval,n=t.bufferTimeSpan,r=t.subscriber,i=t.scheduler,o=r.openContext();r.closed||(r.add(o.closeAction=i.schedule(P,n,{subscriber:r,context:o})),this.schedule(t,e))}function P(t){var e=t.subscriber,n=t.context;e.closeContext(n)}var A=n(75838),O=n(30121),T=n(64809);function x(t,e){return function(n){return n.lift(new R(t,e))}}var R=function(){function t(t,e){this.openings=t,this.closingSelector=e}return t.prototype.call=function(t,e){return e.subscribe(new k(t,this.openings,this.closingSelector))},t}(),k=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.closingSelector=r,i.contexts=[],i.add((0,O.D)(i,n)),i}return r.__extends(e,t),e.prototype._next=function(t){for(var e=this.contexts,n=e.length,r=0;r0;){var r=n.shift();r.subscription.unsubscribe(),r.buffer=null,r.subscription=null}this.contexts=null,t.prototype._error.call(this,e)},e.prototype._complete=function(){for(var e=this.contexts;e.length>0;){var n=e.shift();this.destination.next(n.buffer),n.subscription.unsubscribe(),n.buffer=null,n.subscription=null}this.contexts=null,t.prototype._complete.call(this)},e.prototype.notifyNext=function(t,e){t?this.closeBuffer(t):this.openBuffer(e)},e.prototype.notifyComplete=function(t){this.closeBuffer(t.context)},e.prototype.openBuffer=function(t){try{var e=this.closingSelector.call(this,t);e&&this.trySubscribe(e)}catch(t){this._error(t)}},e.prototype.closeBuffer=function(t){var e=this.contexts;if(e&&t){var n=t.buffer,r=t.subscription;this.destination.next(n),e.splice(e.indexOf(t),1),this.remove(r),r.unsubscribe()}},e.prototype.trySubscribe=function(t){var e=this.contexts,n=new A.w,r={buffer:[],subscription:n};e.push(r);var i=(0,O.D)(this,t,r);!i||i.closed?this.closeBuffer(r):(i.context=r,this.add(i),n.add(i))},e}(T.L);function M(t){return function(e){return e.lift(new N(t))}}var N=function(){function t(t){this.closingSelector=t}return t.prototype.call=function(t,e){return e.subscribe(new D(t,this.closingSelector))},t}(),D=function(t){function e(e,n){var r=t.call(this,e)||this;return r.closingSelector=n,r.subscribing=!1,r.openBuffer(),r}return r.__extends(e,t),e.prototype._next=function(t){this.buffer.push(t)},e.prototype._complete=function(){var e=this.buffer;e&&this.destination.next(e),t.prototype._complete.call(this)},e.prototype._unsubscribe=function(){this.buffer=void 0,this.subscribing=!1},e.prototype.notifyNext=function(){this.openBuffer()},e.prototype.notifyComplete=function(){this.subscribing?this.complete():this.openBuffer()},e.prototype.openBuffer=function(){var t=this.closingSubscription;t&&(this.remove(t),t.unsubscribe());var e,n=this.buffer;this.buffer&&this.destination.next(n),this.buffer=[];try{e=(0,this.closingSelector)()}catch(t){return this.error(t)}t=new A.w,this.closingSubscription=t,this.add(t),this.subscribing=!0,t.add((0,i.ft)(e,new i.IY(this))),this.subscribing=!1},e}(i.Ds),L=n(63660),z=n(12206);function j(t){return function(e){return e.lift(new z.Ms(t))}}n(88033),n(16516);var U=n(24937),F=n(73531);function q(){for(var t=[],e=0;e=2;return function(r){return r.pipe((0,Ct.h)((function(e,n){return n===t})),(0,Tt.q)(1),n?it(e):It((function(){return new wt.W})))}}var Rt=n(12309);function kt(){for(var t=[],e=0;e0&&this._next(t.shift()),this.hasCompleted&&0===this.active&&this.destination.complete()},e}(i.Ds);function Ht(t){return function(e){return e.lift(new Wt(t))}}var Wt=function(){function t(t){this.callback=t}return t.prototype.call=function(t,e){return e.subscribe(new Kt(t,this.callback))},t}(),Kt=function(t){function e(e,n){var r=t.call(this,e)||this;return r.add(new A.w(n)),r}return r.__extends(e,t),e}(h.L);function Zt(t,e){if("function"!=typeof t)throw new TypeError("predicate is not a function");return function(n){return n.lift(new $t(t,n,!1,e))}}var $t=function(){function t(t,e,n,r){this.predicate=t,this.source=e,this.yieldIndex=n,this.thisArg=r}return t.prototype.call=function(t,e){return e.subscribe(new Jt(t,this.predicate,this.source,this.yieldIndex,this.thisArg))},t}(),Jt=function(t){function e(e,n,r,i,o){var a=t.call(this,e)||this;return a.predicate=n,a.source=r,a.yieldIndex=i,a.thisArg=o,a.index=0,a}return r.__extends(e,t),e.prototype.notifyComplete=function(t){var e=this.destination;e.next(t),e.complete(),this.unsubscribe()},e.prototype._next=function(t){var e=this.predicate,n=this.thisArg,r=this.index++;try{e.call(n||this,t,r,this.source)&&this.notifyComplete(this.yieldIndex?r:t)}catch(t){this.destination.error(t)}},e.prototype._complete=function(){this.notifyComplete(this.yieldIndex?-1:void 0)},e}(h.L);function Qt(t,e){return function(n){return n.lift(new $t(t,n,!0,e))}}var Xt=n(16726);function te(t,e){var n=arguments.length>=2;return function(r){return r.pipe(t?(0,Ct.h)((function(e,n){return t(e,n,r)})):Xt.y,(0,Tt.q)(1),n?it(e):It((function(){return new Et.K})))}}var ee=n(82727);function ne(){return function(t){return t.lift(new re)}}var re=function(){function t(){}return t.prototype.call=function(t,e){return e.subscribe(new ie(t))},t}(),ie=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return r.__extends(e,t),e.prototype._next=function(t){},e}(h.L);function oe(){return function(t){return t.lift(new ae)}}var ae=function(){function t(){}return t.prototype.call=function(t,e){return e.subscribe(new ue(t))},t}(),ue=function(t){function e(e){return t.call(this,e)||this}return r.__extends(e,t),e.prototype.notifyComplete=function(t){var e=this.destination;e.next(t),e.complete()},e.prototype._next=function(t){this.notifyComplete(!1)},e.prototype._complete=function(){this.notifyComplete(!0)},e}(h.L),se=n(14585);function ce(t){return function(e){return 0===t?(0,se.c)():e.lift(new de(t))}}var de=function(){function t(t){if(this.total=t,this.total<0)throw new wt.W}return t.prototype.call=function(t,e){return e.subscribe(new le(t,this.total))},t}(),le=function(t){function e(e,n){var r=t.call(this,e)||this;return r.total=n,r.ring=new Array,r.count=0,r}return r.__extends(e,t),e.prototype._next=function(t){var e=this.ring,n=this.total,r=this.count++;e.length0)for(var n=this.count>=this.total?this.total:this.count,r=this.ring,i=0;i=2;return function(r){return r.pipe(t?(0,Ct.h)((function(e,n){return t(e,n,r)})):Xt.y,ce(1),n?it(e):It((function(){return new Et.K})))}}function pe(t){return function(e){return e.lift(new he(t))}}var he=function(){function t(t){this.value=t}return t.prototype.call=function(t,e){return e.subscribe(new ye(t,this.value))},t}(),ye=function(t){function e(e,n){var r=t.call(this,e)||this;return r.value=n,r}return r.__extends(e,t),e.prototype._next=function(t){this.destination.next(this.value)},e}(h.L),me=n(48811);function ve(){return function(t){return t.lift(new ge)}}var ge=function(){function t(){}return t.prototype.call=function(t,e){return e.subscribe(new _e(t))},t}(),_e=function(t){function e(e){return t.call(this,e)||this}return r.__extends(e,t),e.prototype._next=function(t){this.destination.next(me.P.createNext(t))},e.prototype._error=function(t){var e=this.destination;e.next(me.P.createError(t)),e.complete()},e.prototype._complete=function(){var t=this.destination;t.next(me.P.createComplete()),t.complete()},e}(h.L);function be(t,e){var n=!1;return arguments.length>=2&&(n=!0),function(r){return r.lift(new Se(t,e,n))}}var Se=function(){function t(t,e,n){void 0===n&&(n=!1),this.accumulator=t,this.seed=e,this.hasSeed=n}return t.prototype.call=function(t,e){return e.subscribe(new we(t,this.accumulator,this.seed,this.hasSeed))},t}(),we=function(t){function e(e,n,r,i){var o=t.call(this,e)||this;return o.accumulator=n,o._seed=r,o.hasSeed=i,o.index=0,o}return r.__extends(e,t),Object.defineProperty(e.prototype,"seed",{get:function(){return this._seed},set:function(t){this.hasSeed=!0,this._seed=t},enumerable:!0,configurable:!0}),e.prototype._next=function(t){if(this.hasSeed)return this._tryNext(t);this.seed=t,this.destination.next(t)},e.prototype._tryNext=function(t){var e,n=this.index++;try{e=this.accumulator(this.seed,t,n)}catch(t){this.destination.error(t)}this.seed=e,this.destination.next(e)},e}(h.L),Ce=n(76252);function Ee(t,e){return arguments.length>=2?function(n){return(0,Ce.z)(be(t,e),ce(1),it(e))(n)}:function(e){return(0,Ce.z)(be((function(e,n,r){return t(e,n,r+1)})),ce(1))(e)}}function Ie(t){return Ee("function"==typeof t?function(e,n){return t(e,n)>0?e:n}:function(t,e){return t>e?t:e})}var Pe=n(48864);function Ae(){for(var t=[],e=0;e0?this._next(t.shift()):0===this.active&&this.hasCompleted&&(!1===this.hasValue&&this.destination.next(this.acc),this.destination.complete())},e}(i.Ds);function Me(t){return Ee("function"==typeof t?function(e,n){return t(e,n)<0?e:n}:function(t,e){return t-1&&(this.count=n-1),e.subscribe(this._unsubscribeAndRecycle())}},e}(h.L);function un(t){return function(e){return e.lift(new sn(t))}}var sn=function(){function t(t){this.notifier=t}return t.prototype.call=function(t,e){return e.subscribe(new cn(t,this.notifier,e))},t}(),cn=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.notifier=n,i.source=r,i.sourceIsBeingSubscribedTo=!0,i}return r.__extends(e,t),e.prototype.notifyNext=function(){this.sourceIsBeingSubscribedTo=!0,this.source.subscribe(this)},e.prototype.notifyComplete=function(){if(!1===this.sourceIsBeingSubscribedTo)return t.prototype.complete.call(this)},e.prototype.complete=function(){if(this.sourceIsBeingSubscribedTo=!1,!this.isStopped){if(this.retries||this.subscribeToRetries(),!this.retriesSubscription||this.retriesSubscription.closed)return t.prototype.complete.call(this);this._unsubscribeAndRecycle(),this.notifications.next(void 0)}},e.prototype._unsubscribe=function(){var t=this.notifications,e=this.retriesSubscription;t&&(t.unsubscribe(),this.notifications=void 0),e&&(e.unsubscribe(),this.retriesSubscription=void 0),this.retries=void 0},e.prototype._unsubscribeAndRecycle=function(){var e=this._unsubscribe;return this._unsubscribe=null,t.prototype._unsubscribeAndRecycle.call(this),this._unsubscribe=e,this},e.prototype.subscribeToRetries=function(){var e;this.notifications=new We.xQ;try{e=(0,this.notifier)(this.notifications)}catch(e){return t.prototype.complete.call(this)}this.retries=e,this.retriesSubscription=(0,i.ft)(e,new i.IY(this))},e}(i.Ds);function dn(t){return void 0===t&&(t=-1),function(e){return e.lift(new ln(t,e))}}var ln=function(){function t(t,e){this.count=t,this.source=e}return t.prototype.call=function(t,e){return e.subscribe(new fn(t,this.count,this.source))},t}(),fn=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.count=n,i.source=r,i}return r.__extends(e,t),e.prototype.error=function(e){if(!this.isStopped){var n=this.source,r=this.count;if(0===r)return t.prototype.error.call(this,e);r>-1&&(this.count=r-1),n.subscribe(this._unsubscribeAndRecycle())}},e}(h.L),pn=n(62156),hn=n(16807);function yn(t){return function(e){return e.lift(new mn(t))}}var mn=function(){function t(t){this.notifier=t}return t.prototype.call=function(t,e){var n=new vn(t),r=e.subscribe(n);return r.add((0,i.ft)(this.notifier,new i.IY(n))),r},t}(),vn=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.hasValue=!1,e}return r.__extends(e,t),e.prototype._next=function(t){this.value=t,this.hasValue=!0},e.prototype.notifyNext=function(){this.emitValue()},e.prototype.notifyComplete=function(){this.emitValue()},e.prototype.emitValue=function(){this.hasValue&&(this.hasValue=!1,this.destination.next(this.value))},e}(i.Ds);function gn(t,e){return void 0===e&&(e=s.P),function(n){return n.lift(new _n(t,e))}}var _n=function(){function t(t,e){this.period=t,this.scheduler=e}return t.prototype.call=function(t,e){return e.subscribe(new bn(t,this.period,this.scheduler))},t}(),bn=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.period=n,i.scheduler=r,i.hasValue=!1,i.add(r.schedule(Sn,n,{subscriber:i,period:n})),i}return r.__extends(e,t),e.prototype._next=function(t){this.lastValue=t,this.hasValue=!0},e.prototype.notifyNext=function(){this.hasValue&&(this.hasValue=!1,this.destination.next(this.lastValue))},e}(h.L);function Sn(t){var e=t.subscriber,n=t.period;e.notifyNext(),this.schedule(t,n)}function wn(t,e){return function(n){return n.lift(new Cn(t,e))}}var Cn=function(){function t(t,e){this.compareTo=t,this.comparator=e}return t.prototype.call=function(t,e){return e.subscribe(new En(t,this.compareTo,this.comparator))},t}(),En=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.compareTo=n,i.comparator=r,i._a=[],i._b=[],i._oneComplete=!1,i.destination.add(n.subscribe(new In(e,i))),i}return r.__extends(e,t),e.prototype._next=function(t){this._oneComplete&&0===this._b.length?this.emit(!1):(this._a.push(t),this.checkValues())},e.prototype._complete=function(){this._oneComplete?this.emit(0===this._a.length&&0===this._b.length):this._oneComplete=!0,this.unsubscribe()},e.prototype.checkValues=function(){for(var t=this,e=t._a,n=t._b,r=t.comparator;e.length>0&&n.length>0;){var i=e.shift(),o=n.shift(),a=!1;try{a=r?r(i,o):i===o}catch(t){this.destination.error(t)}a||this.emit(!1)}},e.prototype.emit=function(t){var e=this.destination;e.next(t),e.complete()},e.prototype.nextB=function(t){this._oneComplete&&0===this._a.length?this.emit(!1):(this._b.push(t),this.checkValues())},e.prototype.completeB=function(){this._oneComplete?this.emit(0===this._a.length&&0===this._b.length):this._oneComplete=!0},e}(h.L),In=function(t){function e(e,n){var r=t.call(this,e)||this;return r.parent=n,r}return r.__extends(e,t),e.prototype._next=function(t){this.parent.nextB(t)},e.prototype._error=function(t){this.parent.error(t),this.unsubscribe()},e.prototype._complete=function(){this.parent.completeB(),this.unsubscribe()},e}(h.L);function Pn(){return new We.xQ}function An(){return function(t){return(0,hn.x)()(De(Pn)(t))}}var On=n(7263);function Tn(t){return function(e){return e.lift(new xn(t,e))}}var xn=function(){function t(t,e){this.predicate=t,this.source=e}return t.prototype.call=function(t,e){return e.subscribe(new Rn(t,this.predicate,this.source))},t}(),Rn=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.predicate=n,i.source=r,i.seenValue=!1,i.index=0,i}return r.__extends(e,t),e.prototype.applySingleValue=function(t){this.seenValue?this.destination.error("Sequence contains more than one element"):(this.seenValue=!0,this.singleValue=t)},e.prototype._next=function(t){var e=this.index++;this.predicate?this.tryNext(t,e):this.applySingleValue(t)},e.prototype.tryNext=function(t,e){try{this.predicate(t,e,this.source)&&this.applySingleValue(t)}catch(t){this.destination.error(t)}},e.prototype._complete=function(){var t=this.destination;this.index>0?(t.next(this.seenValue?this.singleValue:void 0),t.complete()):t.error(new Et.K)},e}(h.L);function kn(t){return function(e){return e.lift(new Mn(t))}}var Mn=function(){function t(t){this.total=t}return t.prototype.call=function(t,e){return e.subscribe(new Nn(t,this.total))},t}(),Nn=function(t){function e(e,n){var r=t.call(this,e)||this;return r.total=n,r.count=0,r}return r.__extends(e,t),e.prototype._next=function(t){++this.count>this.total&&this.destination.next(t)},e}(h.L);function Dn(t){return function(e){return e.lift(new Ln(t))}}var Ln=function(){function t(t){if(this._skipCount=t,this._skipCount<0)throw new wt.W}return t.prototype.call=function(t,e){return 0===this._skipCount?e.subscribe(new h.L(t)):e.subscribe(new zn(t,this._skipCount))},t}(),zn=function(t){function e(e,n){var r=t.call(this,e)||this;return r._skipCount=n,r._count=0,r._ring=new Array(n),r}return r.__extends(e,t),e.prototype._next=function(t){var e=this._skipCount,n=this._count++;if(n0?this.startWindowEvery:this.windowSize,n=this.destination,r=this.windowSize,i=this.windows,o=i.length,a=0;a=0&&u%e==0&&!this.closed&&i.shift().complete(),++this.count%e==0&&!this.closed){var s=new We.xQ;i.push(s),n.next(s)}},e.prototype._error=function(t){var e=this.windows;if(e)for(;e.length>0&&!this.closed;)e.shift().error(t);this.destination.error(t)},e.prototype._complete=function(){var t=this.windows;if(t)for(;t.length>0&&!this.closed;)t.shift().complete();this.destination.complete()},e.prototype._unsubscribe=function(){this.count=0,this.windows=null},e}(h.L);function jr(t){var e=s.P,n=null,r=Number.POSITIVE_INFINITY;return(0,_.K)(arguments[3])&&(e=arguments[3]),(0,_.K)(arguments[2])?e=arguments[2]:(0,Hn.k)(arguments[2])&&(r=Number(arguments[2])),(0,_.K)(arguments[1])?e=arguments[1]:(0,Hn.k)(arguments[1])&&(n=Number(arguments[1])),function(i){return i.lift(new Ur(t,n,r,e))}}var Ur=function(){function t(t,e,n,r){this.windowTimeSpan=t,this.windowCreationInterval=e,this.maxWindowSize=n,this.scheduler=r}return t.prototype.call=function(t,e){return e.subscribe(new qr(t,this.windowTimeSpan,this.windowCreationInterval,this.maxWindowSize,this.scheduler))},t}(),Fr=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._numberOfNextedValues=0,e}return r.__extends(e,t),e.prototype.next=function(e){this._numberOfNextedValues++,t.prototype.next.call(this,e)},Object.defineProperty(e.prototype,"numberOfNextedValues",{get:function(){return this._numberOfNextedValues},enumerable:!0,configurable:!0}),e}(We.xQ),qr=function(t){function e(e,n,r,i,o){var a=t.call(this,e)||this;a.destination=e,a.windowTimeSpan=n,a.windowCreationInterval=r,a.maxWindowSize=i,a.scheduler=o,a.windows=[];var u=a.openWindow();if(null!==r&&r>=0){var s={subscriber:a,window:u,context:null},c={windowTimeSpan:n,windowCreationInterval:r,subscriber:a,scheduler:o};a.add(o.schedule(Vr,n,s)),a.add(o.schedule(Gr,r,c))}else{var d={subscriber:a,window:u,windowTimeSpan:n};a.add(o.schedule(Br,n,d))}return a}return r.__extends(e,t),e.prototype._next=function(t){for(var e=this.windows,n=e.length,r=0;r=this.maxWindowSize&&this.closeWindow(i))}},e.prototype._error=function(t){for(var e=this.windows;e.length>0;)e.shift().error(t);this.destination.error(t)},e.prototype._complete=function(){for(var t=this.windows;t.length>0;){var e=t.shift();e.closed||e.complete()}this.destination.complete()},e.prototype.openWindow=function(){var t=new Fr;return this.windows.push(t),this.destination.next(t),t},e.prototype.closeWindow=function(t){t.complete();var e=this.windows;e.splice(e.indexOf(t),1)},e}(h.L);function Br(t){var e=t.subscriber,n=t.windowTimeSpan,r=t.window;r&&e.closeWindow(r),t.window=e.openWindow(),this.schedule(t,n)}function Gr(t){var e=t.windowTimeSpan,n=t.subscriber,r=t.scheduler,i=t.windowCreationInterval,o=n.openWindow(),a=this,u={action:a,subscription:null},s={subscriber:n,window:o,context:u};u.subscription=r.schedule(Vr,e,s),a.add(u.subscription),a.schedule(t,i)}function Vr(t){var e=t.subscriber,n=t.window,r=t.context;r&&r.action&&r.subscription&&r.action.remove(r.subscription),e.closeWindow(n)}function Yr(t,e){return function(n){return n.lift(new Hr(t,e))}}var Hr=function(){function t(t,e){this.openings=t,this.closingSelector=e}return t.prototype.call=function(t,e){return e.subscribe(new Wr(t,this.openings,this.closingSelector))},t}(),Wr=function(t){function e(e,n,r){var i=t.call(this,e)||this;return i.openings=n,i.closingSelector=r,i.contexts=[],i.add(i.openSubscription=(0,O.D)(i,n,n)),i}return r.__extends(e,t),e.prototype._next=function(t){var e=this.contexts;if(e)for(var n=e.length,r=0;r0){var i=r.indexOf(n);-1!==i&&r.splice(i,1)}},e.prototype.notifyComplete=function(){},e.prototype._next=function(t){if(0===this.toRespond.length){var e=[t].concat(this.values);this.project?this._tryProject(e):this.destination.next(e)}},e.prototype._tryProject=function(t){var e;try{e=this.project.apply(this,t)}catch(t){return void this.destination.error(t)}this.destination.next(e)},e}(T.L),ti=n(66436);function ei(){for(var t=[],e=0;e{function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(38490),n(13722),n(40737),n(10951),n(5193),t.exports=function(t,e,n,i){var o=n?n.call(i,t,e):void 0;if(void 0!==o)return!!o;if(t===e)return!0;if("object"!==r(t)||!t||"object"!==r(e)||!e)return!1;var a=Object.keys(t),u=Object.keys(e);if(a.length!==u.length)return!1;for(var s=Object.prototype.hasOwnProperty.bind(e),c=0;c{"use strict";n(6550),n(16516),t.exports=function(t,e){if("string"!=typeof t||"string"!=typeof e)throw new TypeError("Expected the arguments to be of type `string`");if(""===e)return[t];var n=t.indexOf(e);return-1===n?[t]:[t.slice(0,n),t.slice(n+e.length)]}},29590:(t,e,n)=>{"use strict";n(40737),n(26667),n(58443),t.exports=function(t){return encodeURIComponent(t).replace(/[!'()*]/g,(function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()}))}},61699:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n.r(e),n.d(e,{__assign:()=>a,__asyncDelegator:()=>S,__asyncGenerator:()=>b,__asyncValues:()=>w,__await:()=>_,__awaiter:()=>l,__classPrivateFieldGet:()=>P,__classPrivateFieldSet:()=>A,__createBinding:()=>p,__decorate:()=>s,__exportStar:()=>h,__extends:()=>o,__generator:()=>f,__importDefault:()=>I,__importStar:()=>E,__makeTemplateObject:()=>C,__metadata:()=>d,__param:()=>c,__read:()=>m,__rest:()=>u,__spread:()=>v,__spreadArrays:()=>g,__values:()=>y}),n(93942),n(70472),n(9190),n(93270),n(88033),n(6550),n(38490),n(27835),n(19926),n(28101),n(40737),n(83823),n(10951),n(5193);var i=function(t,e){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])},i(t,e)};function o(t,e){function n(){this.constructor=t}i(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var a=function(){return a=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=0;s--)(o=t[s])&&(u=(a<3?o(u):a>3?o(e,n,u):o(e,n))||u);return a>3&&u&&Object.defineProperty(e,n,u),u}function c(t,e){return function(n,r){e(n,r,t)}}function d(t,e){if("object"===("undefined"==typeof Reflect?"undefined":r(Reflect))&&"function"==typeof Reflect.metadata)return Reflect.metadata(t,e)}function l(t,e,n,r){return new(n||(n=Promise))((function(i,o){function a(t){try{s(r.next(t))}catch(t){o(t)}}function u(t){try{s(r.throw(t))}catch(t){o(t)}}function s(t){var e;t.done?i(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(a,u)}s((r=r.apply(t,e||[])).next())}))}function f(t,e){var n,r,i,o,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function m(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,i,o=n.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(r=o.next()).done;)a.push(r.value)}catch(t){i={error:t}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return a}function v(){for(var t=[],e=0;e1||u(t,e)}))})}function u(t,e){try{(n=i[t](e)).value instanceof _?Promise.resolve(n.value.v).then(s,c):d(o[0][2],n)}catch(t){d(o[0][3],t)}var n}function s(t){u("next",t)}function c(t){u("throw",t)}function d(t,e){t(e),o.shift(),o.length&&u(o[0][0],o[0][1])}}function S(t){var e,n;return e={},r("next"),r("throw",(function(t){throw t})),r("return"),e[Symbol.iterator]=function(){return this},e;function r(r,i){e[r]=t[r]?function(e){return(n=!n)?{value:_(t[r](e)),done:"return"===r}:i?i(e):e}:i}}function w(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,n=t[Symbol.asyncIterator];return n?n.call(t):(t=y(t),e={},r("next"),r("throw"),r("return"),e[Symbol.asyncIterator]=function(){return this},e);function r(n){e[n]=t[n]&&function(e){return new Promise((function(r,i){!function(t,e,n,r){Promise.resolve(r).then((function(e){t({value:e,done:n})}),e)}(r,i,(e=t[n](e)).done,e.value)}))}}}function C(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function E(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function I(t){return t&&t.__esModule?t:{default:t}}function P(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function A(t,e,n){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,n),n}},86173:(t,e,n)=>{var r=n(34028),i=n(84160),o=TypeError;t.exports=function(t){if(r(t))return t;throw o(i(t)+" is not a function")}},52023:(t,e,n)=>{var r=n(78449),i=n(84160),o=TypeError;t.exports=function(t){if(r(t))return t;throw o(i(t)+" is not a constructor")}},41684:(t,e,n)=>{var r=n(34028),i=String,o=TypeError;t.exports=function(t){if("object"==typeof t||r(t))return t;throw o("Can't set "+i(t)+" as a prototype")}},47512:(t,e,n)=>{var r=n(30191),i=n(13250),o=n(43087).f,a=r("unscopables"),u=Array.prototype;null==u[a]&&o(u,a,{configurable:!0,value:i(null)}),t.exports=function(t){u[a][t]=!0}},75527:(t,e,n)=>{"use strict";var r=n(58402).charAt;t.exports=function(t,e,n){return e+(n?r(t,e).length:1)}},39837:(t,e,n)=>{var r=n(27357),i=TypeError;t.exports=function(t,e){if(r(e,t))return t;throw i("Incorrect invocation")}},52546:(t,e,n)=>{var r=n(51355),i=String,o=TypeError;t.exports=function(t){if(r(t))return t;throw o(i(t)+" is not an object")}},68096:t=>{t.exports="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView},1743:(t,e,n)=>{var r=n(38986);t.exports=r((function(){if("function"==typeof ArrayBuffer){var t=new ArrayBuffer(8);Object.isExtensible(t)&&Object.defineProperty(t,"a",{value:8})}}))},65140:(t,e,n)=>{"use strict";var r=n(32022),i=n(59913),o=n(12115),a=n(68096),u=n(27765),s=n(22775),c=n(3193),d=n(38986),l=n(39837),f=n(75982),p=n(9375),h=n(91173),y=n(38108),m=n(75783),v=n(25466),g=n(92775).f,_=n(43087).f,b=n(13750),S=n(42893),w=n(27747),C=n(78045),E=u.PROPER,I=u.CONFIGURABLE,P=C.get,A=C.set,O="ArrayBuffer",T="DataView",x="prototype",R="Wrong index",k=r[O],M=k,N=M&&M[x],D=r[T],L=D&&D[x],z=Object.prototype,j=r.Array,U=r.RangeError,F=i(b),q=i([].reverse),B=y.pack,G=y.unpack,V=function(t){return[255&t]},Y=function(t){return[255&t,t>>8&255]},H=function(t){return[255&t,t>>8&255,t>>16&255,t>>24&255]},W=function(t){return t[3]<<24|t[2]<<16|t[1]<<8|t[0]},K=function(t){return B(t,23,4)},Z=function(t){return B(t,52,8)},$=function(t,e){_(t[x],e,{get:function(){return P(this)[e]}})},J=function(t,e,n,r){var i=h(n),o=P(t);if(i+e>o.byteLength)throw U(R);var a=P(o.buffer).bytes,u=i+o.byteOffset,s=S(a,u,u+e);return r?s:q(s)},Q=function(t,e,n,r,i,o){var a=h(n),u=P(t);if(a+e>u.byteLength)throw U(R);for(var s=P(u.buffer).bytes,c=a+u.byteOffset,d=r(+i),l=0;lnt;)(tt=et[nt++])in M||s(M,tt,k[tt]);N.constructor=M}v&&m(L)!==z&&v(L,z);var rt=new D(new M(2)),it=i(L.setInt8);rt.setInt8(0,2147483648),rt.setInt8(1,2147483649),!rt.getInt8(0)&&rt.getInt8(1)||c(L,{setInt8:function(t,e){it(this,t,e<<24>>24)},setUint8:function(t,e){it(this,t,e<<24>>24)}},{unsafe:!0})}else N=(M=function(t){l(this,N);var e=h(t);A(this,{bytes:F(j(e),0),byteLength:e}),o||(this.byteLength=e)})[x],L=(D=function(t,e,n){l(this,L),l(t,N);var r=P(t).byteLength,i=f(e);if(i<0||i>r)throw U("Wrong offset");if(i+(n=void 0===n?r-i:p(n))>r)throw U("Wrong length");A(this,{buffer:t,byteLength:n,byteOffset:i}),o||(this.buffer=t,this.byteLength=n,this.byteOffset=i)})[x],o&&($(M,"byteLength"),$(D,"buffer"),$(D,"byteLength"),$(D,"byteOffset")),c(L,{getInt8:function(t){return J(this,1,t)[0]<<24>>24},getUint8:function(t){return J(this,1,t)[0]},getInt16:function(t){var e=J(this,2,t,arguments.length>1?arguments[1]:void 0);return(e[1]<<8|e[0])<<16>>16},getUint16:function(t){var e=J(this,2,t,arguments.length>1?arguments[1]:void 0);return e[1]<<8|e[0]},getInt32:function(t){return W(J(this,4,t,arguments.length>1?arguments[1]:void 0))},getUint32:function(t){return W(J(this,4,t,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(t){return G(J(this,4,t,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(t){return G(J(this,8,t,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(t,e){Q(this,1,t,V,e)},setUint8:function(t,e){Q(this,1,t,V,e)},setInt16:function(t,e){Q(this,2,t,Y,e,arguments.length>2?arguments[2]:void 0)},setUint16:function(t,e){Q(this,2,t,Y,e,arguments.length>2?arguments[2]:void 0)},setInt32:function(t,e){Q(this,4,t,H,e,arguments.length>2?arguments[2]:void 0)},setUint32:function(t,e){Q(this,4,t,H,e,arguments.length>2?arguments[2]:void 0)},setFloat32:function(t,e){Q(this,4,t,K,e,arguments.length>2?arguments[2]:void 0)},setFloat64:function(t,e){Q(this,8,t,Z,e,arguments.length>2?arguments[2]:void 0)}});w(M,O),w(D,T),t.exports={ArrayBuffer:M,DataView:D}},13750:(t,e,n)=>{"use strict";var r=n(47137),i=n(86593),o=n(84117);t.exports=function(t){for(var e=r(this),n=o(e),a=arguments.length,u=i(a>1?arguments[1]:void 0,n),s=a>2?arguments[2]:void 0,c=void 0===s?n:i(s,n);c>u;)e[u++]=t;return e}},33609:(t,e,n)=>{"use strict";var r=n(55883).forEach,i=n(94694)("forEach");t.exports=i?[].forEach:function(t){return r(this,t,arguments.length>1?arguments[1]:void 0)}},65375:(t,e,n)=>{"use strict";var r=n(80391),i=n(49425),o=n(47137),a=n(7701),u=n(92882),s=n(78449),c=n(84117),d=n(19402),l=n(32057),f=n(6897),p=Array;t.exports=function(t){var e=o(t),n=s(this),h=arguments.length,y=h>1?arguments[1]:void 0,m=void 0!==y;m&&(y=r(y,h>2?arguments[2]:void 0));var v,g,_,b,S,w,C=f(e),E=0;if(!C||this===p&&u(C))for(v=c(e),g=n?new this(v):p(v);v>E;E++)w=m?y(e[E],E):e[E],d(g,E,w);else for(S=(b=l(e,C)).next,g=n?new this:[];!(_=i(S,b)).done;E++)w=m?a(b,y,[_.value,E],!0):_.value,d(g,E,w);return g.length=E,g}},78035:(t,e,n)=>{var r=n(58326),i=n(86593),o=n(84117),a=function(t){return function(e,n,a){var u,s=r(e),c=o(s),d=i(a,c);if(t&&n!=n){for(;c>d;)if((u=s[d++])!=u)return!0}else for(;c>d;d++)if((t||d in s)&&s[d]===n)return t||d||0;return!t&&-1}};t.exports={includes:a(!0),indexOf:a(!1)}},55883:(t,e,n)=>{var r=n(80391),i=n(59913),o=n(94032),a=n(47137),u=n(84117),s=n(74842),c=i([].push),d=function(t){var e=1==t,n=2==t,i=3==t,d=4==t,l=6==t,f=7==t,p=5==t||l;return function(h,y,m,v){for(var g,_,b=a(h),S=o(b),w=r(y,m),C=u(S),E=0,I=v||s,P=e?I(h,C):n||f?I(h,0):void 0;C>E;E++)if((p||E in S)&&(_=w(g=S[E],E,b),t))if(e)P[E]=_;else if(_)switch(t){case 3:return!0;case 5:return g;case 6:return E;case 2:c(P,g)}else switch(t){case 4:return!1;case 7:c(P,g)}return l?-1:i||d?d:P}};t.exports={forEach:d(0),map:d(1),filter:d(2),some:d(3),every:d(4),find:d(5),findIndex:d(6),filterReject:d(7)}},44687:(t,e,n)=>{"use strict";var r=n(10584),i=n(58326),o=n(75982),a=n(84117),u=n(94694),s=Math.min,c=[].lastIndexOf,d=!!c&&1/[1].lastIndexOf(1,-0)<0,l=u("lastIndexOf"),f=d||!l;t.exports=f?function(t){if(d)return r(c,this,arguments)||0;var e=i(this),n=a(e),u=n-1;for(arguments.length>1&&(u=s(u,o(arguments[1]))),u<0&&(u=n+u);u>=0;u--)if(u in e&&e[u]===t)return u||0;return-1}:c},41665:(t,e,n)=>{var r=n(38986),i=n(30191),o=n(80714),a=i("species");t.exports=function(t){return o>=51||!r((function(){var e=[];return(e.constructor={})[a]=function(){return{foo:1}},1!==e[t](Boolean).foo}))}},94694:(t,e,n)=>{"use strict";var r=n(38986);t.exports=function(t,e){var n=[][t];return!!n&&r((function(){n.call(null,e||function(){return 1},1)}))}},17761:(t,e,n)=>{"use strict";var r=n(12115),i=n(65351),o=TypeError,a=Object.getOwnPropertyDescriptor,u=r&&!function(){if(void 0!==this)return!0;try{Object.defineProperty([],"length",{writable:!1}).length=1}catch(t){return t instanceof TypeError}}();t.exports=u?function(t,e){if(i(t)&&!a(t,"length").writable)throw o("Cannot set read only .length");return t.length=e}:function(t,e){return t.length=e}},42893:(t,e,n)=>{var r=n(86593),i=n(84117),o=n(19402),a=Array,u=Math.max;t.exports=function(t,e,n){for(var s=i(t),c=r(e,s),d=r(void 0===n?s:n,s),l=a(u(d-c,0)),f=0;c{var r=n(59913);t.exports=r([].slice)},71929:(t,e,n)=>{var r=n(42893),i=Math.floor,o=function(t,e){var n=t.length,s=i(n/2);return n<8?a(t,e):u(t,o(r(t,0,s),e),o(r(t,s),e),e)},a=function(t,e){for(var n,r,i=t.length,o=1;o0;)t[r]=t[--r];r!==o++&&(t[r]=n)}return t},u=function(t,e,n,r){for(var i=e.length,o=n.length,a=0,u=0;a{var r=n(65351),i=n(78449),o=n(51355),a=n(30191)("species"),u=Array;t.exports=function(t){var e;return r(t)&&(e=t.constructor,(i(e)&&(e===u||r(e.prototype))||o(e)&&null===(e=e[a]))&&(e=void 0)),void 0===e?u:e}},74842:(t,e,n)=>{var r=n(78502);t.exports=function(t,e){return new(r(t))(0===e?0:e)}},7701:(t,e,n)=>{var r=n(52546),i=n(94681);t.exports=function(t,e,n,o){try{return o?e(r(n)[0],n[1]):e(n)}catch(e){i(t,"throw",e)}}},41269:(t,e,n)=>{var r=n(30191)("iterator"),i=!1;try{var o=0,a={next:function(){return{done:!!o++}},return:function(){i=!0}};a[r]=function(){return this},Array.from(a,(function(){throw 2}))}catch(t){}t.exports=function(t,e){if(!e&&!i)return!1;var n=!1;try{var o={};o[r]=function(){return{next:function(){return{done:n=!0}}}},t(o)}catch(t){}return n}},39523:(t,e,n)=>{var r=n(59913),i=r({}.toString),o=r("".slice);t.exports=function(t){return o(i(t),8,-1)}},82814:(t,e,n)=>{var r=n(77568),i=n(34028),o=n(39523),a=n(30191)("toStringTag"),u=Object,s="Arguments"==o(function(){return arguments}());t.exports=r?o:function(t){var e,n,r;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(n=function(t,e){try{return t[e]}catch(t){}}(e=u(t),a))?n:s?o(e):"Object"==(r=o(e))&&i(e.callee)?"Arguments":r}},61961:(t,e,n)=>{"use strict";var r=n(43087).f,i=n(13250),o=n(3193),a=n(80391),u=n(39837),s=n(87126),c=n(38640),d=n(53338),l=n(80251),f=n(42343),p=n(12115),h=n(67023).fastKey,y=n(78045),m=y.set,v=y.getterFor;t.exports={getConstructor:function(t,e,n,d){var l=t((function(t,r){u(t,f),m(t,{type:e,index:i(null),first:void 0,last:void 0,size:0}),p||(t.size=0),s(r)||c(r,t[d],{that:t,AS_ENTRIES:n})})),f=l.prototype,y=v(e),g=function(t,e,n){var r,i,o=y(t),a=_(t,e);return a?a.value=n:(o.last=a={index:i=h(e,!0),key:e,value:n,previous:r=o.last,next:void 0,removed:!1},o.first||(o.first=a),r&&(r.next=a),p?o.size++:t.size++,"F"!==i&&(o.index[i]=a)),t},_=function(t,e){var n,r=y(t),i=h(e);if("F"!==i)return r.index[i];for(n=r.first;n;n=n.next)if(n.key==e)return n};return o(f,{clear:function(){for(var t=y(this),e=t.index,n=t.first;n;)n.removed=!0,n.previous&&(n.previous=n.previous.next=void 0),delete e[n.index],n=n.next;t.first=t.last=void 0,p?t.size=0:this.size=0},delete:function(t){var e=this,n=y(e),r=_(e,t);if(r){var i=r.next,o=r.previous;delete n.index[r.index],r.removed=!0,o&&(o.next=i),i&&(i.previous=o),n.first==r&&(n.first=i),n.last==r&&(n.last=o),p?n.size--:e.size--}return!!r},forEach:function(t){for(var e,n=y(this),r=a(t,arguments.length>1?arguments[1]:void 0);e=e?e.next:n.first;)for(r(e.value,e.key,this);e&&e.removed;)e=e.previous},has:function(t){return!!_(this,t)}}),o(f,n?{get:function(t){var e=_(this,t);return e&&e.value},set:function(t,e){return g(this,0===t?0:t,e)}}:{add:function(t){return g(this,t=0===t?0:t,t)}}),p&&r(f,"size",{get:function(){return y(this).size}}),l},setStrong:function(t,e,n){var r=e+" Iterator",i=v(e),o=v(r);d(t,e,(function(t,e){m(this,{type:r,target:t,state:i(t),kind:e,last:void 0})}),(function(){for(var t=o(this),e=t.kind,n=t.last;n&&n.removed;)n=n.previous;return t.target&&(t.last=n=n?n.next:t.state.first)?l("keys"==e?n.key:"values"==e?n.value:[n.key,n.value],!1):(t.target=void 0,l(void 0,!0))}),n?"entries":"values",!n,!0),f(e)}}},31858:(t,e,n)=>{"use strict";var r=n(59913),i=n(3193),o=n(67023).getWeakData,a=n(39837),u=n(52546),s=n(87126),c=n(51355),d=n(38640),l=n(55883),f=n(98511),p=n(78045),h=p.set,y=p.getterFor,m=l.find,v=l.findIndex,g=r([].splice),_=0,b=function(t){return t.frozen||(t.frozen=new S)},S=function(){this.entries=[]},w=function(t,e){return m(t.entries,(function(t){return t[0]===e}))};S.prototype={get:function(t){var e=w(this,t);if(e)return e[1]},has:function(t){return!!w(this,t)},set:function(t,e){var n=w(this,t);n?n[1]=e:this.entries.push([t,e])},delete:function(t){var e=v(this.entries,(function(e){return e[0]===t}));return~e&&g(this.entries,e,1),!!~e}},t.exports={getConstructor:function(t,e,n,r){var l=t((function(t,i){a(t,p),h(t,{type:e,id:_++,frozen:void 0}),s(i)||d(i,t[r],{that:t,AS_ENTRIES:n})})),p=l.prototype,m=y(e),v=function(t,e,n){var r=m(t),i=o(u(e),!0);return!0===i?b(r).set(e,n):i[r.id]=n,t};return i(p,{delete:function(t){var e=m(this);if(!c(t))return!1;var n=o(t);return!0===n?b(e).delete(t):n&&f(n,e.id)&&delete n[e.id]},has:function(t){var e=m(this);if(!c(t))return!1;var n=o(t);return!0===n?b(e).has(t):n&&f(n,e.id)}}),i(p,n?{get:function(t){var e=m(this);if(c(t)){var n=o(t);return!0===n?b(e).get(t):n?n[e.id]:void 0}},set:function(t,e){return v(this,t,e)}}:{add:function(t){return v(this,t,!0)}}),l}}},69866:(t,e,n)=>{"use strict";var r=n(54635),i=n(32022),o=n(59913),a=n(77987),u=n(43068),s=n(67023),c=n(38640),d=n(39837),l=n(34028),f=n(87126),p=n(51355),h=n(38986),y=n(41269),m=n(27747),v=n(99618);t.exports=function(t,e,n){var g=-1!==t.indexOf("Map"),_=-1!==t.indexOf("Weak"),b=g?"set":"add",S=i[t],w=S&&S.prototype,C=S,E={},I=function(t){var e=o(w[t]);u(w,t,"add"==t?function(t){return e(this,0===t?0:t),this}:"delete"==t?function(t){return!(_&&!p(t))&&e(this,0===t?0:t)}:"get"==t?function(t){return _&&!p(t)?void 0:e(this,0===t?0:t)}:"has"==t?function(t){return!(_&&!p(t))&&e(this,0===t?0:t)}:function(t,n){return e(this,0===t?0:t,n),this})};if(a(t,!l(S)||!(_||w.forEach&&!h((function(){(new S).entries().next()})))))C=n.getConstructor(e,t,g,b),s.enable();else if(a(t,!0)){var P=new C,A=P[b](_?{}:-0,1)!=P,O=h((function(){P.has(1)})),T=y((function(t){new S(t)})),x=!_&&h((function(){for(var t=new S,e=5;e--;)t[b](e,e);return!t.has(-0)}));T||((C=e((function(t,e){d(t,w);var n=v(new S,t,C);return f(e)||c(e,n[b],{that:n,AS_ENTRIES:g}),n}))).prototype=w,w.constructor=C),(O||x)&&(I("delete"),I("has"),g&&I("get")),(x||A)&&I(b),_&&w.clear&&delete w.clear}return E[t]=C,r({global:!0,constructor:!0,forced:C!=S},E),m(C,t),_||n.setStrong(C,t,g),C}},74953:(t,e,n)=>{var r=n(98511),i=n(91537),o=n(66213),a=n(43087);t.exports=function(t,e,n){for(var u=i(e),s=a.f,c=o.f,d=0;d{var r=n(30191)("match");t.exports=function(t){var e=/./;try{"/./"[t](e)}catch(n){try{return e[r]=!1,"/./"[t](e)}catch(t){}}return!1}},88538:(t,e,n)=>{var r=n(38986);t.exports=!r((function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype}))},89444:(t,e,n)=>{var r=n(59913),i=n(31591),o=n(74170),a=/"/g,u=r("".replace);t.exports=function(t,e,n,r){var s=o(i(t)),c="<"+e;return""!==n&&(c+=" "+n+'="'+u(o(r),a,""")+'"'),c+">"+s+""}},80251:t=>{t.exports=function(t,e){return{value:t,done:e}}},22775:(t,e,n)=>{var r=n(12115),i=n(43087),o=n(71111);t.exports=r?function(t,e,n){return i.f(t,e,o(1,n))}:function(t,e,n){return t[e]=n,t}},71111:t=>{t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},19402:(t,e,n)=>{"use strict";var r=n(79127),i=n(43087),o=n(71111);t.exports=function(t,e,n){var a=r(e);a in t?i.f(t,a,o(0,n)):t[a]=n}},68959:(t,e,n)=>{"use strict";var r=n(52546),i=n(93126),o=TypeError;t.exports=function(t){if(r(this),"string"===t||"default"===t)t="string";else if("number"!==t)throw o("Incorrect hint");return i(this,t)}},43068:(t,e,n)=>{var r=n(34028),i=n(43087),o=n(43608),a=n(97210);t.exports=function(t,e,n,u){u||(u={});var s=u.enumerable,c=void 0!==u.name?u.name:e;if(r(n)&&o(n,c,u),u.global)s?t[e]=n:a(e,n);else{try{u.unsafe?t[e]&&(s=!0):delete t[e]}catch(t){}s?t[e]=n:i.f(t,e,{value:n,enumerable:!1,configurable:!u.nonConfigurable,writable:!u.nonWritable})}return t}},3193:(t,e,n)=>{var r=n(43068);t.exports=function(t,e,n){for(var i in e)r(t,i,e[i],n);return t}},97210:(t,e,n)=>{var r=n(32022),i=Object.defineProperty;t.exports=function(t,e){try{i(r,t,{value:e,configurable:!0,writable:!0})}catch(n){r[t]=e}return e}},39850:(t,e,n)=>{"use strict";var r=n(84160),i=TypeError;t.exports=function(t,e){if(!delete t[e])throw i("Cannot delete property "+r(e)+" of "+r(t))}},12115:(t,e,n)=>{var r=n(38986);t.exports=!r((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]}))},30805:t=>{var e="object"==typeof document&&document.all,n=void 0===e&&void 0!==e;t.exports={all:e,IS_HTMLDDA:n}},82985:(t,e,n)=>{var r=n(32022),i=n(51355),o=r.document,a=i(o)&&i(o.createElement);t.exports=function(t){return a?o.createElement(t):{}}},81912:t=>{var e=TypeError;t.exports=function(t){if(t>9007199254740991)throw e("Maximum allowed index exceeded");return t}},66910:t=>{t.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}},73391:(t,e,n)=>{var r=n(82985)("span").classList,i=r&&r.constructor&&r.constructor.prototype;t.exports=i===Object.prototype?void 0:i},93454:(t,e,n)=>{var r=n(30727).match(/firefox\/(\d+)/i);t.exports=!!r&&+r[1]},85048:(t,e,n)=>{var r=n(5835),i=n(79456);t.exports=!r&&!i&&"object"==typeof window&&"object"==typeof document},5835:t=>{t.exports="object"==typeof Deno&&Deno&&"object"==typeof Deno.version},88633:(t,e,n)=>{var r=n(30727);t.exports=/MSIE|Trident/.test(r)},88525:(t,e,n)=>{var r=n(30727),i=n(32022);t.exports=/ipad|iphone|ipod/i.test(r)&&void 0!==i.Pebble},649:(t,e,n)=>{var r=n(30727);t.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(r)},79456:(t,e,n)=>{var r=n(39523),i=n(32022);t.exports="process"==r(i.process)},52054:(t,e,n)=>{var r=n(30727);t.exports=/web0s(?!.*chrome)/i.test(r)},30727:(t,e,n)=>{var r=n(83155);t.exports=r("navigator","userAgent")||""},80714:(t,e,n)=>{var r,i,o=n(32022),a=n(30727),u=o.process,s=o.Deno,c=u&&u.versions||s&&s.version,d=c&&c.v8;d&&(i=(r=d.split("."))[0]>0&&r[0]<4?1:+(r[0]+r[1])),!i&&a&&(!(r=a.match(/Edge\/(\d+)/))||r[1]>=74)&&(r=a.match(/Chrome\/(\d+)/))&&(i=+r[1]),t.exports=i},10720:(t,e,n)=>{var r=n(30727).match(/AppleWebKit\/(\d+)\./);t.exports=!!r&&+r[1]},26100:t=>{t.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},54635:(t,e,n)=>{var r=n(32022),i=n(66213).f,o=n(22775),a=n(43068),u=n(97210),s=n(74953),c=n(77987);t.exports=function(t,e){var n,d,l,f,p,h=t.target,y=t.global,m=t.stat;if(n=y?r:m?r[h]||u(h,{}):(r[h]||{}).prototype)for(d in e){if(f=e[d],l=t.dontCallGetSet?(p=i(n,d))&&p.value:n[d],!c(y?d:h+(m?".":"#")+d,t.forced)&&void 0!==l){if(typeof f==typeof l)continue;s(f,l)}(t.sham||l&&l.sham)&&o(f,"sham",!0),a(n,d,f,t)}}},38986:t=>{t.exports=function(t){try{return!!t()}catch(t){return!0}}},26210:(t,e,n)=>{"use strict";n(49636);var r=n(59913),i=n(43068),o=n(83046),a=n(38986),u=n(30191),s=n(22775),c=u("species"),d=RegExp.prototype;t.exports=function(t,e,n,l){var f=u(t),p=!a((function(){var e={};return e[f]=function(){return 7},7!=""[t](e)})),h=p&&!a((function(){var e=!1,n=/a/;return"split"===t&&((n={}).constructor={},n.constructor[c]=function(){return n},n.flags="",n[f]=/./[f]),n.exec=function(){return e=!0,null},n[f](""),!e}));if(!p||!h||n){var y=r(/./[f]),m=e(f,""[t],(function(t,e,n,i,a){var u=r(t),s=e.exec;return s===o||s===d.exec?p&&!a?{done:!0,value:y(e,n,i)}:{done:!0,value:u(n,e,i)}:{done:!1}}));i(String.prototype,t,m[0]),i(d,f,m[1])}l&&s(d[f],"sham",!0)}},47484:(t,e,n)=>{"use strict";var r=n(65351),i=n(84117),o=n(81912),a=n(80391),u=function(t,e,n,s,c,d,l,f){for(var p,h,y=c,m=0,v=!!l&&a(l,f);m0&&r(p)?(h=i(p),y=u(t,e,p,h,y,d-1)-1):(o(y+1),t[y]=p),y++),m++;return y};t.exports=u},6769:(t,e,n)=>{var r=n(38986);t.exports=!r((function(){return Object.isExtensible(Object.preventExtensions({}))}))},10584:(t,e,n)=>{var r=n(74959),i=Function.prototype,o=i.apply,a=i.call;t.exports="object"==typeof Reflect&&Reflect.apply||(r?a.bind(o):function(){return a.apply(o,arguments)})},80391:(t,e,n)=>{var r=n(59913),i=n(86173),o=n(74959),a=r(r.bind);t.exports=function(t,e){return i(t),void 0===e?t:o?a(t,e):function(){return t.apply(e,arguments)}}},74959:(t,e,n)=>{var r=n(38986);t.exports=!r((function(){var t=function(){}.bind();return"function"!=typeof t||t.hasOwnProperty("prototype")}))},49425:(t,e,n)=>{var r=n(74959),i=Function.prototype.call;t.exports=r?i.bind(i):function(){return i.apply(i,arguments)}},27765:(t,e,n)=>{var r=n(12115),i=n(98511),o=Function.prototype,a=r&&Object.getOwnPropertyDescriptor,u=i(o,"name"),s=u&&"something"===function(){}.name,c=u&&(!r||r&&a(o,"name").configurable);t.exports={EXISTS:u,PROPER:s,CONFIGURABLE:c}},59913:(t,e,n)=>{var r=n(74959),i=Function.prototype,o=i.bind,a=i.call,u=r&&o.bind(a,a);t.exports=r?function(t){return t&&u(t)}:function(t){return t&&function(){return a.apply(t,arguments)}}},83155:(t,e,n)=>{var r=n(32022),i=n(34028);t.exports=function(t,e){return arguments.length<2?(n=r[t],i(n)?n:void 0):r[t]&&r[t][e];var n}},6897:(t,e,n)=>{var r=n(82814),i=n(34040),o=n(87126),a=n(13766),u=n(30191)("iterator");t.exports=function(t){if(!o(t))return i(t,u)||i(t,"@@iterator")||a[r(t)]}},32057:(t,e,n)=>{var r=n(49425),i=n(86173),o=n(52546),a=n(84160),u=n(6897),s=TypeError;t.exports=function(t,e){var n=arguments.length<2?u(t):e;if(i(n))return o(r(n,t));throw s(a(t)+" is not iterable")}},34040:(t,e,n)=>{var r=n(86173),i=n(87126);t.exports=function(t,e){var n=t[e];return i(n)?void 0:r(n)}},82319:(t,e,n)=>{var r=n(59913),i=n(47137),o=Math.floor,a=r("".charAt),u=r("".replace),s=r("".slice),c=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,d=/\$([$&'`]|\d{1,2})/g;t.exports=function(t,e,n,r,l,f){var p=n+t.length,h=r.length,y=d;return void 0!==l&&(l=i(l),y=c),u(f,y,(function(i,u){var c;switch(a(u,0)){case"$":return"$";case"&":return t;case"`":return s(e,0,n);case"'":return s(e,p);case"<":c=l[s(u,1,-1)];break;default:var d=+u;if(0===d)return i;if(d>h){var f=o(d/10);return 0===f?i:f<=h?void 0===r[f-1]?a(u,1):r[f-1]+a(u,1):i}c=r[d-1]}return void 0===c?"":c}))}},32022:(t,e,n)=>{var r=function(t){return t&&t.Math==Math&&t};t.exports=r("object"==typeof globalThis&&globalThis)||r("object"==typeof window&&window)||r("object"==typeof self&&self)||r("object"==typeof n.g&&n.g)||function(){return this}()||Function("return this")()},98511:(t,e,n)=>{var r=n(59913),i=n(47137),o=r({}.hasOwnProperty);t.exports=Object.hasOwn||function(t,e){return o(i(t),e)}},17307:t=>{t.exports={}},39361:(t,e,n)=>{var r=n(32022);t.exports=function(t,e){var n=r.console;n&&n.error&&(1==arguments.length?n.error(t):n.error(t,e))}},86419:(t,e,n)=>{var r=n(83155);t.exports=r("document","documentElement")},2159:(t,e,n)=>{var r=n(12115),i=n(38986),o=n(82985);t.exports=!r&&!i((function(){return 7!=Object.defineProperty(o("div"),"a",{get:function(){return 7}}).a}))},38108:t=>{var e=Array,n=Math.abs,r=Math.pow,i=Math.floor,o=Math.log,a=Math.LN2;t.exports={pack:function(t,u,s){var c,d,l,f=e(s),p=8*s-u-1,h=(1<>1,m=23===u?r(2,-24)-r(2,-77):0,v=t<0||0===t&&1/t<0?1:0,g=0;for((t=n(t))!=t||t===1/0?(d=t!=t?1:0,c=h):(c=i(o(t)/a),t*(l=r(2,-c))<1&&(c--,l*=2),(t+=c+y>=1?m/l:m*r(2,1-y))*l>=2&&(c++,l/=2),c+y>=h?(d=0,c=h):c+y>=1?(d=(t*l-1)*r(2,u),c+=y):(d=t*r(2,y-1)*r(2,u),c=0));u>=8;)f[g++]=255&d,d/=256,u-=8;for(c=c<0;)f[g++]=255&c,c/=256,p-=8;return f[--g]|=128*v,f},unpack:function(t,e){var n,i=t.length,o=8*i-e-1,a=(1<>1,s=o-7,c=i-1,d=t[c--],l=127&d;for(d>>=7;s>0;)l=256*l+t[c--],s-=8;for(n=l&(1<<-s)-1,l>>=-s,s+=e;s>0;)n=256*n+t[c--],s-=8;if(0===l)l=1-u;else{if(l===a)return n?NaN:d?-1/0:1/0;n+=r(2,e),l-=u}return(d?-1:1)*n*r(2,l-e)}}},94032:(t,e,n)=>{var r=n(59913),i=n(38986),o=n(39523),a=Object,u=r("".split);t.exports=i((function(){return!a("z").propertyIsEnumerable(0)}))?function(t){return"String"==o(t)?u(t,""):a(t)}:a},99618:(t,e,n)=>{var r=n(34028),i=n(51355),o=n(25466);t.exports=function(t,e,n){var a,u;return o&&r(a=e.constructor)&&a!==n&&i(u=a.prototype)&&u!==n.prototype&&o(t,u),t}},46169:(t,e,n)=>{var r=n(59913),i=n(34028),o=n(43349),a=r(Function.toString);i(o.inspectSource)||(o.inspectSource=function(t){return a(t)}),t.exports=o.inspectSource},67023:(t,e,n)=>{var r=n(54635),i=n(59913),o=n(17307),a=n(51355),u=n(98511),s=n(43087).f,c=n(92775),d=n(12098),l=n(62713),f=n(60232),p=n(6769),h=!1,y=f("meta"),m=0,v=function(t){s(t,y,{value:{objectID:"O"+m++,weakData:{}}})},g=t.exports={enable:function(){g.enable=function(){},h=!0;var t=c.f,e=i([].splice),n={};n[y]=1,t(n).length&&(c.f=function(n){for(var r=t(n),i=0,o=r.length;i{var r,i,o,a=n(74112),u=n(32022),s=n(59913),c=n(51355),d=n(22775),l=n(98511),f=n(43349),p=n(57186),h=n(17307),y="Object already initialized",m=u.TypeError,v=u.WeakMap;if(a||f.state){var g=f.state||(f.state=new v),_=s(g.get),b=s(g.has),S=s(g.set);r=function(t,e){if(b(g,t))throw m(y);return e.facade=t,S(g,t,e),e},i=function(t){return _(g,t)||{}},o=function(t){return b(g,t)}}else{var w=p("state");h[w]=!0,r=function(t,e){if(l(t,w))throw m(y);return e.facade=t,d(t,w,e),e},i=function(t){return l(t,w)?t[w]:{}},o=function(t){return l(t,w)}}t.exports={set:r,get:i,has:o,enforce:function(t){return o(t)?i(t):r(t,{})},getterFor:function(t){return function(e){var n;if(!c(e)||(n=i(e)).type!==t)throw m("Incompatible receiver, "+t+" required");return n}}}},92882:(t,e,n)=>{var r=n(30191),i=n(13766),o=r("iterator"),a=Array.prototype;t.exports=function(t){return void 0!==t&&(i.Array===t||a[o]===t)}},65351:(t,e,n)=>{var r=n(39523);t.exports=Array.isArray||function(t){return"Array"==r(t)}},34028:(t,e,n)=>{var r=n(30805),i=r.all;t.exports=r.IS_HTMLDDA?function(t){return"function"==typeof t||t===i}:function(t){return"function"==typeof t}},78449:(t,e,n)=>{var r=n(59913),i=n(38986),o=n(34028),a=n(82814),u=n(83155),s=n(46169),c=function(){},d=[],l=u("Reflect","construct"),f=/^\s*(?:class|function)\b/,p=r(f.exec),h=!f.exec(c),y=function(t){if(!o(t))return!1;try{return l(c,d,t),!0}catch(t){return!1}},m=function(t){if(!o(t))return!1;switch(a(t)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return h||!!p(f,s(t))}catch(t){return!0}};m.sham=!0,t.exports=!l||i((function(){var t;return y(y.call)||!y(Object)||!y((function(){t=!0}))||t}))?m:y},77987:(t,e,n)=>{var r=n(38986),i=n(34028),o=/#|\.prototype\./,a=function(t,e){var n=s[u(t)];return n==d||n!=c&&(i(e)?r(e):!!e)},u=a.normalize=function(t){return String(t).replace(o,".").toLowerCase()},s=a.data={},c=a.NATIVE="N",d=a.POLYFILL="P";t.exports=a},87126:t=>{t.exports=function(t){return null==t}},51355:(t,e,n)=>{var r=n(34028),i=n(30805),o=i.all;t.exports=i.IS_HTMLDDA?function(t){return"object"==typeof t?null!==t:r(t)||t===o}:function(t){return"object"==typeof t?null!==t:r(t)}},68546:t=>{t.exports=!1},91035:(t,e,n)=>{var r=n(51355),i=n(39523),o=n(30191)("match");t.exports=function(t){var e;return r(t)&&(void 0!==(e=t[o])?!!e:"RegExp"==i(t))}},24505:(t,e,n)=>{var r=n(83155),i=n(34028),o=n(27357),a=n(78590),u=Object;t.exports=a?function(t){return"symbol"==typeof t}:function(t){var e=r("Symbol");return i(e)&&o(e.prototype,u(t))}},38640:(t,e,n)=>{var r=n(80391),i=n(49425),o=n(52546),a=n(84160),u=n(92882),s=n(84117),c=n(27357),d=n(32057),l=n(6897),f=n(94681),p=TypeError,h=function(t,e){this.stopped=t,this.result=e},y=h.prototype;t.exports=function(t,e,n){var m,v,g,_,b,S,w,C=n&&n.that,E=!(!n||!n.AS_ENTRIES),I=!(!n||!n.IS_RECORD),P=!(!n||!n.IS_ITERATOR),A=!(!n||!n.INTERRUPTED),O=r(e,C),T=function(t){return m&&f(m,"normal",t),new h(!0,t)},x=function(t){return E?(o(t),A?O(t[0],t[1],T):O(t[0],t[1])):A?O(t,T):O(t)};if(I)m=t.iterator;else if(P)m=t;else{if(!(v=l(t)))throw p(a(t)+" is not iterable");if(u(v)){for(g=0,_=s(t);_>g;g++)if((b=x(t[g]))&&c(y,b))return b;return new h(!1)}m=d(t,v)}for(S=I?t.next:m.next;!(w=i(S,m)).done;){try{b=x(w.value)}catch(t){f(m,"throw",t)}if("object"==typeof b&&b&&c(y,b))return b}return new h(!1)}},94681:(t,e,n)=>{var r=n(49425),i=n(52546),o=n(34040);t.exports=function(t,e,n){var a,u;i(t);try{if(!(a=o(t,"return"))){if("throw"===e)throw n;return n}a=r(a,t)}catch(t){u=!0,a=t}if("throw"===e)throw n;if(u)throw a;return i(a),n}},92480:(t,e,n)=>{"use strict";var r=n(10798).IteratorPrototype,i=n(13250),o=n(71111),a=n(27747),u=n(13766),s=function(){return this};t.exports=function(t,e,n,c){var d=e+" Iterator";return t.prototype=i(r,{next:o(+!c,n)}),a(t,d,!1,!0),u[d]=s,t}},53338:(t,e,n)=>{"use strict";var r=n(54635),i=n(49425),o=n(68546),a=n(27765),u=n(34028),s=n(92480),c=n(75783),d=n(25466),l=n(27747),f=n(22775),p=n(43068),h=n(30191),y=n(13766),m=n(10798),v=a.PROPER,g=a.CONFIGURABLE,_=m.IteratorPrototype,b=m.BUGGY_SAFARI_ITERATORS,S=h("iterator"),w="keys",C="values",E="entries",I=function(){return this};t.exports=function(t,e,n,a,h,m,P){s(n,e,a);var A,O,T,x=function(t){if(t===h&&D)return D;if(!b&&t in M)return M[t];switch(t){case w:case C:case E:return function(){return new n(this,t)}}return function(){return new n(this)}},R=e+" Iterator",k=!1,M=t.prototype,N=M[S]||M["@@iterator"]||h&&M[h],D=!b&&N||x(h),L="Array"==e&&M.entries||N;if(L&&(A=c(L.call(new t)))!==Object.prototype&&A.next&&(o||c(A)===_||(d?d(A,_):u(A[S])||p(A,S,I)),l(A,R,!0,!0),o&&(y[R]=I)),v&&h==C&&N&&N.name!==C&&(!o&&g?f(M,"name",C):(k=!0,D=function(){return i(N,this)})),h)if(O={values:x(C),keys:m?D:x(w),entries:x(E)},P)for(T in O)(b||k||!(T in M))&&p(M,T,O[T]);else r({target:e,proto:!0,forced:b||k},O);return o&&!P||M[S]===D||p(M,S,D,{name:h}),y[e]=D,O}},10798:(t,e,n)=>{"use strict";var r,i,o,a=n(38986),u=n(34028),s=n(51355),c=n(13250),d=n(75783),l=n(43068),f=n(30191),p=n(68546),h=f("iterator"),y=!1;[].keys&&("next"in(o=[].keys())?(i=d(d(o)))!==Object.prototype&&(r=i):y=!0),!s(r)||a((function(){var t={};return r[h].call(t)!==t}))?r={}:p&&(r=c(r)),u(r[h])||l(r,h,(function(){return this})),t.exports={IteratorPrototype:r,BUGGY_SAFARI_ITERATORS:y}},13766:t=>{t.exports={}},84117:(t,e,n)=>{var r=n(9375);t.exports=function(t){return r(t.length)}},43608:(t,e,n)=>{var r=n(38986),i=n(34028),o=n(98511),a=n(12115),u=n(27765).CONFIGURABLE,s=n(46169),c=n(78045),d=c.enforce,l=c.get,f=Object.defineProperty,p=a&&!r((function(){return 8!==f((function(){}),"length",{value:8}).length})),h=String(String).split("String"),y=t.exports=function(t,e,n){"Symbol("===String(e).slice(0,7)&&(e="["+String(e).replace(/^Symbol\(([^)]*)\)/,"$1")+"]"),n&&n.getter&&(e="get "+e),n&&n.setter&&(e="set "+e),(!o(t,"name")||u&&t.name!==e)&&(a?f(t,"name",{value:e,configurable:!0}):t.name=e),p&&n&&o(n,"arity")&&t.length!==n.arity&&f(t,"length",{value:n.arity});try{n&&o(n,"constructor")&&n.constructor?a&&f(t,"prototype",{writable:!1}):t.prototype&&(t.prototype=void 0)}catch(t){}var r=d(t);return o(r,"source")||(r.source=h.join("string"==typeof e?e:"")),t};Function.prototype.toString=y((function(){return i(this)&&l(this).source||s(this)}),"toString")},39309:t=>{var e=Math.ceil,n=Math.floor;t.exports=Math.trunc||function(t){var r=+t;return(r>0?n:e)(r)}},76173:(t,e,n)=>{var r,i,o,a,u,s,c,d,l=n(32022),f=n(80391),p=n(66213).f,h=n(16416).set,y=n(649),m=n(88525),v=n(52054),g=n(79456),_=l.MutationObserver||l.WebKitMutationObserver,b=l.document,S=l.process,w=l.Promise,C=p(l,"queueMicrotask"),E=C&&C.value;E||(r=function(){var t,e;for(g&&(t=S.domain)&&t.exit();i;){e=i.fn,i=i.next;try{e()}catch(t){throw i?a():o=void 0,t}}o=void 0,t&&t.enter()},y||g||v||!_||!b?!m&&w&&w.resolve?((c=w.resolve(void 0)).constructor=w,d=f(c.then,c),a=function(){d(r)}):g?a=function(){S.nextTick(r)}:(h=f(h,l),a=function(){h(r)}):(u=!0,s=b.createTextNode(""),new _(r).observe(s,{characterData:!0}),a=function(){s.data=u=!u})),t.exports=E||function(t){var e={fn:t,next:void 0};o&&(o.next=e),i||(i=e,a()),o=e}},67892:(t,e,n)=>{"use strict";var r=n(86173),i=TypeError,o=function(t){var e,n;this.promise=new t((function(t,r){if(void 0!==e||void 0!==n)throw i("Bad Promise constructor");e=t,n=r})),this.resolve=r(e),this.reject=r(n)};t.exports.f=function(t){return new o(t)}},17911:(t,e,n)=>{var r=n(91035),i=TypeError;t.exports=function(t){if(r(t))throw i("The method doesn't accept regular expressions");return t}},57017:(t,e,n)=>{var r=n(32022),i=n(38986),o=n(59913),a=n(74170),u=n(76109).trim,s=n(60812),c=o("".charAt),d=r.parseFloat,l=r.Symbol,f=l&&l.iterator,p=1/d(s+"-0")!=-1/0||f&&!i((function(){d(Object(f))}));t.exports=p?function(t){var e=u(a(t)),n=d(e);return 0===n&&"-"==c(e,0)?-0:n}:d},84475:(t,e,n)=>{var r=n(32022),i=n(38986),o=n(59913),a=n(74170),u=n(76109).trim,s=n(60812),c=r.parseInt,d=r.Symbol,l=d&&d.iterator,f=/^[+-]?0x/i,p=o(f.exec),h=8!==c(s+"08")||22!==c(s+"0x16")||l&&!i((function(){c(Object(l))}));t.exports=h?function(t,e){var n=u(a(t));return c(n,e>>>0||(p(f,n)?16:10))}:c},86851:(t,e,n)=>{"use strict";var r=n(12115),i=n(59913),o=n(49425),a=n(38986),u=n(95932),s=n(31711),c=n(23659),d=n(47137),l=n(94032),f=Object.assign,p=Object.defineProperty,h=i([].concat);t.exports=!f||a((function(){if(r&&1!==f({b:1},f(p({},"a",{enumerable:!0,get:function(){p(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var t={},e={},n=Symbol(),i="abcdefghijklmnopqrst";return t[n]=7,i.split("").forEach((function(t){e[t]=t})),7!=f({},t)[n]||u(f({},e)).join("")!=i}))?function(t,e){for(var n=d(t),i=arguments.length,a=1,f=s.f,p=c.f;i>a;)for(var y,m=l(arguments[a++]),v=f?h(u(m),f(m)):u(m),g=v.length,_=0;g>_;)y=v[_++],r&&!o(p,m,y)||(n[y]=m[y]);return n}:f},13250:(t,e,n)=>{var r,i=n(52546),o=n(13330),a=n(26100),u=n(17307),s=n(86419),c=n(82985),d=n(57186),l="prototype",f="script",p=d("IE_PROTO"),h=function(){},y=function(t){return"<"+f+">"+t+""},m=function(t){t.write(y("")),t.close();var e=t.parentWindow.Object;return t=null,e},v=function(){try{r=new ActiveXObject("htmlfile")}catch(t){}var t,e,n;v="undefined"!=typeof document?document.domain&&r?m(r):(e=c("iframe"),n="java"+f+":",e.style.display="none",s.appendChild(e),e.src=String(n),(t=e.contentWindow.document).open(),t.write(y("document.F=Object")),t.close(),t.F):m(r);for(var i=a.length;i--;)delete v[l][a[i]];return v()};u[p]=!0,t.exports=Object.create||function(t,e){var n;return null!==t?(h[l]=i(t),n=new h,h[l]=null,n[p]=t):n=v(),void 0===e?n:o.f(n,e)}},13330:(t,e,n)=>{var r=n(12115),i=n(71330),o=n(43087),a=n(52546),u=n(58326),s=n(95932);e.f=r&&!i?Object.defineProperties:function(t,e){a(t);for(var n,r=u(e),i=s(e),c=i.length,d=0;c>d;)o.f(t,n=i[d++],r[n]);return t}},43087:(t,e,n)=>{var r=n(12115),i=n(2159),o=n(71330),a=n(52546),u=n(79127),s=TypeError,c=Object.defineProperty,d=Object.getOwnPropertyDescriptor,l="enumerable",f="configurable",p="writable";e.f=r?o?function(t,e,n){if(a(t),e=u(e),a(n),"function"==typeof t&&"prototype"===e&&"value"in n&&p in n&&!n[p]){var r=d(t,e);r&&r[p]&&(t[e]=n.value,n={configurable:f in n?n[f]:r[f],enumerable:l in n?n[l]:r[l],writable:!1})}return c(t,e,n)}:c:function(t,e,n){if(a(t),e=u(e),a(n),i)try{return c(t,e,n)}catch(t){}if("get"in n||"set"in n)throw s("Accessors not supported");return"value"in n&&(t[e]=n.value),t}},66213:(t,e,n)=>{var r=n(12115),i=n(49425),o=n(23659),a=n(71111),u=n(58326),s=n(79127),c=n(98511),d=n(2159),l=Object.getOwnPropertyDescriptor;e.f=r?l:function(t,e){if(t=u(t),e=s(e),d)try{return l(t,e)}catch(t){}if(c(t,e))return a(!i(o.f,t,e),t[e])}},12098:(t,e,n)=>{var r=n(39523),i=n(58326),o=n(92775).f,a=n(42893),u="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];t.exports.f=function(t){return u&&"Window"==r(t)?function(t){try{return o(t)}catch(t){return a(u)}}(t):o(i(t))}},92775:(t,e,n)=>{var r=n(7282),i=n(26100).concat("length","prototype");e.f=Object.getOwnPropertyNames||function(t){return r(t,i)}},31711:(t,e)=>{e.f=Object.getOwnPropertySymbols},75783:(t,e,n)=>{var r=n(98511),i=n(34028),o=n(47137),a=n(57186),u=n(88538),s=a("IE_PROTO"),c=Object,d=c.prototype;t.exports=u?c.getPrototypeOf:function(t){var e=o(t);if(r(e,s))return e[s];var n=e.constructor;return i(n)&&e instanceof n?n.prototype:e instanceof c?d:null}},62713:(t,e,n)=>{var r=n(38986),i=n(51355),o=n(39523),a=n(1743),u=Object.isExtensible,s=r((function(){u(1)}));t.exports=s||a?function(t){return!!i(t)&&(!a||"ArrayBuffer"!=o(t))&&(!u||u(t))}:u},27357:(t,e,n)=>{var r=n(59913);t.exports=r({}.isPrototypeOf)},7282:(t,e,n)=>{var r=n(59913),i=n(98511),o=n(58326),a=n(78035).indexOf,u=n(17307),s=r([].push);t.exports=function(t,e){var n,r=o(t),c=0,d=[];for(n in r)!i(u,n)&&i(r,n)&&s(d,n);for(;e.length>c;)i(r,n=e[c++])&&(~a(d,n)||s(d,n));return d}},95932:(t,e,n)=>{var r=n(7282),i=n(26100);t.exports=Object.keys||function(t){return r(t,i)}},23659:(t,e)=>{"use strict";var n={}.propertyIsEnumerable,r=Object.getOwnPropertyDescriptor,i=r&&!n.call({1:2},1);e.f=i?function(t){var e=r(this,t);return!!e&&e.enumerable}:n},25466:(t,e,n)=>{var r=n(59913),i=n(52546),o=n(41684);t.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var t,e=!1,n={};try{(t=r(Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set))(n,[]),e=n instanceof Array}catch(t){}return function(n,r){return i(n),o(r),e?t(n,r):n.__proto__=r,n}}():void 0)},76389:(t,e,n)=>{var r=n(12115),i=n(59913),o=n(95932),a=n(58326),u=i(n(23659).f),s=i([].push),c=function(t){return function(e){for(var n,i=a(e),c=o(i),d=c.length,l=0,f=[];d>l;)n=c[l++],r&&!u(i,n)||s(f,t?[n,i[n]]:i[n]);return f}};t.exports={entries:c(!0),values:c(!1)}},75954:(t,e,n)=>{"use strict";var r=n(77568),i=n(82814);t.exports=r?{}.toString:function(){return"[object "+i(this)+"]"}},93126:(t,e,n)=>{var r=n(49425),i=n(34028),o=n(51355),a=TypeError;t.exports=function(t,e){var n,u;if("string"===e&&i(n=t.toString)&&!o(u=r(n,t)))return u;if(i(n=t.valueOf)&&!o(u=r(n,t)))return u;if("string"!==e&&i(n=t.toString)&&!o(u=r(n,t)))return u;throw a("Can't convert object to primitive value")}},91537:(t,e,n)=>{var r=n(83155),i=n(59913),o=n(92775),a=n(31711),u=n(52546),s=i([].concat);t.exports=r("Reflect","ownKeys")||function(t){var e=o.f(u(t)),n=a.f;return n?s(e,n(t)):e}},23034:(t,e,n)=>{var r=n(32022);t.exports=r},25786:t=>{t.exports=function(t){try{return{error:!1,value:t()}}catch(t){return{error:!0,value:t}}}},93494:(t,e,n)=>{var r=n(32022),i=n(33183),o=n(34028),a=n(77987),u=n(46169),s=n(30191),c=n(85048),d=n(5835),l=n(68546),f=n(80714),p=i&&i.prototype,h=s("species"),y=!1,m=o(r.PromiseRejectionEvent),v=a("Promise",(function(){var t=u(i),e=t!==String(i);if(!e&&66===f)return!0;if(l&&(!p.catch||!p.finally))return!0;if(!f||f<51||!/native code/.test(t)){var n=new i((function(t){t(1)})),r=function(t){t((function(){}),(function(){}))};if((n.constructor={})[h]=r,!(y=n.then((function(){}))instanceof r))return!0}return!e&&(c||d)&&!m}));t.exports={CONSTRUCTOR:v,REJECTION_EVENT:m,SUBCLASSING:y}},33183:(t,e,n)=>{var r=n(32022);t.exports=r.Promise},39062:(t,e,n)=>{var r=n(52546),i=n(51355),o=n(67892);t.exports=function(t,e){if(r(t),i(e)&&e.constructor===t)return e;var n=o.f(t);return(0,n.resolve)(e),n.promise}},22208:(t,e,n)=>{var r=n(33183),i=n(41269),o=n(93494).CONSTRUCTOR;t.exports=o||!i((function(t){r.all(t).then(void 0,(function(){}))}))},83623:(t,e,n)=>{var r=n(43087).f;t.exports=function(t,e,n){n in t||r(t,n,{configurable:!0,get:function(){return e[n]},set:function(t){e[n]=t}})}},97278:t=>{var e=function(){this.head=null,this.tail=null};e.prototype={add:function(t){var e={item:t,next:null};this.head?this.tail.next=e:this.head=e,this.tail=e},get:function(){var t=this.head;if(t)return this.head=t.next,this.tail===t&&(this.tail=null),t.item}},t.exports=e},70468:(t,e,n)=>{var r=n(49425),i=n(52546),o=n(34028),a=n(39523),u=n(83046),s=TypeError;t.exports=function(t,e){var n=t.exec;if(o(n)){var c=r(n,t,e);return null!==c&&i(c),c}if("RegExp"===a(t))return r(u,t,e);throw s("RegExp#exec called on incompatible receiver")}},83046:(t,e,n)=>{"use strict";var r,i,o=n(49425),a=n(59913),u=n(74170),s=n(60333),c=n(13917),d=n(27905),l=n(13250),f=n(78045).get,p=n(45969),h=n(25404),y=d("native-string-replace",String.prototype.replace),m=RegExp.prototype.exec,v=m,g=a("".charAt),_=a("".indexOf),b=a("".replace),S=a("".slice),w=(i=/b*/g,o(m,r=/a/,"a"),o(m,i,"a"),0!==r.lastIndex||0!==i.lastIndex),C=c.BROKEN_CARET,E=void 0!==/()??/.exec("")[1];(w||E||C||p||h)&&(v=function(t){var e,n,r,i,a,c,d,p=this,h=f(p),I=u(t),P=h.raw;if(P)return P.lastIndex=p.lastIndex,e=o(v,P,I),p.lastIndex=P.lastIndex,e;var A=h.groups,O=C&&p.sticky,T=o(s,p),x=p.source,R=0,k=I;if(O&&(T=b(T,"y",""),-1===_(T,"g")&&(T+="g"),k=S(I,p.lastIndex),p.lastIndex>0&&(!p.multiline||p.multiline&&"\n"!==g(I,p.lastIndex-1))&&(x="(?: "+x+")",k=" "+k,R++),n=new RegExp("^(?:"+x+")",T)),E&&(n=new RegExp("^"+x+"$(?!\\s)",T)),w&&(r=p.lastIndex),i=o(m,O?n:p,k),O?i?(i.input=S(i.input,R),i[0]=S(i[0],R),i.index=p.lastIndex,p.lastIndex+=i[0].length):p.lastIndex=0:w&&i&&(p.lastIndex=p.global?i.index+i[0].length:r),E&&i&&i.length>1&&o(y,i[0],n,(function(){for(a=1;a{"use strict";var r=n(52546);t.exports=function(){var t=r(this),e="";return t.hasIndices&&(e+="d"),t.global&&(e+="g"),t.ignoreCase&&(e+="i"),t.multiline&&(e+="m"),t.dotAll&&(e+="s"),t.unicode&&(e+="u"),t.unicodeSets&&(e+="v"),t.sticky&&(e+="y"),e}},79517:(t,e,n)=>{var r=n(49425),i=n(98511),o=n(27357),a=n(60333),u=RegExp.prototype;t.exports=function(t){var e=t.flags;return void 0!==e||"flags"in u||i(t,"flags")||!o(u,t)?e:r(a,t)}},13917:(t,e,n)=>{var r=n(38986),i=n(32022).RegExp,o=r((function(){var t=i("a","y");return t.lastIndex=2,null!=t.exec("abcd")})),a=o||r((function(){return!i("a","y").sticky})),u=o||r((function(){var t=i("^r","gy");return t.lastIndex=2,null!=t.exec("str")}));t.exports={BROKEN_CARET:u,MISSED_STICKY:a,UNSUPPORTED_Y:o}},45969:(t,e,n)=>{var r=n(38986),i=n(32022).RegExp;t.exports=r((function(){var t=i(".","s");return!(t.dotAll&&t.exec("\n")&&"s"===t.flags)}))},25404:(t,e,n)=>{var r=n(38986),i=n(32022).RegExp;t.exports=r((function(){var t=i("(?b)","g");return"b"!==t.exec("b").groups.a||"bc"!=="b".replace(t,"$c")}))},31591:(t,e,n)=>{var r=n(87126),i=TypeError;t.exports=function(t){if(r(t))throw i("Can't call method on "+t);return t}},60528:t=>{t.exports=Object.is||function(t,e){return t===e?0!==t||1/t==1/e:t!=t&&e!=e}},42343:(t,e,n)=>{"use strict";var r=n(83155),i=n(43087),o=n(30191),a=n(12115),u=o("species");t.exports=function(t){var e=r(t),n=i.f;a&&e&&!e[u]&&n(e,u,{configurable:!0,get:function(){return this}})}},27747:(t,e,n)=>{var r=n(43087).f,i=n(98511),o=n(30191)("toStringTag");t.exports=function(t,e,n){t&&!n&&(t=t.prototype),t&&!i(t,o)&&r(t,o,{configurable:!0,value:e})}},57186:(t,e,n)=>{var r=n(27905),i=n(60232),o=r("keys");t.exports=function(t){return o[t]||(o[t]=i(t))}},43349:(t,e,n)=>{var r=n(32022),i=n(97210),o="__core-js_shared__",a=r[o]||i(o,{});t.exports=a},27905:(t,e,n)=>{var r=n(68546),i=n(43349);(t.exports=function(t,e){return i[t]||(i[t]=void 0!==e?e:{})})("versions",[]).push({version:"3.25.2",mode:r?"pure":"global",copyright:"© 2014-2022 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.25.2/LICENSE",source:"https://github.com/zloirock/core-js"})},33820:(t,e,n)=>{var r=n(52546),i=n(52023),o=n(87126),a=n(30191)("species");t.exports=function(t,e){var n,u=r(t).constructor;return void 0===u||o(n=r(u)[a])?e:i(n)}},9120:(t,e,n)=>{var r=n(38986);t.exports=function(t){return r((function(){var e=""[t]('"');return e!==e.toLowerCase()||e.split('"').length>3}))}},58402:(t,e,n)=>{var r=n(59913),i=n(75982),o=n(74170),a=n(31591),u=r("".charAt),s=r("".charCodeAt),c=r("".slice),d=function(t){return function(e,n){var r,d,l=o(a(e)),f=i(n),p=l.length;return f<0||f>=p?t?"":void 0:(r=s(l,f))<55296||r>56319||f+1===p||(d=s(l,f+1))<56320||d>57343?t?u(l,f):r:t?c(l,f,f+2):d-56320+(r-55296<<10)+65536}};t.exports={codeAt:d(!1),charAt:d(!0)}},4465:(t,e,n)=>{var r=n(30727);t.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(r)},59015:(t,e,n)=>{var r=n(59913),i=n(9375),o=n(74170),a=n(48126),u=n(31591),s=r(a),c=r("".slice),d=Math.ceil,l=function(t){return function(e,n,r){var a,l,f=o(u(e)),p=i(n),h=f.length,y=void 0===r?" ":o(r);return p<=h||""==y?f:((l=s(y,d((a=p-h)/y.length))).length>a&&(l=c(l,0,a)),t?f+l:l+f)}};t.exports={start:l(!1),end:l(!0)}},48126:(t,e,n)=>{"use strict";var r=n(75982),i=n(74170),o=n(31591),a=RangeError;t.exports=function(t){var e=i(o(this)),n="",u=r(t);if(u<0||u==1/0)throw a("Wrong number of repetitions");for(;u>0;(u>>>=1)&&(e+=e))1&u&&(n+=e);return n}},9334:(t,e,n)=>{"use strict";var r=n(76109).end,i=n(41017);t.exports=i("trimEnd")?function(){return r(this)}:"".trimEnd},41017:(t,e,n)=>{var r=n(27765).PROPER,i=n(38986),o=n(60812);t.exports=function(t){return i((function(){return!!o[t]()||"​…᠎"!=="​…᠎"[t]()||r&&o[t].name!==t}))}},97746:(t,e,n)=>{"use strict";var r=n(76109).start,i=n(41017);t.exports=i("trimStart")?function(){return r(this)}:"".trimStart},76109:(t,e,n)=>{var r=n(59913),i=n(31591),o=n(74170),a=n(60812),u=r("".replace),s="["+a+"]",c=RegExp("^"+s+s+"*"),d=RegExp(s+s+"*$"),l=function(t){return function(e){var n=o(i(e));return 1&t&&(n=u(n,c,"")),2&t&&(n=u(n,d,"")),n}};t.exports={start:l(1),end:l(2),trim:l(3)}},86263:(t,e,n)=>{var r=n(80714),i=n(38986);t.exports=!!Object.getOwnPropertySymbols&&!i((function(){var t=Symbol();return!String(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&r&&r<41}))},47498:(t,e,n)=>{var r=n(49425),i=n(83155),o=n(30191),a=n(43068);t.exports=function(){var t=i("Symbol"),e=t&&t.prototype,n=e&&e.valueOf,u=o("toPrimitive");e&&!e[u]&&a(e,u,(function(t){return r(n,this)}),{arity:1})}},55666:(t,e,n)=>{var r=n(86263);t.exports=r&&!!Symbol.for&&!!Symbol.keyFor},16416:(t,e,n)=>{var r,i,o,a,u=n(32022),s=n(10584),c=n(80391),d=n(34028),l=n(98511),f=n(38986),p=n(86419),h=n(23141),y=n(82985),m=n(24246),v=n(649),g=n(79456),_=u.setImmediate,b=u.clearImmediate,S=u.process,w=u.Dispatch,C=u.Function,E=u.MessageChannel,I=u.String,P=0,A={},O="onreadystatechange";try{r=u.location}catch(t){}var T=function(t){if(l(A,t)){var e=A[t];delete A[t],e()}},x=function(t){return function(){T(t)}},R=function(t){T(t.data)},k=function(t){u.postMessage(I(t),r.protocol+"//"+r.host)};_&&b||(_=function(t){m(arguments.length,1);var e=d(t)?t:C(t),n=h(arguments,1);return A[++P]=function(){s(e,void 0,n)},i(P),P},b=function(t){delete A[t]},g?i=function(t){S.nextTick(x(t))}:w&&w.now?i=function(t){w.now(x(t))}:E&&!v?(a=(o=new E).port2,o.port1.onmessage=R,i=c(a.postMessage,a)):u.addEventListener&&d(u.postMessage)&&!u.importScripts&&r&&"file:"!==r.protocol&&!f(k)?(i=k,u.addEventListener("message",R,!1)):i=O in y("script")?function(t){p.appendChild(y("script"))[O]=function(){p.removeChild(this),T(t)}}:function(t){setTimeout(x(t),0)}),t.exports={set:_,clear:b}},10829:(t,e,n)=>{var r=n(59913);t.exports=r(1..valueOf)},86593:(t,e,n)=>{var r=n(75982),i=Math.max,o=Math.min;t.exports=function(t,e){var n=r(t);return n<0?i(n+e,0):o(n,e)}},91173:(t,e,n)=>{var r=n(75982),i=n(9375),o=RangeError;t.exports=function(t){if(void 0===t)return 0;var e=r(t),n=i(e);if(e!==n)throw o("Wrong length or index");return n}},58326:(t,e,n)=>{var r=n(94032),i=n(31591);t.exports=function(t){return r(i(t))}},75982:(t,e,n)=>{var r=n(39309);t.exports=function(t){var e=+t;return e!=e||0===e?0:r(e)}},9375:(t,e,n)=>{var r=n(75982),i=Math.min;t.exports=function(t){return t>0?i(r(t),9007199254740991):0}},47137:(t,e,n)=>{var r=n(31591),i=Object;t.exports=function(t){return i(r(t))}},99127:(t,e,n)=>{var r=n(49425),i=n(51355),o=n(24505),a=n(34040),u=n(93126),s=n(30191),c=TypeError,d=s("toPrimitive");t.exports=function(t,e){if(!i(t)||o(t))return t;var n,s=a(t,d);if(s){if(void 0===e&&(e="default"),n=r(s,t,e),!i(n)||o(n))return n;throw c("Can't convert object to primitive value")}return void 0===e&&(e="number"),u(t,e)}},79127:(t,e,n)=>{var r=n(99127),i=n(24505);t.exports=function(t){var e=r(t,"string");return i(e)?e:e+""}},77568:(t,e,n)=>{var r={};r[n(30191)("toStringTag")]="z",t.exports="[object z]"===String(r)},74170:(t,e,n)=>{var r=n(82814),i=String;t.exports=function(t){if("Symbol"===r(t))throw TypeError("Cannot convert a Symbol value to a string");return i(t)}},84160:t=>{var e=String;t.exports=function(t){try{return e(t)}catch(t){return"Object"}}},60232:(t,e,n)=>{var r=n(59913),i=0,o=Math.random(),a=r(1..toString);t.exports=function(t){return"Symbol("+(void 0===t?"":t)+")_"+a(++i+o,36)}},78590:(t,e,n)=>{var r=n(86263);t.exports=r&&!Symbol.sham&&"symbol"==typeof Symbol.iterator},71330:(t,e,n)=>{var r=n(12115),i=n(38986);t.exports=r&&i((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype}))},24246:t=>{var e=TypeError;t.exports=function(t,n){if(t{var r=n(32022),i=n(34028),o=r.WeakMap;t.exports=i(o)&&/native code/.test(String(o))},91165:(t,e,n)=>{var r=n(23034),i=n(98511),o=n(58855),a=n(43087).f;t.exports=function(t){var e=r.Symbol||(r.Symbol={});i(e,t)||a(e,t,{value:o.f(t)})}},58855:(t,e,n)=>{var r=n(30191);e.f=r},30191:(t,e,n)=>{var r=n(32022),i=n(27905),o=n(98511),a=n(60232),u=n(86263),s=n(78590),c=i("wks"),d=r.Symbol,l=d&&d.for,f=s?d:d&&d.withoutSetter||a;t.exports=function(t){if(!o(c,t)||!u&&"string"!=typeof c[t]){var e="Symbol."+t;u&&o(d,t)?c[t]=d[t]:c[t]=s&&l?l(e):f(e)}return c[t]}},60812:t=>{t.exports="\t\n\v\f\r                 \u2028\u2029\ufeff"},14459:(t,e,n)=>{"use strict";var r=n(54635),i=n(32022),o=n(65140),a=n(42343),u="ArrayBuffer",s=o[u];r({global:!0,constructor:!0,forced:i[u]!==s},{ArrayBuffer:s}),a(u)},75894:(t,e,n)=>{"use strict";var r=n(54635),i=n(59913),o=n(38986),a=n(65140),u=n(52546),s=n(86593),c=n(9375),d=n(33820),l=a.ArrayBuffer,f=a.DataView,p=f.prototype,h=i(l.prototype.slice),y=i(p.getUint8),m=i(p.setUint8);r({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:o((function(){return!new l(2).slice(1,void 0).byteLength}))},{slice:function(t,e){if(h&&void 0===e)return h(u(this),t);for(var n=u(this).byteLength,r=s(t,n),i=s(void 0===e?n:e,n),o=new(d(this,l))(c(i-r)),a=new f(this),p=new f(o),v=0;r{"use strict";var r=n(54635),i=n(38986),o=n(65351),a=n(51355),u=n(47137),s=n(84117),c=n(81912),d=n(19402),l=n(74842),f=n(41665),p=n(30191),h=n(80714),y=p("isConcatSpreadable"),m=h>=51||!i((function(){var t=[];return t[y]=!1,t.concat()[0]!==t})),v=f("concat"),g=function(t){if(!a(t))return!1;var e=t[y];return void 0!==e?!!e:o(t)};r({target:"Array",proto:!0,arity:1,forced:!m||!v},{concat:function(t){var e,n,r,i,o,a=u(this),f=l(a,0),p=0;for(e=-1,r=arguments.length;e{var r=n(54635),i=n(13750),o=n(47512);r({target:"Array",proto:!0},{fill:i}),o("fill")},51725:(t,e,n)=>{"use strict";var r=n(54635),i=n(55883).filter;r({target:"Array",proto:!0,forced:!n(41665)("filter")},{filter:function(t){return i(this,t,arguments.length>1?arguments[1]:void 0)}})},23143:(t,e,n)=>{"use strict";var r=n(54635),i=n(55883).findIndex,o=n(47512),a="findIndex",u=!0;a in[]&&Array(1)[a]((function(){u=!1})),r({target:"Array",proto:!0,forced:u},{findIndex:function(t){return i(this,t,arguments.length>1?arguments[1]:void 0)}}),o(a)},88342:(t,e,n)=>{"use strict";var r=n(54635),i=n(55883).find,o=n(47512),a="find",u=!0;a in[]&&Array(1)[a]((function(){u=!1})),r({target:"Array",proto:!0,forced:u},{find:function(t){return i(this,t,arguments.length>1?arguments[1]:void 0)}}),o(a)},25036:(t,e,n)=>{"use strict";var r=n(54635),i=n(47484),o=n(86173),a=n(47137),u=n(84117),s=n(74842);r({target:"Array",proto:!0},{flatMap:function(t){var e,n=a(this),r=u(n);return o(t),(e=s(n,0)).length=i(e,n,n,r,0,1,t,arguments.length>1?arguments[1]:void 0),e}})},95040:(t,e,n)=>{var r=n(54635),i=n(65375);r({target:"Array",stat:!0,forced:!n(41269)((function(t){Array.from(t)}))},{from:i})},5099:(t,e,n)=>{"use strict";var r=n(54635),i=n(78035).includes,o=n(38986),a=n(47512);r({target:"Array",proto:!0,forced:o((function(){return!Array(1).includes()}))},{includes:function(t){return i(this,t,arguments.length>1?arguments[1]:void 0)}}),a("includes")},6550:(t,e,n)=>{"use strict";var r=n(54635),i=n(59913),o=n(78035).indexOf,a=n(94694),u=i([].indexOf),s=!!u&&1/u([1],1,-0)<0,c=a("indexOf");r({target:"Array",proto:!0,forced:s||!c},{indexOf:function(t){var e=arguments.length>1?arguments[1]:void 0;return s?u(this,t,e)||0:o(this,t,e)}})},38490:(t,e,n)=>{"use strict";var r=n(58326),i=n(47512),o=n(13766),a=n(78045),u=n(43087).f,s=n(53338),c=n(80251),d=n(68546),l=n(12115),f="Array Iterator",p=a.set,h=a.getterFor(f);t.exports=s(Array,"Array",(function(t,e){p(this,{type:f,target:r(t),index:0,kind:e})}),(function(){var t=h(this),e=t.target,n=t.kind,r=t.index++;return!e||r>=e.length?(t.target=void 0,c(void 0,!0)):c("keys"==n?r:"values"==n?e[r]:[r,e[r]],!1)}),"values");var y=o.Arguments=o.Array;if(i("keys"),i("values"),i("entries"),!d&&l&&"values"!==y.name)try{u(y,"name",{value:"values"})}catch(t){}},64668:(t,e,n)=>{"use strict";var r=n(54635),i=n(59913),o=n(94032),a=n(58326),u=n(94694),s=i([].join),c=o!=Object,d=u("join",",");r({target:"Array",proto:!0,forced:c||!d},{join:function(t){return s(a(this),void 0===t?",":t)}})},74803:(t,e,n)=>{var r=n(54635),i=n(44687);r({target:"Array",proto:!0,forced:i!==[].lastIndexOf},{lastIndexOf:i})},95412:(t,e,n)=>{"use strict";var r=n(54635),i=n(55883).map;r({target:"Array",proto:!0,forced:!n(41665)("map")},{map:function(t){return i(this,t,arguments.length>1?arguments[1]:void 0)}})},72590:(t,e,n)=>{"use strict";var r=n(54635),i=n(59913),o=n(65351),a=i([].reverse),u=[1,2];r({target:"Array",proto:!0,forced:String(u)===String(u.reverse())},{reverse:function(){return o(this)&&(this.length=this.length),a(this)}})},16516:(t,e,n)=>{"use strict";var r=n(54635),i=n(65351),o=n(78449),a=n(51355),u=n(86593),s=n(84117),c=n(58326),d=n(19402),l=n(30191),f=n(41665),p=n(23141),h=f("slice"),y=l("species"),m=Array,v=Math.max;r({target:"Array",proto:!0,forced:!h},{slice:function(t,e){var n,r,l,f=c(this),h=s(f),g=u(t,h),_=u(void 0===e?h:e,h);if(i(f)&&(n=f.constructor,(o(n)&&(n===m||i(n.prototype))||a(n)&&null===(n=n[y]))&&(n=void 0),n===m||void 0===n))return p(f,g,_);for(r=new(void 0===n?m:n)(v(_-g,0)),l=0;g<_;g++,l++)g in f&&d(r,l,f[g]);return r.length=l,r}})},2934:(t,e,n)=>{"use strict";var r=n(54635),i=n(59913),o=n(86173),a=n(47137),u=n(84117),s=n(39850),c=n(74170),d=n(38986),l=n(71929),f=n(94694),p=n(93454),h=n(88633),y=n(80714),m=n(10720),v=[],g=i(v.sort),_=i(v.push),b=d((function(){v.sort(void 0)})),S=d((function(){v.sort(null)})),w=f("sort"),C=!d((function(){if(y)return y<70;if(!(p&&p>3)){if(h)return!0;if(m)return m<603;var t,e,n,r,i="";for(t=65;t<76;t++){switch(e=String.fromCharCode(t),t){case 66:case 69:case 70:case 72:n=3;break;case 68:case 71:n=4;break;default:n=2}for(r=0;r<47;r++)v.push({k:e+r,v:n})}for(v.sort((function(t,e){return e.v-t.v})),r=0;rc(n)?1:-1}}(t)),n=u(i),r=0;r{"use strict";var r=n(54635),i=n(47137),o=n(86593),a=n(75982),u=n(84117),s=n(17761),c=n(81912),d=n(74842),l=n(19402),f=n(39850),p=n(41665)("splice"),h=Math.max,y=Math.min;r({target:"Array",proto:!0,forced:!p},{splice:function(t,e){var n,r,p,m,v,g,_=i(this),b=u(_),S=o(t,b),w=arguments.length;for(0===w?n=r=0:1===w?(n=0,r=b-S):(n=w-2,r=y(h(a(e),0),b-S)),c(b+n-r),p=d(_,r),m=0;mb-r+n;m--)f(_,m-1)}else if(n>r)for(m=b-r;m>S;m--)g=m+n-1,(v=m+r-1)in _?_[g]=_[v]:f(_,g);for(m=0;m{n(47512)("flatMap")},16368:(t,e,n)=>{var r=n(98511),i=n(43068),o=n(68959),a=n(30191)("toPrimitive"),u=Date.prototype;r(u,a)||i(u,a,o)},34745:(t,e,n)=>{var r=n(12115),i=n(27765).EXISTS,o=n(59913),a=n(43087).f,u=Function.prototype,s=o(u.toString),c=/function\b(?:\s|\/\*[\S\s]*?\*\/|\/\/[^\n\r]*[\n\r]+)*([^\s(/]*)/,d=o(c.exec);r&&!i&&a(u,"name",{configurable:!0,get:function(){try{return d(c,s(this))[1]}catch(t){return""}}})},55205:(t,e,n)=>{var r=n(54635),i=n(83155),o=n(10584),a=n(49425),u=n(59913),s=n(38986),c=n(65351),d=n(34028),l=n(51355),f=n(24505),p=n(23141),h=n(86263),y=i("JSON","stringify"),m=u(/./.exec),v=u("".charAt),g=u("".charCodeAt),_=u("".replace),b=u(1..toString),S=/[\uD800-\uDFFF]/g,w=/^[\uD800-\uDBFF]$/,C=/^[\uDC00-\uDFFF]$/,E=!h||s((function(){var t=i("Symbol")();return"[null]"!=y([t])||"{}"!=y({a:t})||"{}"!=y(Object(t))})),I=s((function(){return'"\\udf06\\ud834"'!==y("\udf06\ud834")||'"\\udead"'!==y("\udead")})),P=function(t,e){var n=p(arguments),r=e;if((l(e)||void 0!==t)&&!f(t))return c(e)||(e=function(t,e){if(d(r)&&(e=a(r,this,t,e)),!f(e))return e}),n[1]=e,o(y,null,n)},A=function(t,e,n){var r=v(n,e-1),i=v(n,e+1);return m(w,t)&&!m(C,i)||m(C,t)&&!m(w,r)?"\\u"+b(g(t,0),16):t};y&&r({target:"JSON",stat:!0,arity:3,forced:E||I},{stringify:function(t,e,n){var r=p(arguments),i=o(E?P:y,null,r);return I&&"string"==typeof i?_(i,S,A):i}})},3635:(t,e,n)=>{"use strict";n(69866)("Map",(function(t){return function(){return t(this,arguments.length?arguments[0]:void 0)}}),n(61961))},34897:(t,e,n)=>{n(3635)},99023:(t,e,n)=>{"use strict";var r=n(12115),i=n(32022),o=n(59913),a=n(77987),u=n(43068),s=n(98511),c=n(99618),d=n(27357),l=n(24505),f=n(99127),p=n(38986),h=n(92775).f,y=n(66213).f,m=n(43087).f,v=n(10829),g=n(76109).trim,_="Number",b=i[_],S=b.prototype,w=i.TypeError,C=o("".slice),E=o("".charCodeAt);if(a(_,!b(" 0o1")||!b("0b1")||b("+0x1"))){for(var I,P=function(t){var e=arguments.length<1?0:b(function(t){var e=f(t,"number");return"bigint"==typeof e?e:function(t){var e,n,r,i,o,a,u,s,c=f(t,"number");if(l(c))throw w("Cannot convert a Symbol value to a number");if("string"==typeof c&&c.length>2)if(c=g(c),43===(e=E(c,0))||45===e){if(88===(n=E(c,2))||120===n)return NaN}else if(48===e){switch(E(c,1)){case 66:case 98:r=2,i=49;break;case 79:case 111:r=8,i=55;break;default:return+c}for(a=(o=C(c,2)).length,u=0;ui)return NaN;return parseInt(o,r)}return+c}(e)}(t)),n=this;return d(S,n)&&p((function(){v(n)}))?c(Object(e),n,P):e},A=r?h(b):"MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,isFinite,isInteger,isNaN,isSafeInteger,parseFloat,parseInt,fromString,range".split(","),O=0;A.length>O;O++)s(b,I=A[O])&&!s(P,I)&&m(P,I,y(b,I));P.prototype=S,S.constructor=P,u(i,_,P,{constructor:!0})}},80226:(t,e,n)=>{n(54635)({target:"Number",stat:!0},{isNaN:function(t){return t!=t}})},21212:(t,e,n)=>{"use strict";var r=n(54635),i=n(59913),o=n(75982),a=n(10829),u=n(48126),s=n(38986),c=RangeError,d=String,l=Math.floor,f=i(u),p=i("".slice),h=i(1..toFixed),y=function(t,e,n){return 0===e?n:e%2==1?y(t,e-1,n*t):y(t*t,e/2,n)},m=function(t,e,n){for(var r=-1,i=n;++r<6;)i+=e*t[r],t[r]=i%1e7,i=l(i/1e7)},v=function(t,e){for(var n=6,r=0;--n>=0;)r+=t[n],t[n]=l(r/e),r=r%e*1e7},g=function(t){for(var e=6,n="";--e>=0;)if(""!==n||0===e||0!==t[e]){var r=d(t[e]);n=""===n?r:n+f("0",7-r.length)+r}return n};r({target:"Number",proto:!0,forced:s((function(){return"0.000"!==h(8e-5,3)||"1"!==h(.9,0)||"1.25"!==h(1.255,2)||"1000000000000000128"!==h(0xde0b6b3a7640080,0)}))||!s((function(){h({})}))},{toFixed:function(t){var e,n,r,i,u=a(this),s=o(t),l=[0,0,0,0,0,0],h="",_="0";if(s<0||s>20)throw c("Incorrect fraction digits");if(u!=u)return"NaN";if(u<=-1e21||u>=1e21)return d(u);if(u<0&&(h="-",u=-u),u>1e-21)if(n=(e=function(t){for(var e=0,n=t;n>=4096;)e+=12,n/=4096;for(;n>=2;)e+=1,n/=2;return e}(u*y(2,69,1))-69)<0?u*y(2,-e,1):u/y(2,e,1),n*=4503599627370496,(e=52-e)>0){for(m(l,0,n),r=s;r>=7;)m(l,1e7,0),r-=7;for(m(l,y(10,r,1),0),r=e-1;r>=23;)v(l,1<<23),r-=23;v(l,1<0?h+((i=_.length)<=s?"0."+f("0",s-i)+_:p(_,0,i-s)+"."+p(_,i-s)):h+_}})},27835:(t,e,n)=>{var r=n(54635),i=n(86851);r({target:"Object",stat:!0,arity:2,forced:Object.assign!==i},{assign:i})},64701:(t,e,n)=>{var r=n(54635),i=n(76389).entries;r({target:"Object",stat:!0},{entries:function(t){return i(t)}})},33409:(t,e,n)=>{var r=n(54635),i=n(6769),o=n(38986),a=n(51355),u=n(67023).onFreeze,s=Object.freeze;r({target:"Object",stat:!0,forced:o((function(){s(1)})),sham:!i},{freeze:function(t){return s&&a(t)?s(u(t)):t}})},19926:(t,e,n)=>{var r=n(54635),i=n(38986),o=n(58326),a=n(66213).f,u=n(12115),s=i((function(){a(1)}));r({target:"Object",stat:!0,forced:!u||s,sham:!u},{getOwnPropertyDescriptor:function(t,e){return a(o(t),e)}})},60678:(t,e,n)=>{var r=n(54635),i=n(38986),o=n(12098).f;r({target:"Object",stat:!0,forced:i((function(){return!Object.getOwnPropertyNames(1)}))},{getOwnPropertyNames:o})},17524:(t,e,n)=>{var r=n(54635),i=n(86263),o=n(38986),a=n(31711),u=n(47137);r({target:"Object",stat:!0,forced:!i||o((function(){a.f(1)}))},{getOwnPropertySymbols:function(t){var e=a.f;return e?e(u(t)):[]}})},71582:(t,e,n)=>{var r=n(54635),i=n(38986),o=n(47137),a=n(75783),u=n(88538);r({target:"Object",stat:!0,forced:i((function(){a(1)})),sham:!u},{getPrototypeOf:function(t){return a(o(t))}})},97814:(t,e,n)=>{var r=n(54635),i=n(38986),o=n(51355),a=n(39523),u=n(1743),s=Object.isFrozen;r({target:"Object",stat:!0,forced:i((function(){s(1)}))||u},{isFrozen:function(t){return!o(t)||!(!u||"ArrayBuffer"!=a(t))||!!s&&s(t)}})},13722:(t,e,n)=>{var r=n(54635),i=n(47137),o=n(95932);r({target:"Object",stat:!0,forced:n(38986)((function(){o(1)}))},{keys:function(t){return o(i(t))}})},28101:(t,e,n)=>{n(54635)({target:"Object",stat:!0},{setPrototypeOf:n(25466)})},40737:(t,e,n)=>{var r=n(77568),i=n(43068),o=n(75954);r||i(Object.prototype,"toString",o,{unsafe:!0})},83681:(t,e,n)=>{var r=n(54635),i=n(57017);r({global:!0,forced:parseFloat!=i},{parseFloat:i})},50633:(t,e,n)=>{var r=n(54635),i=n(84475);r({global:!0,forced:parseInt!=i},{parseInt:i})},47197:(t,e,n)=>{"use strict";var r=n(54635),i=n(49425),o=n(86173),a=n(67892),u=n(25786),s=n(38640);r({target:"Promise",stat:!0,forced:n(22208)},{all:function(t){var e=this,n=a.f(e),r=n.resolve,c=n.reject,d=u((function(){var n=o(e.resolve),a=[],u=0,d=1;s(t,(function(t){var o=u++,s=!1;d++,i(n,e,t).then((function(t){s||(s=!0,a[o]=t,--d||r(a))}),c)})),--d||r(a)}));return d.error&&c(d.value),n.promise}})},41395:(t,e,n)=>{"use strict";var r=n(54635),i=n(68546),o=n(93494).CONSTRUCTOR,a=n(33183),u=n(83155),s=n(34028),c=n(43068),d=a&&a.prototype;if(r({target:"Promise",proto:!0,forced:o,real:!0},{catch:function(t){return this.then(void 0,t)}}),!i&&s(a)){var l=u("Promise").prototype.catch;d.catch!==l&&c(d,"catch",l,{unsafe:!0})}},59761:(t,e,n)=>{"use strict";var r,i,o,a=n(54635),u=n(68546),s=n(79456),c=n(32022),d=n(49425),l=n(43068),f=n(25466),p=n(27747),h=n(42343),y=n(86173),m=n(34028),v=n(51355),g=n(39837),_=n(33820),b=n(16416).set,S=n(76173),w=n(39361),C=n(25786),E=n(97278),I=n(78045),P=n(33183),A=n(93494),O=n(67892),T="Promise",x=A.CONSTRUCTOR,R=A.REJECTION_EVENT,k=A.SUBCLASSING,M=I.getterFor(T),N=I.set,D=P&&P.prototype,L=P,z=D,j=c.TypeError,U=c.document,F=c.process,q=O.f,B=q,G=!!(U&&U.createEvent&&c.dispatchEvent),V="unhandledrejection",Y=function(t){var e;return!(!v(t)||!m(e=t.then))&&e},H=function(t,e){var n,r,i,o=e.value,a=1==e.state,u=a?t.ok:t.fail,s=t.resolve,c=t.reject,l=t.domain;try{u?(a||(2===e.rejection&&J(e),e.rejection=1),!0===u?n=o:(l&&l.enter(),n=u(o),l&&(l.exit(),i=!0)),n===t.promise?c(j("Promise-chain cycle")):(r=Y(n))?d(r,n,s,c):s(n)):c(o)}catch(t){l&&!i&&l.exit(),c(t)}},W=function(t,e){t.notified||(t.notified=!0,S((function(){for(var n,r=t.reactions;n=r.get();)H(n,t);t.notified=!1,e&&!t.rejection&&Z(t)})))},K=function(t,e,n){var r,i;G?((r=U.createEvent("Event")).promise=e,r.reason=n,r.initEvent(t,!1,!0),c.dispatchEvent(r)):r={promise:e,reason:n},!R&&(i=c["on"+t])?i(r):t===V&&w("Unhandled promise rejection",n)},Z=function(t){d(b,c,(function(){var e,n=t.facade,r=t.value;if($(t)&&(e=C((function(){s?F.emit("unhandledRejection",r,n):K(V,n,r)})),t.rejection=s||$(t)?2:1,e.error))throw e.value}))},$=function(t){return 1!==t.rejection&&!t.parent},J=function(t){d(b,c,(function(){var e=t.facade;s?F.emit("rejectionHandled",e):K("rejectionhandled",e,t.value)}))},Q=function(t,e,n){return function(r){t(e,r,n)}},X=function(t,e,n){t.done||(t.done=!0,n&&(t=n),t.value=e,t.state=2,W(t,!0))},tt=function(t,e,n){if(!t.done){t.done=!0,n&&(t=n);try{if(t.facade===e)throw j("Promise can't be resolved itself");var r=Y(e);r?S((function(){var n={done:!1};try{d(r,e,Q(tt,n,t),Q(X,n,t))}catch(e){X(n,e,t)}})):(t.value=e,t.state=1,W(t,!1))}catch(e){X({done:!1},e,t)}}};if(x&&(z=(L=function(t){g(this,z),y(t),d(r,this);var e=M(this);try{t(Q(tt,e),Q(X,e))}catch(t){X(e,t)}}).prototype,(r=function(t){N(this,{type:T,done:!1,notified:!1,parent:!1,reactions:new E,rejection:!1,state:0,value:void 0})}).prototype=l(z,"then",(function(t,e){var n=M(this),r=q(_(this,L));return n.parent=!0,r.ok=!m(t)||t,r.fail=m(e)&&e,r.domain=s?F.domain:void 0,0==n.state?n.reactions.add(r):S((function(){H(r,n)})),r.promise})),i=function(){var t=new r,e=M(t);this.promise=t,this.resolve=Q(tt,e),this.reject=Q(X,e)},O.f=q=function(t){return t===L||void 0===t?new i(t):B(t)},!u&&m(P)&&D!==Object.prototype)){o=D.then,k||l(D,"then",(function(t,e){var n=this;return new L((function(t,e){d(o,n,t,e)})).then(t,e)}),{unsafe:!0});try{delete D.constructor}catch(t){}f&&f(D,z)}a({global:!0,constructor:!0,wrap:!0,forced:x},{Promise:L}),p(L,T,!1,!0),h(T)},83823:(t,e,n)=>{n(59761),n(47197),n(41395),n(99790),n(38777),n(79244)},99790:(t,e,n)=>{"use strict";var r=n(54635),i=n(49425),o=n(86173),a=n(67892),u=n(25786),s=n(38640);r({target:"Promise",stat:!0,forced:n(22208)},{race:function(t){var e=this,n=a.f(e),r=n.reject,c=u((function(){var a=o(e.resolve);s(t,(function(t){i(a,e,t).then(n.resolve,r)}))}));return c.error&&r(c.value),n.promise}})},38777:(t,e,n)=>{"use strict";var r=n(54635),i=n(49425),o=n(67892);r({target:"Promise",stat:!0,forced:n(93494).CONSTRUCTOR},{reject:function(t){var e=o.f(this);return i(e.reject,void 0,t),e.promise}})},79244:(t,e,n)=>{"use strict";var r=n(54635),i=n(83155),o=n(68546),a=n(33183),u=n(93494).CONSTRUCTOR,s=n(39062),c=i("Promise"),d=o&&!u;r({target:"Promise",stat:!0,forced:o||u},{resolve:function(t){return s(d&&this===c?a:this,t)}})},84868:(t,e,n)=>{var r=n(12115),i=n(32022),o=n(59913),a=n(77987),u=n(99618),s=n(22775),c=n(92775).f,d=n(27357),l=n(91035),f=n(74170),p=n(79517),h=n(13917),y=n(83623),m=n(43068),v=n(38986),g=n(98511),_=n(78045).enforce,b=n(42343),S=n(30191),w=n(45969),C=n(25404),E=S("match"),I=i.RegExp,P=I.prototype,A=i.SyntaxError,O=o(P.exec),T=o("".charAt),x=o("".replace),R=o("".indexOf),k=o("".slice),M=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,N=/a/g,D=/a/g,L=new I(N)!==N,z=h.MISSED_STICKY,j=h.UNSUPPORTED_Y;if(a("RegExp",r&&(!L||z||w||C||v((function(){return D[E]=!1,I(N)!=N||I(D)==D||"/a/i"!=I(N,"i")}))))){for(var U=function(t,e){var n,r,i,o,a,c,h=d(P,this),y=l(t),m=void 0===e,v=[],b=t;if(!h&&y&&m&&t.constructor===U)return t;if((y||d(P,t))&&(t=t.source,m&&(e=p(b))),t=void 0===t?"":f(t),e=void 0===e?"":f(e),b=t,w&&"dotAll"in N&&(r=!!e&&R(e,"s")>-1)&&(e=x(e,/s/g,"")),n=e,z&&"sticky"in N&&(i=!!e&&R(e,"y")>-1)&&j&&(e=x(e,/y/g,"")),C&&(o=function(t){for(var e,n=t.length,r=0,i="",o=[],a={},u=!1,s=!1,c=0,d="";r<=n;r++){if("\\"===(e=T(t,r)))e+=T(t,++r);else if("]"===e)u=!1;else if(!u)switch(!0){case"["===e:u=!0;break;case"("===e:O(M,k(t,r+1))&&(r+=2,s=!0),i+=e,c++;continue;case">"===e&&s:if(""===d||g(a,d))throw new A("Invalid capture group name");a[d]=!0,o[o.length]=[d,c],s=!1,d="";continue}s?d+=e:i+=e}return[i,o]}(t),t=o[0],v=o[1]),a=u(I(t,e),h?this:P,U),(r||i||v.length)&&(c=_(a),r&&(c.dotAll=!0,c.raw=U(function(t){for(var e,n=t.length,r=0,i="",o=!1;r<=n;r++)"\\"!==(e=T(t,r))?o||"."!==e?("["===e?o=!0:"]"===e&&(o=!1),i+=e):i+="[\\s\\S]":i+=e+T(t,++r);return i}(t),n)),i&&(c.sticky=!0),v.length&&(c.groups=v)),t!==b)try{s(a,"source",""===b?"(?:)":b)}catch(t){}return a},F=c(I),q=0;F.length>q;)y(U,I,F[q++]);P.constructor=U,U.prototype=P,m(i,"RegExp",U,{constructor:!0})}b("RegExp")},49636:(t,e,n)=>{"use strict";var r=n(54635),i=n(83046);r({target:"RegExp",proto:!0,forced:/./.exec!==i},{exec:i})},26667:(t,e,n)=>{"use strict";var r=n(27765).PROPER,i=n(43068),o=n(52546),a=n(74170),u=n(38986),s=n(79517),c="toString",d=RegExp.prototype[c],l=u((function(){return"/a/b"!=d.call({source:"a",flags:"b"})})),f=r&&d.name!=c;(l||f)&&i(RegExp.prototype,c,(function(){var t=o(this);return"/"+a(t.source)+"/"+a(s(t))}),{unsafe:!0})},1386:(t,e,n)=>{"use strict";n(69866)("Set",(function(t){return function(){return t(this,arguments.length?arguments[0]:void 0)}}),n(61961))},98351:(t,e,n)=>{n(1386)},51996:(t,e,n)=>{"use strict";var r,i=n(54635),o=n(59913),a=n(66213).f,u=n(9375),s=n(74170),c=n(17911),d=n(31591),l=n(41813),f=n(68546),p=o("".endsWith),h=o("".slice),y=Math.min,m=l("endsWith");i({target:"String",proto:!0,forced:!(!f&&!m&&(r=a(String.prototype,"endsWith"),r&&!r.writable)||m)},{endsWith:function(t){var e=s(d(this));c(t);var n=arguments.length>1?arguments[1]:void 0,r=e.length,i=void 0===n?r:y(u(n),r),o=s(t);return p?p(e,o,i):h(e,i-o.length,i)===o}})},74035:(t,e,n)=>{"use strict";var r=n(54635),i=n(59913),o=n(17911),a=n(31591),u=n(74170),s=n(41813),c=i("".indexOf);r({target:"String",proto:!0,forced:!s("includes")},{includes:function(t){return!!~c(u(a(this)),u(o(t)),arguments.length>1?arguments[1]:void 0)}})},10951:(t,e,n)=>{"use strict";var r=n(58402).charAt,i=n(74170),o=n(78045),a=n(53338),u=n(80251),s="String Iterator",c=o.set,d=o.getterFor(s);a(String,"String",(function(t){c(this,{type:s,string:i(t),index:0})}),(function(){var t,e=d(this),n=e.string,i=e.index;return i>=n.length?u(void 0,!0):(t=r(n,i),e.index+=t.length,u(t,!1))}))},88720:(t,e,n)=>{"use strict";var r=n(54635),i=n(89444);r({target:"String",proto:!0,forced:n(9120)("link")},{link:function(t){return i(this,"a","href",t)}})},15483:(t,e,n)=>{"use strict";var r=n(49425),i=n(26210),o=n(52546),a=n(87126),u=n(9375),s=n(74170),c=n(31591),d=n(34040),l=n(75527),f=n(70468);i("match",(function(t,e,n){return[function(e){var n=c(this),i=a(e)?void 0:d(e,t);return i?r(i,e,n):new RegExp(e)[t](s(n))},function(t){var r=o(this),i=s(t),a=n(e,r,i);if(a.done)return a.value;if(!r.global)return f(r,i);var c=r.unicode;r.lastIndex=0;for(var d,p=[],h=0;null!==(d=f(r,i));){var y=s(d[0]);p[h]=y,""===y&&(r.lastIndex=l(i,u(r.lastIndex),c)),h++}return 0===h?null:p}]}))},40550:(t,e,n)=>{"use strict";var r=n(54635),i=n(59015).end;r({target:"String",proto:!0,forced:n(4465)},{padEnd:function(t){return i(this,t,arguments.length>1?arguments[1]:void 0)}})},79963:(t,e,n)=>{"use strict";var r=n(54635),i=n(59015).start;r({target:"String",proto:!0,forced:n(4465)},{padStart:function(t){return i(this,t,arguments.length>1?arguments[1]:void 0)}})},41267:(t,e,n)=>{n(54635)({target:"String",proto:!0},{repeat:n(48126)})},58443:(t,e,n)=>{"use strict";var r=n(10584),i=n(49425),o=n(59913),a=n(26210),u=n(38986),s=n(52546),c=n(34028),d=n(87126),l=n(75982),f=n(9375),p=n(74170),h=n(31591),y=n(75527),m=n(34040),v=n(82319),g=n(70468),_=n(30191)("replace"),b=Math.max,S=Math.min,w=o([].concat),C=o([].push),E=o("".indexOf),I=o("".slice),P="$0"==="a".replace(/./,"$0"),A=!!/./[_]&&""===/./[_]("a","$0");a("replace",(function(t,e,n){var o=A?"$":"$0";return[function(t,n){var r=h(this),o=d(t)?void 0:m(t,_);return o?i(o,t,r,n):i(e,p(r),t,n)},function(t,i){var a=s(this),u=p(t);if("string"==typeof i&&-1===E(i,o)&&-1===E(i,"$<")){var d=n(e,a,u,i);if(d.done)return d.value}var h=c(i);h||(i=p(i));var m=a.global;if(m){var _=a.unicode;a.lastIndex=0}for(var P=[];;){var A=g(a,u);if(null===A)break;if(C(P,A),!m)break;""===p(A[0])&&(a.lastIndex=y(u,f(a.lastIndex),_))}for(var O,T="",x=0,R=0;R=x&&(T+=I(u,x,M)+j,x=M+k.length)}return T+I(u,x)}]}),!!u((function(){var t=/./;return t.exec=function(){var t=[];return t.groups={a:"7"},t},"7"!=="".replace(t,"$")}))||!P||A)},57347:(t,e,n)=>{"use strict";var r=n(49425),i=n(26210),o=n(52546),a=n(87126),u=n(31591),s=n(60528),c=n(74170),d=n(34040),l=n(70468);i("search",(function(t,e,n){return[function(e){var n=u(this),i=a(e)?void 0:d(e,t);return i?r(i,e,n):new RegExp(e)[t](c(n))},function(t){var r=o(this),i=c(t),a=n(e,r,i);if(a.done)return a.value;var u=r.lastIndex;s(u,0)||(r.lastIndex=0);var d=l(r,i);return s(r.lastIndex,u)||(r.lastIndex=u),null===d?-1:d.index}]}))},34500:(t,e,n)=>{"use strict";var r=n(10584),i=n(49425),o=n(59913),a=n(26210),u=n(52546),s=n(87126),c=n(91035),d=n(31591),l=n(33820),f=n(75527),p=n(9375),h=n(74170),y=n(34040),m=n(42893),v=n(70468),g=n(83046),_=n(13917),b=n(38986),S=_.UNSUPPORTED_Y,w=4294967295,C=Math.min,E=[].push,I=o(/./.exec),P=o(E),A=o("".slice);a("split",(function(t,e,n){var o;return o="c"=="abbc".split(/(b)*/)[1]||4!="test".split(/(?:)/,-1).length||2!="ab".split(/(?:ab)*/).length||4!=".".split(/(.?)(.?)/).length||".".split(/()()/).length>1||"".split(/.?/).length?function(t,n){var o=h(d(this)),a=void 0===n?w:n>>>0;if(0===a)return[];if(void 0===t)return[o];if(!c(t))return i(e,o,t,a);for(var u,s,l,f=[],p=(t.ignoreCase?"i":"")+(t.multiline?"m":"")+(t.unicode?"u":"")+(t.sticky?"y":""),y=0,v=new RegExp(t.source,p+"g");(u=i(g,v,o))&&!((s=v.lastIndex)>y&&(P(f,A(o,y,u.index)),u.length>1&&u.index=a));)v.lastIndex===u.index&&v.lastIndex++;return y===o.length?!l&&I(v,"")||P(f,""):P(f,A(o,y)),f.length>a?m(f,0,a):f}:"0".split(void 0,0).length?function(t,n){return void 0===t&&0===n?[]:i(e,this,t,n)}:e,[function(e,n){var r=d(this),a=s(e)?void 0:y(e,t);return a?i(a,e,r,n):i(o,h(r),e,n)},function(t,r){var i=u(this),a=h(t),s=n(o,i,a,r,o!==e);if(s.done)return s.value;var c=l(i,RegExp),d=i.unicode,y=(i.ignoreCase?"i":"")+(i.multiline?"m":"")+(i.unicode?"u":"")+(S?"g":"y"),m=new c(S?"^(?:"+i.source+")":i,y),g=void 0===r?w:r>>>0;if(0===g)return[];if(0===a.length)return null===v(m,a)?[a]:[];for(var _=0,b=0,E=[];b{"use strict";var r,i=n(54635),o=n(59913),a=n(66213).f,u=n(9375),s=n(74170),c=n(17911),d=n(31591),l=n(41813),f=n(68546),p=o("".startsWith),h=o("".slice),y=Math.min,m=l("startsWith");i({target:"String",proto:!0,forced:!(!f&&!m&&(r=a(String.prototype,"startsWith"),r&&!r.writable)||m)},{startsWith:function(t){var e=s(d(this));c(t);var n=u(y(arguments.length>1?arguments[1]:void 0,e.length)),r=s(t);return p?p(e,r,n):h(e,n,n+r.length)===r}})},91652:(t,e,n)=>{n(74962);var r=n(54635),i=n(9334);r({target:"String",proto:!0,name:"trimEnd",forced:"".trimEnd!==i},{trimEnd:i})},86630:(t,e,n)=>{var r=n(54635),i=n(97746);r({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==i},{trimLeft:i})},74962:(t,e,n)=>{var r=n(54635),i=n(9334);r({target:"String",proto:!0,name:"trimEnd",forced:"".trimRight!==i},{trimRight:i})},94064:(t,e,n)=>{n(86630);var r=n(54635),i=n(97746);r({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==i},{trimStart:i})},25959:(t,e,n)=>{"use strict";var r=n(54635),i=n(76109).trim;r({target:"String",proto:!0,forced:n(41017)("trim")},{trim:function(){return i(this)}})},9190:(t,e,n)=>{n(91165)("asyncIterator")},69106:(t,e,n)=>{"use strict";var r=n(54635),i=n(32022),o=n(49425),a=n(59913),u=n(68546),s=n(12115),c=n(86263),d=n(38986),l=n(98511),f=n(27357),p=n(52546),h=n(58326),y=n(79127),m=n(74170),v=n(71111),g=n(13250),_=n(95932),b=n(92775),S=n(12098),w=n(31711),C=n(66213),E=n(43087),I=n(13330),P=n(23659),A=n(43068),O=n(27905),T=n(57186),x=n(17307),R=n(60232),k=n(30191),M=n(58855),N=n(91165),D=n(47498),L=n(27747),z=n(78045),j=n(55883).forEach,U=T("hidden"),F="Symbol",q="prototype",B=z.set,G=z.getterFor(F),V=Object[q],Y=i.Symbol,H=Y&&Y[q],W=i.TypeError,K=i.QObject,Z=C.f,$=E.f,J=S.f,Q=P.f,X=a([].push),tt=O("symbols"),et=O("op-symbols"),nt=O("wks"),rt=!K||!K[q]||!K[q].findChild,it=s&&d((function(){return 7!=g($({},"a",{get:function(){return $(this,"a",{value:7}).a}})).a}))?function(t,e,n){var r=Z(V,e);r&&delete V[e],$(t,e,n),r&&t!==V&&$(V,e,r)}:$,ot=function(t,e){var n=tt[t]=g(H);return B(n,{type:F,tag:t,description:e}),s||(n.description=e),n},at=function(t,e,n){t===V&&at(et,e,n),p(t);var r=y(e);return p(n),l(tt,r)?(n.enumerable?(l(t,U)&&t[U][r]&&(t[U][r]=!1),n=g(n,{enumerable:v(0,!1)})):(l(t,U)||$(t,U,v(1,{})),t[U][r]=!0),it(t,r,n)):$(t,r,n)},ut=function(t,e){p(t);var n=h(e),r=_(n).concat(lt(n));return j(r,(function(e){s&&!o(st,n,e)||at(t,e,n[e])})),t},st=function(t){var e=y(t),n=o(Q,this,e);return!(this===V&&l(tt,e)&&!l(et,e))&&(!(n||!l(this,e)||!l(tt,e)||l(this,U)&&this[U][e])||n)},ct=function(t,e){var n=h(t),r=y(e);if(n!==V||!l(tt,r)||l(et,r)){var i=Z(n,r);return!i||!l(tt,r)||l(n,U)&&n[U][r]||(i.enumerable=!0),i}},dt=function(t){var e=J(h(t)),n=[];return j(e,(function(t){l(tt,t)||l(x,t)||X(n,t)})),n},lt=function(t){var e=t===V,n=J(e?et:h(t)),r=[];return j(n,(function(t){!l(tt,t)||e&&!l(V,t)||X(r,tt[t])})),r};c||(A(H=(Y=function(){if(f(H,this))throw W("Symbol is not a constructor");var t=arguments.length&&void 0!==arguments[0]?m(arguments[0]):void 0,e=R(t),n=function(t){this===V&&o(n,et,t),l(this,U)&&l(this[U],e)&&(this[U][e]=!1),it(this,e,v(1,t))};return s&&rt&&it(V,e,{configurable:!0,set:n}),ot(e,t)})[q],"toString",(function(){return G(this).tag})),A(Y,"withoutSetter",(function(t){return ot(R(t),t)})),P.f=st,E.f=at,I.f=ut,C.f=ct,b.f=S.f=dt,w.f=lt,M.f=function(t){return ot(k(t),t)},s&&($(H,"description",{configurable:!0,get:function(){return G(this).description}}),u||A(V,"propertyIsEnumerable",st,{unsafe:!0}))),r({global:!0,constructor:!0,wrap:!0,forced:!c,sham:!c},{Symbol:Y}),j(_(nt),(function(t){N(t)})),r({target:F,stat:!0,forced:!c},{useSetter:function(){rt=!0},useSimple:function(){rt=!1}}),r({target:"Object",stat:!0,forced:!c,sham:!s},{create:function(t,e){return void 0===e?g(t):ut(g(t),e)},defineProperty:at,defineProperties:ut,getOwnPropertyDescriptor:ct}),r({target:"Object",stat:!0,forced:!c},{getOwnPropertyNames:dt}),D(),L(Y,F),x[U]=!0},70472:(t,e,n)=>{"use strict";var r=n(54635),i=n(12115),o=n(32022),a=n(59913),u=n(98511),s=n(34028),c=n(27357),d=n(74170),l=n(43087).f,f=n(74953),p=o.Symbol,h=p&&p.prototype;if(i&&s(p)&&(!("description"in h)||void 0!==p().description)){var y={},m=function(){var t=arguments.length<1||void 0===arguments[0]?void 0:d(arguments[0]),e=c(h,this)?new p(t):void 0===t?p():p(t);return""===t&&(y[e]=!0),e};f(m,p),m.prototype=h,h.constructor=m;var v="Symbol(test)"==String(p("test")),g=a(h.valueOf),_=a(h.toString),b=/^Symbol\((.*)\)[^)]+$/,S=a("".replace),w=a("".slice);l(h,"description",{configurable:!0,get:function(){var t=g(this);if(u(y,t))return"";var e=_(t),n=v?w(e,7,-1):S(e,b,"$1");return""===n?void 0:n}}),r({global:!0,constructor:!0,forced:!0},{Symbol:m})}},83038:(t,e,n)=>{var r=n(54635),i=n(83155),o=n(98511),a=n(74170),u=n(27905),s=n(55666),c=u("string-to-symbol-registry"),d=u("symbol-to-string-registry");r({target:"Symbol",stat:!0,forced:!s},{for:function(t){var e=a(t);if(o(c,e))return c[e];var n=i("Symbol")(e);return c[e]=n,d[n]=e,n}})},93270:(t,e,n)=>{n(91165)("iterator")},93942:(t,e,n)=>{n(69106),n(83038),n(84272),n(55205),n(17524)},84272:(t,e,n)=>{var r=n(54635),i=n(98511),o=n(24505),a=n(84160),u=n(27905),s=n(55666),c=u("symbol-to-string-registry");r({target:"Symbol",stat:!0,forced:!s},{keyFor:function(t){if(!o(t))throw TypeError(a(t)+" is not a symbol");if(i(c,t))return c[t]}})},8962:(t,e,n)=>{var r=n(91165),i=n(47498);r("toPrimitive"),i()},56019:(t,e,n)=>{"use strict";var r,i=n(32022),o=n(59913),a=n(3193),u=n(67023),s=n(69866),c=n(31858),d=n(51355),l=n(62713),f=n(78045).enforce,p=n(74112),h=!i.ActiveXObject&&"ActiveXObject"in i,y=function(t){return function(){return t(this,arguments.length?arguments[0]:void 0)}},m=s("WeakMap",y,c);if(p&&h){r=c.getConstructor(y,"WeakMap",!0),u.enable();var v=m.prototype,g=o(v.delete),_=o(v.has),b=o(v.get),S=o(v.set);a(v,{delete:function(t){if(d(t)&&!l(t)){var e=f(this);return e.frozen||(e.frozen=new r),g(this,t)||e.frozen.delete(t)}return g(this,t)},has:function(t){if(d(t)&&!l(t)){var e=f(this);return e.frozen||(e.frozen=new r),_(this,t)||e.frozen.has(t)}return _(this,t)},get:function(t){if(d(t)&&!l(t)){var e=f(this);return e.frozen||(e.frozen=new r),_(this,t)?b(this,t):e.frozen.get(t)}return b(this,t)},set:function(t,e){if(d(t)&&!l(t)){var n=f(this);n.frozen||(n.frozen=new r),_(this,t)?S(this,t,e):n.frozen.set(t,e)}else S(this,t,e);return this}})}},5963:(t,e,n)=>{n(56019)},71806:(t,e,n)=>{var r=n(32022),i=n(66910),o=n(73391),a=n(33609),u=n(22775),s=function(t){if(t&&t.forEach!==a)try{u(t,"forEach",a)}catch(e){t.forEach=a}};for(var c in i)i[c]&&s(r[c]&&r[c].prototype);s(o)},5193:(t,e,n)=>{var r=n(32022),i=n(66910),o=n(73391),a=n(38490),u=n(22775),s=n(30191),c=s("iterator"),d=s("toStringTag"),l=a.values,f=function(t,e){if(t){if(t[c]!==l)try{u(t,c,l)}catch(e){t[c]=l}if(t[d]||u(t,d,e),i[e])for(var n in a)if(t[n]!==a[n])try{u(t,n,a[n])}catch(e){t[n]=a[n]}}};for(var p in i)f(r[p]&&r[p].prototype,p);f(o,"DOMTokenList")},72031:(t,e,n)=>{"use strict";var r=n(54635),i=n(49425);r({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return i(URL.prototype.toString,this)}})}},e={};function n(r){var i=e[r];if(void 0!==i)return i.exports;var o=e[r]={id:r,loaded:!1,exports:{}};return t[r].call(o.exports,o,o.exports,n),o.loaded=!0,o.exports}n.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var r in e)n.o(e,r)&&!n.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.nmd=t=>(t.paths=[],t.children||(t.children=[]),t);var r={};return(()=>{"use strict";n.r(r),n.d(r,{createCheckoutButtonInitializer:()=>Wu,createTimeout:()=>e.createTimeout});var t={};n.r(t),n.d(t,{createApplePayButtonStrategy:()=>au,createBoltButtonStrategy:()=>yu,createPayPalCommerceAlternativeMethodsButtonStrategy:()=>ju,createPayPalCommerceButtonStrategy:()=>ku,createPayPalCommerceCreditButtonStrategy:()=>Nu,createPayPalCommerceVenmoButtonStrategy:()=>Lu,createPaypalExpressButtonStrategy:()=>Hu});var e=n(14121),i=n(13751),o=n(61699),a=n(45346);const u=function(t){function e(e){var n,r,i=this.constructor,o=t.call(this,e||"An unexpected error has occurred.")||this;return o.name="StandardError",o.type="standard",n=o,r=i.prototype,Object.setPrototypeOf?Object.setPrototypeOf(n,r):n.__proto__=r,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(o,i):o.stack=new Error(o.message).stack,o}return(0,o.__extends)(e,t),e}(Error);var s={body:{},headers:{},status:0};const c=function(t){function e(e,n){var r=void 0===n?{}:n,i=r.message,o=r.errors,a=this,u=e||s,c=u.body,d=u.headers,l=u.status;return(a=t.call(this,i||"An unexpected error has occurred.")||this).name="RequestError",a.type="request",a.body=c,a.headers=d,a.status=l,a.errors=o||[],a}return(0,o.__extends)(e,t),e}(u),d=function(t){function e(e){var n=t.call(this,e,{message:"There is a problem processing your payment. Please try again later."})||this;return n.name="PaymentMethodInvalidError",n.type="payment_method_invalid",n}return(0,o.__extends)(e,t),e}(c);n(34745),n(28101);const l=function(t){function e(e){var n,r,i=this.constructor,o=t.call(this,e||"An unexpected error has occurred.")||this;return o.name="StandardError",o.type="standard",n=o,r=i.prototype,Object.setPrototypeOf?Object.setPrototypeOf(n,r):n.__proto__=r,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(o,i):o.stack=new Error(o.message).stack,o}return(0,o.__extends)(e,t),e}(Error);var f={body:{},headers:{},status:0};const p=function(t){function e(e,n){var r=void 0===n?{}:n,i=r.message,o=r.errors,a=this,u=e||f,s=u.body,c=u.headers,d=u.status;return(a=t.call(this,i||"An unexpected error has occurred.")||this).name="RequestError",a.type="request",a.body=s,a.headers=c,a.status=d,a.errors=o||[],a}return(0,o.__extends)(e,t),e}(l),h=function(t){function e(e,n){var r=t.call(this,e,{message:n||"An unexpected error has occurred. The checkout process cannot continue as a result."})||this;return r.name="UnrecoverableError",r.type="unrecoverable",r}return(0,o.__extends)(e,t),e}(p);n(93942),n(70472),n(93270),n(38490),n(40737),n(10951),n(34500),n(5193);var y=n(87275);function m(t){return t.reduce((function(t,e){return e?(0,o.__spreadArrays)(t,[e]):t}),[]).join(" ")}function v(t,e){var n=t.body.errors,r=void 0===n?[]:n;return new p(t,{message:g(r)||e,errors:r})}function g(t){if(Array.isArray(t))return t.reduce((function(t,e){return e&&e.message?(0,o.__spreadArrays)(t,[e.message]):t}),[]).join(" ")}n(64668),n(95412);const _=function(t){function e(e){var n=t.call(this,e,{message:"The request has timed out or aborted."})||this;return n.name="TimeoutError",n.type="timeout",n}return(0,o.__extends)(e,t),e}(p);function b(t){return b="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},b(t)}const S=function(){function t(){this._factoryMethods={},this.register("default",(function(t,e){return new p(t,{message:e})})),this.register("internal",(function(t,e){return function(t,e){var n=t.body,r=n.errors,i=void 0===r?[]:r;return new p(t,{message:m(i)||n.detail||n.title||e,errors:i.length?i.map((function(t){return{code:n.type,message:t}})):[{code:n.type,message:n.detail||n.title}]})}(t,e)})),this.register("storefront",(function(t,e){return function(t,e){var n=t.body;return new p(t,{message:e||n.detail||n.title,errors:[{code:n.code||n.type,message:n.detail||n.title}]})}(t,e)})),this.register("payment",(function(t,e){return v(t,e)})),this.register("timeout",(function(t){return new _(t)}))}return t.prototype.register=function(t,e){this._factoryMethods[t]=e},t.prototype.createError=function(t,e){return(this._factoryMethods[this._getType(t)]||this._factoryMethods.default)(t,e)},t.prototype._getType=function(t){if(0===t.status)return"timeout";if(this._isStorefrontErrorResponseBody(t.body))return"storefront";if(this._isInternalErrorResponseBody(t.body)){var e=(0,y.last)(t.body.type.split("/"));return e&&this._factoryMethods[e]?e:"internal"}var n=(0,y.last)(t.body&&t.body.errors);return n&&n.code&&this._factoryMethods[n.code]?n.code:"payment"},t.prototype._isStorefrontErrorResponseBody=function(t){var e=t;return!this._isInternalErrorResponseBody(t)&&"string"==typeof e.title&&"string"==typeof e.type&&"number"==typeof e.status&&"string"==typeof e.detail},t.prototype._isInternalErrorResponseBody=function(t){var e=t;return"object"===b(e.errors)&&"string"==typeof e.title&&"string"==typeof e.type&&"number"==typeof e.status},t}();var w,C,E,I,P=n(73531),A=n(63660);function O(t){return O="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},O(t)}function T(t,e){return Array.isArray(t)?t.map((function(t){return T(t,e)})):(0,y.isPlainObject)(t)?(0,y.transform)((0,y.omitBy)(t,e),(function(t,n,r){t[r]=T(n,e)}),{}):t}function x(t,e){return function(t){return t.type===C.ClearError}(e)?T(t,(function(t){return t===e.payload})):t}function R(t){return R="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},R(t)}function k(t,e,n){return t===e||(t&&e&&"object"===R(t)&&"object"===R(e)?Array.isArray(t)&&Array.isArray(e)?function(t,e,n){if(t.length!==e.length)return!1;for(var r=0,i=t.length;r-1){var i=n[r];return r>0&&(n.splice(r,1),n.unshift(i)),i.value}return Nn}return{get:r,put:function(e,i){r(e)===Nn&&(n.unshift({key:e,value:i}),n.length>t&&n.pop())},getEntries:function(){return n},clear:function(){n=[]}}}(s,d);function f(){var e=l.get(arguments);if(e===Nn){if(e=t.apply(null,arguments),c){var n=l.getEntries().find((function(t){return c(t.value,e)}));n&&(e=n.value)}l.put(arguments,e)}return e}return f.clearCache=function(){return l.clear()},f}function zn(t){return zn="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},zn(t)}function jn(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r0}})),H=Un(U,(function(t){return function(e){return!(!e||!e.nonce)||t()===Vn||t()===Yn}})),(0,Rn.qe)((function(t,e){return{getPaymentId:z({checkout:t,order:e}),getPaymentIdOrThrow:j({checkout:t,order:e}),getPaymentStatus:U({checkout:t,order:e}),getPaymentStatusOrThrow:F({checkout:t,order:e}),getPaymentToken:q({checkout:t,order:e}),getPaymentTokenOrThrow:B({checkout:t,order:e}),getPaymentRedirectUrl:G({checkout:t,order:e}),getPaymentRedirectUrlOrThrow:V({checkout:t,order:e}),isPaymentDataRequired:Y({checkout:t,order:e}),isPaymentDataSubmitted:H({checkout:t,order:e})}}))),Et=function(){var t=Un((function(t){return t.errors.applyError}),(function(t){return function(){return t}})),e=Un((function(t){return!!t.statuses.isApplying}),(function(t){return function(){return t}}));return(0,Rn.qe)((function(n){return void 0===n&&(n=Kn),{getApplyError:t(n),isApplying:e(n)}}))}(),Pt=function(){var t=Un((function(t){return t.errors.updateError}),(function(t){return function(){return t}})),e=Un((function(t){return!!t.statuses.isUpdating}),(function(t){return function(){return t}}));return(0,Rn.qe)((function(n){return void 0===n&&(n=Sn),{getUpdateError:t(n),isUpdating:e(n)}}))}(),At=(K=Un((function(t){return t.data}),(function(t){return function(){return t}})),Z=Un((function(t){return t.errors.sendError}),(function(t){return function(){return t}})),$=Un((function(t){return!!t.statuses.isSending}),(function(t){return function(){return t}})),(0,Rn.qe)((function(t){return void 0===t&&(t=ln),{getEmail:K(t),getSendError:Z(t),isSending:$(t)}}))),Ot=function(){var t=Un((function(t){return t.data}),(function(t){return function(){return t}})),e=Un((function(t){return t.data}),(function(t){return function(e){return null==t?void 0:t.find((function(t){return t.region===e}))}})),n=Un((function(t){return t.errors.loadError}),(function(t){return function(){return t}})),r=Un((function(t){return t.statuses.isLoading}),(function(t){return function(){return!!t}}));return(0,Rn.qe)((function(i){return void 0===i&&(i=zt),{getExtensions:t(i),getExtensionByRegion:e(i),getLoadError:n(i),isLoading:r(i)}}))}();return function(t,e){void 0===e&&(e={});var n=J(t.billingAddress),r=Q(t.cart),i=tt(t.checkoutButton),o=nt(t.countries),a=rt(t.coupons),u=it(t.customer),s=ot(t.customerStrategies),c=Ot(t.extensions),d=ct(t.formFields),l=at(t.giftCertificates),f=ut(t.instruments),p=wt(t.orderBillingAddress),h=dt(t.paymentMethods),y=lt(t.paymentStrategies),m=ft(t.pickupOptions),v=ht(t.remoteCheckout),g=yt(t.consignments),_=mt(t.shippingCountries),b=vt(t.shippingStrategies),S=Pt(t.subscriptions),w=Et(t.storeCredit),C=At(t.signInEmail),E=gt(t.consignments,r),I=bt(t.checkout,n,r,E,a,u,l),P=St(t.order,p,a),A=Ct(I,P),O={billingAddress:n,cart:r,checkout:I,checkoutButton:i,config:et(t.config,t.formFields),consignments:E,countries:o,coupons:a,customer:u,customerStrategies:s,extensions:c,form:d,giftCertificates:l,instruments:f,order:P,orderBillingAddress:p,payment:A,paymentMethods:h,paymentStrategies:y,pickupOptions:m,remoteCheckout:v,shippingAddress:g,shippingCountries:_,shippingStrategies:b,signInEmail:C,subscriptions:S,storeCredit:w};return e.shouldWarnMutation?function(t){return Object.keys(t).reduce((function(e,n){return e[n]=Bn(t[n]),e}),{})}(O):O}}function $n(t,e){void 0===t&&(t={});var n,r,i=(n=new S,["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((function(t){n.register(t,(function(t,e){return new h(t,e)}))})),n.register("invalid_payment_provider",(function(t){return new d(t)})),n.register("payment_config_not_found",(function(t){return new d(t)})),r=n,function(t){return(0,P.D)(t).pipe((0,A.K)((function(t){if(t instanceof Error||t.payload instanceof Error)throw t;if((n=t.payload)&&"object"===O(n)&&["body","headers","status","statusText"].every((function(t){return Object.prototype.hasOwnProperty.call(n,t)}))){var e=t.payload.body&&t.payload.body.detail;throw(0,o.__assign)((0,o.__assign)({},t),{payload:r.createError(t.payload,e)})}var n;throw t})))}),u=Zn();return(0,a.Mg)((0,a.UY)({billingAddress:L,cart:K,checkout:Pn,checkoutButton:rt,config:ct,consignments:je,countries:Zt,coupons:ht,customer:Pt,customerStrategies:kt,extensions:jt,formFields:Vt,giftCertificates:bt,instruments:Oe,orderBillingAddress:se,order:te,payment:de,paymentMethods:ye,paymentStrategies:we,pickupOptions:We,remoteCheckout:Ne,shippingCountries:Xe,shippingStrategies:an,signInEmail:fn,subscriptions:wn,storeCredit:vn}),t,(0,o.__assign)({actionTransformer:i,stateTransformer:function(t){return u(t)}},e))}var Jn=n(64074),Qn=(n(5963),n(7263));function Xn(t,e,n){var r=new WeakMap;function i(t){var n=this;return function(){for(var i,a=[],u=0;u=400&&t.status<500)throw new Cr(t);throw t}))},t.prototype.updateCheckout=function(t,e,n){var r=void 0===n?{}:n,i=r.params,a=(void 0===i?{}:i).include,u=r.timeout,s="/api/storefront/checkout/"+t,c=(0,o.__assign)({Accept:nr.JsonV1},ir);return this._requestSender.put(s,{params:{include:Sr(wr,a)},body:e,headers:c,timeout:u})},t}();n(16516);const Ir=function(){function t(){}return t.prototype.isEqual=function(t,e){return(0,y.isEqual)(this._normalize(t),this._normalize(e))},t.prototype._normalize=function(t){return{cartAmount:t.cartAmount,currency:t.currency,id:t.id,lineItems:{digitalItems:t.lineItems.digitalItems.slice().sort((function(t,e){return(""+t.productId+t.variantId).localeCompare(""+e.productId+e.variantId)})).map((function(t){return{extendedSalePrice:t.extendedSalePrice,productId:t.productId,quantity:t.quantity,variantId:t.variantId}})),giftCertificates:t.lineItems.giftCertificates.slice().sort((function(t,e){return(""+t.id).localeCompare(""+e.id)})).map((function(t){return{amount:t.amount,recipient:t.recipient}})),physicalItems:t.lineItems.physicalItems.slice().sort((function(t,e){return(""+t.productId+t.variantId).localeCompare(""+e.productId+e.variantId)})).map((function(t){return{extendedSalePrice:t.extendedSalePrice,productId:t.productId,quantity:t.quantity,variantId:t.variantId,giftWrapping:t.giftWrapping}}))}}},t}(),Pr=function(t){function e(e,n){var r=t.call(this,"An update to your shopping cart has been detected and your available shipping costs have been updated.")||this;return r.name="CartChangedError",r.type="cart_changed",r.data={previous:e,updated:n},r}return(0,o.__extends)(e,t),e}(l),Ar=function(){function t(t){this._checkoutRequestSender=t}return t.prototype.validate=function(t,e){var n=this;if(!t)throw new kn(xn.MissingCheckout);return this._checkoutRequestSender.loadCheckout(t.id,e).then((function(e){var r=new Ir;if(!(t.outstandingBalance===e.body.outstandingBalance&&n._compareCoupons(t.coupons,e.body.coupons)&&n._compareGiftCertificates(t.giftCertificates,e.body.giftCertificates)&&r.isEqual(t.cart,e.body.cart)))throw new Pr(n._getComparableCheckout(t),n._getComparableCheckout(e.body))}))},t.prototype._compareCoupons=function(t,e){return(0,y.isEqual)((0,y.map)(t,"code"),(0,y.map)(e,"code"))},t.prototype._compareGiftCertificates=function(t,e){return(0,y.isEqual)((0,y.map)(t,"code"),(0,y.map)(e,"code"))},t.prototype._getComparableCheckout=function(t){var e=t.cart,n=t.coupons,r=t.giftCertificates,i=t.outstandingBalance;return{cart:{cartAmount:e.cartAmount,currency:e.currency,lineItems:e.lineItems},coupons:n,giftCertificates:r,outstandingBalance:i}},t}(),Or=function(){function t(t){this._configRequestSender=t}return t.prototype.loadConfig=function(t){var e=this;return Jn.y.create((function(n){n.next((0,a.PH)(Q.LoadConfigRequested)),e._configRequestSender.loadConfig(t).then((function(t){n.next((0,a.PH)(Q.LoadConfigSucceeded,t.body)),n.complete()})).catch((function(t){n.error((0,a.bR)(Q.LoadConfigFailed,t))}))}))},(0,o.__decorate)([Xn],t.prototype,"loadConfig",null),t}(),Tr=function(){function t(t){this._requestSender=t}return t.prototype.loadConfig=function(t){var e=void 0===t?{}:t,n=e.timeout,r=e.params;return this._requestSender.get("/api/storefront/checkout-settings",{timeout:n,headers:(0,o.__assign)({Accept:nr.JsonV1,"X-API-INTERNAL":rr},ir),params:r}).catch((function(t){if(t.status>=400&&t.status<500)throw new Cr(t);throw t}))},t}();var xr=n(64440);function Rr(t){return Rr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Rr(t)}function kr(t){var e=t;return"object"===Rr(e)&&"object"===Rr(e.payload)&&"string"==typeof e.payload.token}const Mr=function(){function t(t,e,n){this._customerRequestSender=t,this._checkoutActionCreator=e,this._spamProtectionActionCreator=n}return t.prototype.createCustomer=function(t,e){var n=this;return function(r){var i=r.getState().config.getStoreConfigOrThrow().checkoutSettings.isStorefrontSpamProtectionEnabled,u=function(i){return(0,P.D)(n._customerRequestSender.createAccount((0,o.__assign)((0,o.__assign)({},t),{token:i}),e)).pipe((0,xr.w)((function(){return(0,sr.z)(n._checkoutActionCreator.loadCurrentCheckout(e)(r),(0,cr.of)((0,a.PH)(gt.CreateCustomerSucceeded)))})))};return(0,sr.z)((0,cr.of)((0,a.PH)(gt.CreateCustomerRequested)),i?(0,P.D)(n._spamProtectionActionCreator.execute()(r)).pipe((0,xr.w)((function(t){var e;return kr(t)?(0,sr.z)((0,cr.of)(t),u(null===(e=t.payload)||void 0===e?void 0:e.token)):(0,cr.of)(t)}))):u()).pipe((0,A.K)((function(t){return pr(gt.CreateCustomerFailed,t)})))}},t.prototype.createAddress=function(t,e){var n=this;return(0,sr.z)((0,cr.of)((0,a.PH)(gt.CreateCustomerAddressRequested)),(0,dr.P)((function(){return(0,o.__awaiter)(n,void 0,void 0,(function(){var n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._customerRequestSender.createAddress(t,e)];case 1:return n=r.sent().body,[2,(0,a.PH)(gt.CreateCustomerAddressSucceeded,n)]}}))}))}))).pipe((0,A.K)((function(t){return pr(gt.CreateCustomerAddressFailed,t)})))},t.prototype.signInCustomer=function(t,e){var n=this;return function(r){return(0,sr.z)((0,cr.of)((0,a.PH)(gt.SignInCustomerRequested)),(0,P.D)(n._customerRequestSender.signInCustomer(t,e)).pipe((0,xr.w)((function(t){var i=t.body;return(0,sr.z)(n._checkoutActionCreator.loadCurrentCheckout(e)(r),(0,cr.of)((0,a.PH)(gt.SignInCustomerSucceeded,i.data)))})))).pipe((0,A.K)((function(t){return pr(gt.SignInCustomerFailed,t)})))}},t.prototype.signOutCustomer=function(t){var e=this;return function(n){return(0,sr.z)((0,cr.of)((0,a.PH)(gt.SignOutCustomerRequested)),(0,P.D)(e._customerRequestSender.signOutCustomer(t)).pipe((0,xr.w)((function(r){var i=r.body;return(0,sr.z)(e._checkoutActionCreator.loadCurrentCheckout(t)(n),(0,cr.of)((0,a.PH)(gt.SignOutCustomerSucceeded,i.data)))})))).pipe((0,A.K)((function(t){return pr(gt.SignOutCustomerFailed,t)})))}},t}(),Nr=function(){function t(t){this._requestSender=t}return t.prototype.createAccount=function(t,e){var n=(void 0===e?{}:e).timeout;return this._requestSender.post("/api/storefront/customer",{timeout:n,headers:ir,body:t})},t.prototype.createAddress=function(t,e){var n=(void 0===e?{}:e).timeout;return this._requestSender.post("/api/storefront/customer-address",{timeout:n,headers:ir,body:t})},t.prototype.signInCustomer=function(t,e){var n=(void 0===e?{}:e).timeout;return this._requestSender.post("/internalapi/v1/checkout/customer",{timeout:n,headers:ir,body:t})},t.prototype.signOutCustomer=function(t){var e=(void 0===t?{}:t).timeout;return this._requestSender.delete("/internalapi/v1/checkout/customer",{timeout:e,headers:ir})},t}(),Dr=function(){function t(t){this._formFieldsRequestSender=t}return t.prototype.loadFormFields=function(t){var e=this;return(0,sr.z)((0,cr.of)((0,a.PH)(Lt.LoadFormFieldsRequested)),(0,dr.P)((function(){return(0,o.__awaiter)(e,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return[4,this._formFieldsRequestSender.loadFields(t)];case 1:return e=n.sent().body,[2,(0,a.PH)(Lt.LoadFormFieldsSucceeded,e)]}}))}))}))).pipe((0,A.K)((function(t){return pr(Lt.LoadFormFieldsFailed,t)})))},(0,o.__decorate)([Xn],t.prototype,"loadFormFields",null),t}(),Lr=function(){function t(t){this._requestSender=t}return t.prototype.loadFields=function(t){var e=(void 0===t?{}:t).timeout;return this._requestSender.get("/api/storefront/form-fields",{timeout:e,headers:(0,o.__assign)({Accept:nr.JsonV1,"X-API-INTERNAL":rr},ir)})},t}();n(95040);const zr=function(t){var e=this,n=new Promise((function(t,n){e.cancel=n}));this.promise=Promise.race([t,n])},jr=function(t){function e(e){var n=t.call(this,e||"Unable to proceed because the required element is unexpectedly detached from the page.")||this;return n.name="UnexpectedDetachmentError",n.type="unexpected_detachment",n}return(0,o.__extends)(e,t),e}(l),Ur=function(){function t(t){this._mutationObserver=t}return t.prototype.ensurePresence=function(t,e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r,i,a;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:n=new zr(e),(r=this._mutationObserver.create((function(e){e.forEach((function(e){0!==Array.from(e.removedNodes).filter((function(e){return t.some((function(t){return e===t||e.contains(t)}))})).length&&n.cancel(new jr)}))}))).observe(document.body,{childList:!0,subtree:!0}),o.label=1;case 1:return o.trys.push([1,3,,4]),[4,n.promise];case 2:return i=o.sent(),r.disconnect(),[2,i];case 3:throw a=o.sent(),r.disconnect(),a;case 4:return[2]}}))}))},t}();var Fr=function(){function t(t){void 0===t&&(t=window),this._window=t}return t.prototype.create=function(t){return new this._window.MutationObserver(t)},t}(),qr=n(55343),Br=n(20239),Gr=n(92160),Vr=n(31407);n(57347);const Yr=function(t){function e(e){var n=t.call(this,e||"Invalid arguments have been provided.")||this;return n.name="InvalidArgumentError",n.type="invalid_argument",n}return(0,o.__extends)(e,t),e}(l);function Hr(t){if(!/^(https?:)?\/\//.test(t))throw new Yr("The provided URL must be absolute.");var e=document.createElement("a");e.href=t;var n=e.port&&-1!==t.indexOf(e.hostname+":"+e.port)?e.port:"";return{hash:e.hash,hostname:e.hostname,href:e.href,origin:e.protocol+"//"+e.hostname+(n?":"+n:""),pathname:e.pathname,port:n,protocol:e.protocol,search:e.search}}function Wr(t,e){return t.type===e}const Kr=function(){function t(t,e){this._targetWindow=e,this._targetOrigin="*"===t?"*":Hr(t).origin}return t.prototype.post=function(t,e){var n=this,r=this._targetWindow;if(window!==r){if(!r)throw new Error("Unable to post message because target window is not set.");var i=e&&(0,qr.R)(window,"message").pipe((0,Br.h)((function(t){return t.origin===n._targetOrigin&&Wr(t.data,t.data.type)&&-1!==[e.successType,e.errorType].indexOf(t.data.type)})),(0,Gr.U)((function(t){if(e.errorType===t.data.type)throw t.data;return t.data})),(0,Vr.q)(1)).toPromise();return r.postMessage(t,this._targetOrigin),i}},t.prototype.setTarget=function(t){this._targetWindow=t},t}();n(19926);const Zr=function(t,e,n){return e&&n?$r(0,e,n):function(t){var e=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return(0,o.__extends)(e,t),e}(t);return Object.getOwnPropertyNames(t.prototype).forEach((function(n){var r=Object.getOwnPropertyDescriptor(t.prototype,n);r&&"constructor"!==n&&Object.defineProperty(e.prototype,n,$r(t.prototype,n,r))})),e}(t)};function $r(t,e,n){if("function"!=typeof n.value)return n;var r=n.value;return{get:function(){var t=r.bind(this);return Object.defineProperty(this,e,(0,o.__assign)((0,o.__assign)({},n),{value:t})),t},set:function(t){r=t}}}const Jr=function(){function t(t){var e;this._sourceOrigins=[Hr(t).origin,(e=Hr(t),Hr(0===e.hostname.indexOf("www")?e.href:e.href.replace(e.hostname,"www."+e.hostname))).origin],this._isListening=!1,this._listeners={}}return t.prototype.listen=function(){this._isListening||(this._isListening=!0,window.addEventListener("message",this._handleMessage))},t.prototype.stopListen=function(){this._isListening&&(this._isListening=!1,window.removeEventListener("message",this._handleMessage))},t.prototype.addListener=function(t,e){var n=this._listeners[t];n||(this._listeners[t]=n=[]),-1===n.indexOf(e)&&n.push(e)},t.prototype.removeListener=function(t,e){var n=this._listeners[t];if(n){var r=n.indexOf(e);r>=0&&n.splice(r,1)}},t.prototype.trigger=function(t){var e=this._listeners[t.type];e&&e.forEach((function(e){return e(t)}))},t.prototype._handleMessage=function(t){-1!==this._sourceOrigins.indexOf(t.origin)&&Wr(t.data,t.data.type)&&this.trigger(t.data)},(0,o.__decorate)([Zr],t.prototype,"_handleMessage",null),t}(),Qr=function(t){function e(){var e=t.call(this,"You haven't complete our spam protection challenge. Please try again.")||this;return e.name="SpamProtectionChallengeNotCompletedError",e.type="spam_protection_challenge_not_completed",e}return(0,o.__extends)(e,t),e}(l),Xr=function(t){function e(){var e=t.call(this,"Please complete our human verification challenge and try again.")||this;return e.name="CardingProtectionChallengeNotCompletedError",e.type="carding_protection_challenge_not_completed",e}return(0,o.__extends)(e,t),e}(l),ti=function(t){function e(){var e=t.call(this,"We were not able to verify that you are not a robot. Please try again.")||this;return e.name="CardingProtectionFailedError",e.type="carding_protection_failed",e}return(0,o.__extends)(e,t),e}(l),ei=function(){function t(t){this._googleRecaptcha=t}return t.prototype.handle=function(t,e){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(n){return"string"==typeof t?[2,this.handleWithRecaptchaSitekey(t,e)]:[2,this.handleWithPaymentHumanVerificationRequestError(t)]}))}))},t.prototype.handleWithPaymentHumanVerificationRequestError=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(e){switch(e.label){case 0:if(!this._isPaymentHumanVerificationRequest(t))throw t;return[4,this._initialize(t.body.additional_action_required.data.key)];case 1:return e.sent(),[2,this._performRecaptcha()]}}))}))},t.prototype.handleWithRecaptchaSitekey=function(t,e){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if("recaptcha_v2"!==t)throw Error("Human verification method is not supported.");if(!e)throw Error("Recaptcha site key is missing.");return[4,this._initialize(e)];case 1:return n.sent(),[2,this._performRecaptcha()]}}))}))},t.prototype._performRecaptcha=function(){var t=this;return this._googleRecaptcha.execute().pipe((0,Vr.q)(1)).pipe((0,xr.w)((function(e){var n=e.error,r=e.token;return(0,o.__awaiter)(t,void 0,void 0,(function(){return(0,o.__generator)(this,(function(t){if(n instanceof Qr)throw new Xr;if(n||!r)throw new ti;return[2,{type:"recaptcha_v2_verification",data:{human_verification_token:r}}]}))}))}))).toPromise()},t.prototype._initialize=function(t){var e="cardingProtectionContainer",n=document.getElementById(e);return n&&n.parentNode&&n.parentNode.removeChild(n),(n=document.createElement("div")).setAttribute("id",e),document.body.appendChild(n),this._googleRecaptcha.load(e,t)},t.prototype._isPaymentHumanVerificationRequest=function(t){var e=t.body||{},n=e.additional_action_required;return"additional_action_required"===e.status&&n&&"recaptcha_v2_verification"===n.type},t}();var ni,ri=n(99357),ii=n(62156),oi=n(5026);!function(t){t[t.CheckoutButtonNotInitialized=0]="CheckoutButtonNotInitialized",t[t.CustomerNotInitialized=1]="CustomerNotInitialized",t[t.PaymentNotInitialized=2]="PaymentNotInitialized",t[t.ShippingNotInitialized=3]="ShippingNotInitialized",t[t.SpamProtectionNotInitialized=4]="SpamProtectionNotInitialized"}(ni||(ni={}));const ai=function(t){function e(e){var n=t.call(this,function(t){switch(t){case ni.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case ni.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case ni.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case ni.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;return n.subtype=e,n.name="NotInitializedError",n.type="not_initialized",n}return(0,o.__extends)(e,t),e}(l),ui=function(t){function e(){var e=t.call(this,"We were not able to complete your spam protection verification. Please try again.")||this;return e.name="SpamProtectionFailedError",e.type="spam_protection_failed",e}return(0,o.__extends)(e,t),e}(l),si=function(t){function e(){var e=t.call(this,"Spam protection is not loaded. Please try again.")||this;return e.name="SpamProtectionNotLoadedError",e.type="spam_protection_failed",e}return(0,o.__extends)(e,t),e}(l),ci=function(){function t(t,e){var n=this;this.googleRecaptchaScriptLoader=t,this.mutationObserverFactory=e,this._memoized=(0,Rn.HP)((function(t,e,r){var i=new ri.xQ;if(!r)throw new Error;return n._widgetId=t.render(r.id,{sitekey:e,size:"invisible",callback:function(){i.next({token:t.getResponse(n._widgetId)}),t.reset(n._widgetId)},"error-callback":function(){i.next({error:new ui})}}),i}),{isEqual:function(t,e){return t===e}})}return t.prototype.load=function(t,e){var n=this;return this.googleRecaptchaScriptLoader.load().then((function(r){r&&(n._event$=n._memoized(r,e,document.getElementById(t)),n._recaptcha=r)}))},t.prototype.execute=function(){var t=this;return(0,dr.P)((function(){var e=t._event$,n=t._recaptcha;if(!e||!n)throw new ai(ni.SpamProtectionNotInitialized);return(0,dr.P)((function(){var t=document.querySelector('iframe[src*="bframe"]');return t?(0,cr.of)(t):(0,fr._)(new si)})).pipe((0,ii.a)((function(t){return t.pipe((0,oi.g)(250),(0,xr.w)((function(t,e){return e<28?(0,cr.of)(t):(0,fr._)(t)})))})),(0,xr.w)((function(r){return t._watchRecaptchaChallengeWindow(e,r),n.execute(t._widgetId),e})),(0,A.K)((function(t){return(0,cr.of)({error:t})})))}))},t.prototype._watchRecaptchaChallengeWindow=function(t,e){var n=e.parentElement;if(!n)throw new si;var r=n.parentElement;if(!r)throw new si;this.mutationObserverFactory.create((function(){"hidden"===r.style.visibility&&t.next({error:new Qr})})).observe(r,{attributes:!0,attributeFilter:["style"]})},t}();n(83823);const di=function(){function t(t,e){void 0===e&&(e=window),this._scriptLoader=t,this._window=e}return t.prototype.load=function(){return this._loadPromise||(this._loadPromise=this._loadScript()),this._loadPromise},t.prototype._loadScript=function(){var t=this,e="initRecaptcha",n=["onload="+e,"render=explicit"].join("&");return new Promise((function(r,i){t._window[e]=function(){return r(t._window.grecaptcha)},t._scriptLoader.loadScript("//www.google.com/recaptcha/api.js?"+n).catch((function(e){t._loadPromise=void 0,i(e)}))}))},t}();function li(t){return new ci(new di(t),new Fr)}const fi=function(t){function e(e){var n=t.call(this,e||"Unable to proceed due to invalid configuration provided for the hosted payment form.")||this;return n.name="InvalidHostedFormConfigError",n.type="invalid_hosted_form_config",n}return(0,o.__extends)(e,t),e}(l),pi=function(t){function e(e){var n=t.call(this,e||"Unable to proceed due to an unknown error with the hosted payment form.")||this;return n.name="InvalidHostedFormError",n.type="invalid_hosted_form",n}return(0,o.__extends)(e,t),e}(l),hi=function(t){function e(e){var n=t.call(this,(0,o.__spreadArrays)(["Unable to proceed due to invalid user input values"],(0,y.flatMap)((0,y.values)(e),(function(t){return(0,y.map)(t,(function(t){return t.message}))}))).join(". "))||this;return n.errors=e,n.name="InvalidHostedFormValueError",n.type="invalid_hosted_form_value",n}return(0,o.__extends)(e,t),e}(l);var yi,mi;!function(t){t.AttachRequested="HOSTED_FIELD:ATTACH_REQUESTED",t.SubmitRequested="HOSTED_FIELD:SUBMITTED_REQUESTED",t.ValidateRequested="HOSTED_FIELD:VALIDATE_REQUESTED"}(yi||(yi={})),function(t){t.AttachSucceeded="HOSTED_INPUT:ATTACH_SUCCEEDED",t.AttachFailed="HOSTED_INPUT:ATTACH_FAILED",t.BinChanged="HOSTED_INPUT:BIN_CHANGED",t.Blurred="HOSTED_INPUT:BLURRED",t.Changed="HOSTED_INPUT:CHANGED",t.CardTypeChanged="HOSTED_INPUT:CARD_TYPE_CHANGED",t.Entered="HOSTED_INPUT:ENTERED",t.Focused="HOSTED_INPUT:FOCUSED",t.SubmitSucceeded="HOSTED_INPUT:SUBMIT_SUCCEEDED",t.SubmitFailed="HOSTED_INPUT:SUBMIT_FAILED",t.Validated="HOSTED_INPUT:VALIDATED"}(mi||(mi={}));const vi=function(){function t(t,e,n,r,i,o,a,u,s){this._type=t,this._containerId=e,this._placeholder=n,this._accessibilityLabel=r,this._styles=i,this._eventPoster=o,this._eventListener=a,this._detachmentObserver=u,this._cardInstrument=s,this._iframe=document.createElement("iframe"),this._iframe.src="/checkout/payment/hosted-field?version=1.398.2",this._iframe.style.border="none",this._iframe.style.height="100%",this._iframe.style.overflow="hidden",this._iframe.style.width="100%"}return t.prototype.getType=function(){return this._type},t.prototype.attach=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,e,n=this;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:if(!(t=document.getElementById(this._containerId)))throw new fi("Unable to proceed because the provided container ID is not valid.");return t.appendChild(this._iframe),this._eventListener.listen(),e=(0,qr.R)(this._iframe,"load").pipe((0,xr.w)((function(t){var e=t.target;return(0,o.__awaiter)(n,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if(!(t=e&&e.contentWindow))throw new Error("The content window of the iframe cannot be accessed.");return this._eventPoster.setTarget(t),[4,this._eventPoster.post({type:yi.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:mi.AttachSucceeded,errorType:mi.AttachFailed})];case 1:return n.sent(),[2]}}))}))})),(0,Vr.q)(1)).toPromise(),[4,this._detachmentObserver.ensurePresence([this._iframe],e)];case 1:return r.sent(),[2]}}))}))},t.prototype.detach=function(){this._iframe.parentElement&&(this._iframe.parentElement.removeChild(this._iframe),this._eventListener.stopListen())},t.prototype.submitForm=function(t,e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),n=this._eventPoster.post({type:yi.SubmitRequested,payload:{fields:t,data:e}},{successType:mi.SubmitSucceeded,errorType:mi.SubmitFailed}),[4,this._detachmentObserver.ensurePresence([this._iframe],n)];case 1:return[2,i.sent()];case 2:if(r=i.sent(),this._isSubmitErrorEvent(r)){if("hosted_form_error"===r.payload.error.code)throw new pi(r.payload.error.message);if(r.payload.response)throw v(r.payload.response);throw new Error(r.payload.error.message)}throw r;case 3:return[2]}}))}))},t.prototype.validateForm=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return t=this._eventPoster.post({type:yi.ValidateRequested},{successType:mi.Validated}),[4,this._detachmentObserver.ensurePresence([this._iframe],t)];case 1:if(!(e=n.sent().payload).isValid)throw new hi(e.errors);return[2]}}))}))},t.prototype._getFontUrls=function(){var t=this,e="fonts.googleapis.com",n=document.querySelectorAll("link[href*='"+e+"'][rel='stylesheet']");return Array.prototype.slice.call(n).filter((function(t){return Hr(t.href).hostname===e})).filter((function(e){return(0,y.values)(t._styles).map((function(t){return t&&t.fontFamily})).filter((function(t){return"string"==typeof t})).some((function(t){return t.split(/,\s/).some((function(t){return-1!==e.href.indexOf(t.replace(" ","+"))}))}))})).map((function(t){return t.href}))},t.prototype._isSubmitErrorEvent=function(t){return t.type===mi.SubmitFailed},t}(),gi=function(){function t(t,e,n,r,i){var a=this;this._fields=t,this._eventListener=e,this._payloadTransformer=n,this._eventCallbacks=r,this._paymentHumanVerificationHandler=i,this._handleEnter=function(t){var e=t.payload;return(0,o.__awaiter)(a,void 0,void 0,(function(){var t,n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,this.validate()];case 1:return r.sent(),[3,3];case 2:if("InvalidHostedFormValueError"!==(t=r.sent()).name)throw t;return[3,3];case 3:return(void 0===(n=this._eventCallbacks.onEnter)?y.noop:n)(e),[2]}}))}))};var u=this._eventCallbacks,s=u.onBlur,c=void 0===s?y.noop:s,d=u.onCardTypeChange,l=void 0===d?y.noop:d,f=u.onFocus,p=void 0===f?y.noop:f,h=u.onValidate,m=void 0===h?y.noop:h;this._eventListener.addListener(mi.Blurred,(function(t){var e=t.payload;return c(e)})),this._eventListener.addListener(mi.CardTypeChanged,(function(t){var e=t.payload;return l(e)})),this._eventListener.addListener(mi.Focused,(function(t){var e=t.payload;return p(e)})),this._eventListener.addListener(mi.Validated,(function(t){var e=t.payload;return m(e)})),this._eventListener.addListener(mi.Entered,this._handleEnter),this._eventListener.addListener(mi.CardTypeChanged,(function(t){var e=t.payload;return a._cardType=e.cardType})),this._eventListener.addListener(mi.BinChanged,(function(t){var e=t.payload;return a._bin=e.bin}))}return t.prototype.getBin=function(){return this._bin},t.prototype.getCardType=function(){return this._cardType},t.prototype.attach=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return this._eventListener.listen(),t=this._getFirstField(),e=(0,y.without)(this._fields,t),[4,t.attach()];case 1:return n.sent(),[4,Promise.all(e.map((function(t){return t.attach()})))];case 2:return n.sent(),[2]}}))}))},t.prototype.detach=function(){this._eventListener.stopListen(),this._fields.forEach((function(t){t.detach()}))},t.prototype.submit=function(t,e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,5]),[4,this._getFirstField().submitForm(this._fields.map((function(t){return t.getType()})),this._payloadTransformer.transform(t,e))];case 1:case 4:return[2,i.sent()];case 2:return n=i.sent(),[4,this._paymentHumanVerificationHandler.handle(n)];case 3:return r=i.sent(),[4,this._getFirstField().submitForm(this._fields.map((function(t){return t.getType()})),this._payloadTransformer.transform(t,r))];case 5:return[2]}}))}))},t.prototype.validate=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(t){return[2,this._getFirstField().validateForm()]}))}))},t.prototype._getFirstField=function(){var t=this._fields[0];if(!t)throw new fi("Unable to proceed because the payment form has no field defined.");return t},t}();function _i(t){return Boolean(t.instrumentId)}const bi=function(){function t(t){this._store=t}return t.prototype.transform=function(t,e){var n=this._store.getState(),r=n.checkout.getCheckout(),i=n.config.getConfig(),o=n.instruments.getInstrumentsMeta(),a=n.order.getOrder(),u=n.order.getOrderMeta(),s=(0,y.omit)(t.paymentData,"ccExpiry","ccName","ccNumber","ccCvv"),c=n.paymentMethods.getPaymentMethod(t.methodId,t.gatewayId),d=n.paymentMethods.getPaymentMethodsMeta(),l=o&&s&&_i(s)?n.payment.getPaymentToken()+", "+o.vaultAccessToken:n.payment.getPaymentToken();if(!l)throw new kn(xn.MissingPaymentToken);return{additionalAction:e,authToken:l,checkout:r,config:i,order:a,orderMeta:u,payment:s,paymentMethod:c,paymentMethodMeta:d}},t}(),Si=function(){function t(t){this._store=t}return t.prototype.create=function(t,e){var n=this,r=Object.keys(e.fields).reduce((function(r,i){var a=e.fields[i];return a?(0,o.__spreadArrays)(r,[new vi(i,a.containerId,a.placeholder||"",a.accessibilityLabel||"",e.styles||{},new Kr(t),new Jr(t),new Ur(new Fr),"instrumentId"in a?n._getCardInstrument(a.instrumentId):void 0)]):r}),[]);return new gi(r,new Jr(t),new bi(this._store),(0,y.pick)(e,"onBlur","onEnter","onFocus","onCardTypeChange","onValidate"),new ei(li((0,ar.VD)())))},t.prototype._getCardInstrument=function(t){var e=(0,this._store.getState().instruments.getCardInstrument)(t);if(!e)throw new kn(xn.MissingPaymentInstrument);return e},t}(),wi=function(t){function e(){var e=t.call(this,"You haven't complete our spam check. Please try again.")||this;return e.name="SpamProtectionNotCompletedError",e.type="spam_protection_not_completed",e}return(0,o.__extends)(e,t),e}(l),Ci=function(){function t(t,e){this._orderRequestSender=t,this._checkoutValidator=e}return t.prototype.loadOrder=function(t,e){var n=this;return new Jn.y((function(r){r.next((0,a.PH)(ut.LoadOrderRequested)),n._orderRequestSender.loadOrder(t,e).then((function(t){r.next((0,a.PH)(ut.LoadOrderSucceeded,t.body)),r.complete()})).catch((function(t){r.error((0,a.bR)(ut.LoadOrderFailed,t))}))}))},t.prototype.loadOrderPayments=function(t,e){var n=this;return new Jn.y((function(r){r.next((0,a.PH)(ut.LoadOrderPaymentsRequested)),n._orderRequestSender.loadOrder(t,e).then((function(t){r.next((0,a.PH)(ut.LoadOrderPaymentsSucceeded,t.body)),r.complete()})).catch((function(t){r.error((0,a.bR)(ut.LoadOrderPaymentsFailed,t))}))}))},t.prototype.loadCurrentOrder=function(t){var e=this;return function(n){return(0,dr.P)((function(){var r=e._getCurrentOrderId(n.getState());if(!r)throw new kn(xn.MissingOrderId);return e.loadOrder(r,t)}))}},t.prototype.submitOrder=function(t,e){var n=this;return function(r){return(0,sr.z)((0,cr.of)((0,a.PH)(ut.SubmitOrderRequested)),(0,dr.P)((function(){var i=r.getState(),u=i.config.getExternalSource(),s=i.config.getVariantIdentificationToken(),c=i.checkout.getCheckout();if(!c)throw new kn(xn.MissingCheckout);if(c.shouldExecuteSpamCheck)throw new wi;return(0,P.D)(n._checkoutValidator.validate(c,e).then((function(){return n._orderRequestSender.submitOrder(n._mapToOrderRequestBody(null!=t?t:{},c.id,c.customerMessage,u),(0,o.__assign)((0,o.__assign)({},e),{headers:{checkoutVariant:s}}))}))).pipe((0,xr.w)((function(t){return(0,sr.z)(n.loadOrder(t.body.data.order.orderId,e),(0,cr.of)((0,a.PH)(ut.SubmitOrderSucceeded,t.body.data,(0,o.__assign)((0,o.__assign)({},t.body.meta),{token:t.headers.token}))))})))})).pipe((0,A.K)((function(t){return pr(ut.SubmitOrderFailed,t)}))))}},t.prototype.finalizeOrder=function(t,e){var n=this;return(0,sr.z)((0,cr.of)((0,a.PH)(ut.FinalizeOrderRequested)),(0,P.D)(this._orderRequestSender.finalizeOrder(t,e)).pipe((0,xr.w)((function(r){return(0,sr.z)(n.loadOrder(t,e),(0,cr.of)((0,a.PH)(ut.FinalizeOrderSucceeded,r.body.data)))})))).pipe((0,A.K)((function(t){return pr(ut.FinalizeOrderFailed,t)})))},t.prototype._getCurrentOrderId=function(t){var e=t.order.getOrder(),n=t.checkout.getCheckout();return e&&e.orderId||n&&n.orderId},t.prototype._mapToOrderRequestBody=function(t,e,n,r){var i=t.payment,a=(0,o.__rest)(t,["payment"]);return i?(0,o.__assign)((0,o.__assign)({},a),{cartId:e,customerMessage:n,externalSource:r,payment:{paymentData:i.paymentData,name:i.methodId,gateway:i.gatewayId}}):(0,o.__assign)((0,o.__assign)({},a),{cartId:e,customerMessage:n,externalSource:r})},t}(),Ei=function(t){function e(e){var n=t.call(this,e||"Your checkout could not be processed because some details have changed. Please review your order and try again.")||this;return n.name="CartConsistencyError",n.type="cart_consistency",n}return(0,o.__extends)(e,t),e}(l),Ii=function(t){function e(e){var n=t.call(this,e||"The tax provider is unavailable.")||this;return n.name="OrderTaxProviderUnavailableError",n.type="tax_provider_unavailable",n}return(0,o.__extends)(e,t),e}(l),Pi=function(){function t(t){this._requestSender=t}return t.prototype.loadOrder=function(t,e){var n=(void 0===e?{}:e).timeout,r="/api/storefront/orders/"+t,i=(0,o.__assign)({Accept:nr.JsonV1},ir);return this._requestSender.get(r,{params:{include:br(["payments","lineItems.physicalItems.socialMedia","lineItems.physicalItems.options","lineItems.physicalItems.categories","lineItems.digitalItems.socialMedia","lineItems.digitalItems.options","lineItems.digitalItems.categories"])},headers:i,timeout:n})},t.prototype.submitOrder=function(t,e){var n=void 0===e?{}:e,r=n.headers,i=n.timeout;return this._requestSender.post("/internalapi/v1/checkout/order",{body:t,headers:(0,y.omitBy)((0,o.__assign)({"X-Checkout-Variant":r&&r.checkoutVariant},ir),y.isNil),timeout:i}).catch((function(t){if("tax_provider_unavailable"===t.body.type)throw new Ii;if("cart_has_changed"===t.body.type)throw new Ei;throw t}))},t.prototype.finalizeOrder=function(t,e){var n=(void 0===e?{}:e).timeout,r="/internalapi/v1/checkout/order/"+t;return this._requestSender.post(r,{timeout:n,headers:ir})},t}(),Ai=function(){function t(t,e,n,r){var i=this;this._paymentRequestSender=t,this._orderActionCreator=e,this._paymentRequestTransformer=n,this._paymentHumanVerificationHandler=r,this.initializeOffsitePayment=function(t){var e=t.methodId,n=t.gatewayId,r=t.instrumentId,o=t.target,u=t.promise,s=t.shouldSaveInstrument,c=t.shouldSetAsDefaultInstrument;return function(t){var d;r?d={formattedPayload:{bigpay_token:r}}:s&&(d={formattedPayload:{vault_payment_instrument:s,set_as_default_stored_instrument:c||null}});var l=i._paymentRequestTransformer.transform({gatewayId:n,methodId:e,paymentData:d},t.getState());return(0,sr.z)((0,cr.of)((0,a.PH)(oe.InitializeOffsitePaymentRequested)),Promise.race([i._paymentRequestSender.initializeOffsitePayment(l,o),u].filter(Boolean)).then((function(){return(0,a.PH)(oe.InitializeOffsitePaymentSucceeded)}))).pipe((0,A.K)((function(t){return pr(oe.InitializeOffsitePaymentFailed,t)})))}}}return t.prototype.submitPayment=function(t){var e=this;return function(n){return(0,sr.z)((0,cr.of)((0,a.PH)(oe.SubmitPaymentRequested)),(0,dr.P)((function(){return(0,o.__awaiter)(e,void 0,void 0,(function(){var e,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,5]),[4,this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform(t,n.getState()))];case 1:case 4:return[2,i.sent()];case 2:return e=i.sent(),[4,this._paymentHumanVerificationHandler.handle(e)];case 3:return r=i.sent(),[4,this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform((0,o.__assign)((0,o.__assign)({},t),{additionalAction:r}),n.getState()))];case 5:return[2]}}))}))})).pipe((0,xr.w)((function(t){var r=t.body;return(0,sr.z)(e._orderActionCreator.loadCurrentOrder()(n),(0,cr.of)((0,a.PH)(oe.SubmitPaymentSucceeded,r)))})))).pipe((0,A.K)((function(t){return pr(oe.SubmitPaymentFailed,t)})))}},t}(),Oi=function(){function t(t){this._client=t}return t.prototype.submitPayment=function(t){var e=this;return new Promise((function(n,r){e._client.submitPayment(t,(function(t,i){t?r(e._transformResponse(t)):n(e._transformResponse(i))}))}))},t.prototype.initializeOffsitePayment=function(t,e){var n=this;return new Promise((function(){n._client.initializeOffsitePayment(t,null,e)}))},t.prototype._transformResponse=function(t){return{headers:t.headers,body:t.data,status:t.status,statusText:t.statusText}},t}();var Ti=n(36438);function xi(t,e){var n;return function(t){return void 0!==t.id}(t)?n=t.id:e&&e.length&&(n=e[0].id),{id:n,firstName:t.firstName,lastName:t.lastName,company:t.company,addressLine1:t.address1,addressLine2:t.address2,city:t.city,province:t.stateOrProvince,provinceCode:t.stateOrProvinceCode,postCode:t.postalCode,country:t.country,countryCode:t.countryCode,phone:t.phone,customFields:t.customFields}}const Ri=function(){function t(t){this._decimalPlaces=t}return t.prototype.toInteger=function(t){return Math.round(t*Math.pow(10,this._decimalPlaces))},t}();var ki,Mi=["per_item_discount","percentage_discount","per_total_discount","shipping_discount","free_shipping"];function Ni(t){return{code:t.code,discount:t.displayName,discountType:Mi.indexOf(t.couponType)}}function Di(t){return{code:t.code,discountedAmount:t.used,remainingBalance:t.remaining,giftCertificate:{balance:t.balance,code:t.code,purchaseDate:t.purchaseDate}}}function Li(t,e,n){return void 0===n&&(n="id"),Object.keys(t).reduce((function(r,i){return(0,o.__spreadArrays)(r,t[i].map((function(t){return"giftCertificates"===i?function(t,e){var n=new Ri(e);return{id:t.id,imageUrl:"",name:t.name,amount:t.amount,amountAfterDiscount:t.amount,discount:0,integerAmount:n.toInteger(t.amount),integerAmountAfterDiscount:n.toInteger(t.amount),integerUnitPrice:n.toInteger(t.amount),integerUnitPriceAfterDiscount:n.toInteger(t.amount),integerDiscount:0,quantity:1,sender:t.sender,recipient:t.recipient,type:"ItemGiftCertificateEntity",attributes:[],variantId:null}}(t,e):function(t,e,n,r){void 0===r&&(r="id");var i=new Ri(n);return{id:t[r],imageUrl:t.imageUrl,amount:t.extendedListPrice,amountAfterDiscount:t.extendedSalePrice,discount:t.discountAmount,integerAmount:i.toInteger(t.extendedListPrice),integerAmountAfterDiscount:i.toInteger(t.extendedSalePrice),integerDiscount:i.toInteger(t.discountAmount),integerUnitPrice:i.toInteger(t.listPrice),integerUnitPriceAfterDiscount:i.toInteger(t.salePrice),downloadsPageUrl:t.downloadPageUrl,name:t.name,quantity:t.quantity,brand:t.brand,sku:t.sku,categoryNames:t.categoryNames,variantId:t.variantId,productId:t.productId,attributes:(t.options||[]).map((function(t){return{name:t.name,value:t.value}})),addedByPromotion:t.addedByPromotion,type:e}}(t,function(t){switch(t){case"physicalItems":return"ItemPhysicalEntity";case"digitalItems":return"ItemDigitalEntity";case"giftCertificates":return"ItemGiftCertificateEntity";default:return""}}(i),e,n)})))}),[])}function zi(t){var e,n,r=t.cart.currency.decimalPlaces,i=new Ri(r);return{id:t.cart.id,items:Li(t.cart.lineItems,r),currency:t.cart.currency.code,coupon:{discountedAmount:(0,y.reduce)(t.cart.coupons,(function(t,e){return t+e.discountedAmount}),0),coupons:t.cart.coupons.map(Ni)},discount:{amount:t.cart.discountAmount,integerAmount:i.toInteger(t.cart.discountAmount)},discountNotifications:(e=t.promotions,n=[],(e||[]).forEach((function(t){(t.banners||[]).forEach((function(t){n.push({placeholders:[],discountType:null,message:"",messageHtml:t.text})}))})),n),giftCertificate:{totalDiscountedAmount:(0,y.reduce)(t.giftCertificates,(function(t,e){return t+e.used}),0),appliedGiftCertificates:(0,y.keyBy)(t.giftCertificates.map(Di),"code")},shipping:{amount:t.shippingCostTotal,integerAmount:i.toInteger(t.shippingCostTotal),amountBeforeDiscount:t.shippingCostBeforeDiscount,integerAmountBeforeDiscount:i.toInteger(t.shippingCostBeforeDiscount),required:(0,y.some)(t.cart.lineItems.physicalItems,(function(t){return t.isShippingRequired}))},subtotal:{amount:t.subtotal,integerAmount:i.toInteger(t.subtotal)},storeCredit:{amount:t.customer?t.customer.storeCredit:0},taxSubtotal:{amount:t.taxTotal,integerAmount:i.toInteger(t.taxTotal)},taxes:t.taxes,taxTotal:{amount:t.taxTotal,integerAmount:i.toInteger(t.taxTotal)},handling:{amount:t.handlingCostTotal,integerAmount:i.toInteger(t.handlingCostTotal)},grandTotal:{amount:t.grandTotal,integerAmount:i.toInteger(t.grandTotal)}}}!function(t){t.APPLEPAY="applepay",t.AMAZON_PAY_V2="amazonpay",t.BRAINTREE_PAYPAL="braintreepaypal",t.BRAINTREE_VENMO="braintreevenmo",t.BRAINTREE_PAYPAL_CREDIT="braintreepaypalcredit",t.GOOGLEPAY_ADYENV2="googlepayadyenv2",t.GOOGLEPAY_ADYENV3="googlepayadyenv3",t.GOOGLEPAY_AUTHORIZENET="googlepayauthorizenet",t.GOOGLEPAY_BNZ="googlepaybnz",t.GOOGLEPAY_BRAINTREE="googlepaybraintree",t.GOOGLEPAY_CHECKOUTCOM="googlepaycheckoutcom",t.GOOGLEPAY_CYBERSOURCEV2="googlepaycybersourcev2",t.GOOGLEPAY_ORBITAL="googlepayorbital",t.GOOGLEPAY_STRIPE="googlepaystripe",t.GOOGLEPAY_STRIPEUPE="googlepaystripeupe",t.GOOGLEPAY_WORLDPAYACCESS="googlepayworldpayaccess",t.MASTERPASS="masterpass",t.PAYPALEXPRESS="paypalexpress"}(ki||(ki={}));const ji=ki;function Ui(t,e){var n=t.firstName||e.firstName||"",r=t.lastName||e.lastName||"";return{addresses:(t.addresses||[]).map((function(t){return xi(t)})),customerId:t.id,isGuest:t.isGuest,storeCredit:t.storeCredit,email:t.email||e.email||"",firstName:n,lastName:r,name:t.fullName||[n,r].join(" "),customerGroupName:t.customerGroup&&t.customerGroup.name}}const Fi=function(){function t(){}return t.prototype.format=function(t){var e=t.split(new RegExp("\\s*/\\s*")),n=e[0],r=void 0===n?"":n,i=e[1],o=void 0===i?"":i,a=r.slice(0,2),u=4===o.length?o.slice(-2):o?o.slice(0,2):r.slice(2);return t.length<2?r:t.length>3&&!u?a:a+" / "+u},t.prototype.toObject=function(t){var e=t.split(new RegExp("\\s*/\\s*")),n=e[0],r=void 0===n?"":n,i=e[1],o=void 0===i?"":i;return/^\d+$/.test(r)&&/^\d+$/.test(o)?{month:1===r.length?"0"+r:r.slice(0,2),year:2===o.length?"20"+o:o.slice(0,4)}:{month:"",year:""}},t}();var qi=n(67061);const Bi=function(){function t(){}return t.prototype.format=function(t){var e=(0,qi.number)(t).card;if(!e)return t;var n=(0,y.max)((0,qi.creditCardType)(t).map((function(t){return(0,y.max)(t.lengths)}))),r=this.unformat(t).slice(0,n);return e.gaps.filter((function(t){return r.length>t})).reduce((function(t,e,n){return[t.slice(0,e+n),t.slice(e+n)].join(" ")}),r)},t.prototype.unformat=function(t){return(0,qi.number)(t).card?t.replace(new RegExp(" ","g"),""):t},t}();function Gi(t,e){void 0===e&&(e={});var n,r,i=t.currency.decimalPlaces,o=new Ri(i);return{id:t.orderId,items:Li(t.lineItems,t.currency.decimalPlaces,"productId"),orderId:t.orderId,currency:t.currency.code,customerCanBeCreated:t.customerCanBeCreated,payment:Yi(t.payments,e.payment),subtotal:{amount:t.baseAmount,integerAmount:o.toInteger(t.baseAmount)},coupon:{discountedAmount:(0,y.reduce)(t.coupons,(function(t,e){return t+e.discountedAmount}),0),coupons:t.coupons.map(Ni)},discount:{amount:t.discountAmount,integerAmount:o.toInteger(t.discountAmount)},token:e.orderToken,callbackUrl:e.callbackUrl,discountNotifications:[],giftCertificate:(n=t.payments,r=(0,y.filter)(n,{providerId:"giftcertificate"}),{totalDiscountedAmount:(0,y.reduce)(r,(function(t,e){return e.amount+t}),0),appliedGiftCertificates:(0,y.keyBy)(r.map((function(t){return{code:t.detail.code,discountedAmount:t.amount,remainingBalance:t.detail.remaining,giftCertificate:{balance:t.amount+t.detail.remaining,code:t.detail.code,purchaseDate:""}}})),"code")}),socialData:Wi(t),status:t.status,hasDigitalItems:t.hasDigitalItems,isDownloadable:t.isDownloadable,isComplete:t.isComplete,shipping:{amount:t.shippingCostTotal,integerAmount:o.toInteger(t.shippingCostTotal),amountBeforeDiscount:t.shippingCostBeforeDiscount,integerAmountBeforeDiscount:o.toInteger(t.shippingCostBeforeDiscount)},storeCredit:{amount:Vi(t.payments)},taxes:t.taxes,taxTotal:{amount:t.taxTotal,integerAmount:o.toInteger(t.taxTotal)},handling:{amount:t.handlingCostTotal,integerAmount:o.toInteger(t.handlingCostTotal)},grandTotal:{amount:t.orderAmount,integerAmount:t.orderAmountAsInteger}}}function Vi(t){var e=(0,y.find)(t,{providerId:"storecredit"});return e?e.amount:0}function Yi(t,e){void 0===e&&(e={});var n,r=(0,y.find)(t,Hi);return r?{id:r.providerId,status:(n=r.detail.step,"PAYMENT_STATUS_"+n),helpText:r.detail.instructions,returnUrl:e.returnUrl}:{}}function Hi(t){return"giftcertificate"!==t.providerId&&"storecredit"!==t.providerId}function Wi(t){var e={};return(0,o.__spreadArrays)(t.lineItems.physicalItems,t.lineItems.digitalItems).forEach((function(t){var n;e[t.id]=(n=t,["fb","tw","gp"].reduce((function(t,e){var r=n.socialMedia&&(0,y.find)(n.socialMedia,(function(t){return t.code===e}));return r?(t[e]={name:n.name,description:n.name,image:n.imageUrl,url:r.link,shareText:r.text,sharingLink:r.link,channelName:r.channel,channelCode:r.code},t):t}),{}))})),e}function Ki(t,e){return{description:t.description,module:t.type,price:t.cost,id:t.id,selected:e,isRecommended:t.isRecommended,imageUrl:t.imageUrl,transitTime:t.transitTime}}n(88720);const Zi=function(){function t(){this._cardExpiryFormatter=new Fi,this._cardNumberFormatter=new Bi}return t.prototype.transform=function(t,e){var n,r=e.billingAddress.getBillingAddress(),i=e.checkout.getCheckout(),a=e.customer.getCustomer(),u=e.order.getOrder(),s=e.paymentMethods.getPaymentMethod(t.methodId,t.gatewayId),c=this._mapShippingAddress(e,s),d=e.consignments.getConsignments(),l=e.consignments.getShippingOption(),f=e.config.getStoreConfig(),p=e.config.getContextConfig(),h=e.instruments.getInstrumentsMeta(),m=e.paymentMethods.getPaymentMethodsMeta(),v=e.order.getOrderMeta(),g=a&&r&&Ui(a,r),_=h&&t.paymentData&&(_i(t.paymentData)||(n=t.paymentData.formattedPayload)&&("string"==typeof n.bigpay_token||Boolean(n.bigpay_token&&n.bigpay_token.token)))?e.payment.getPaymentToken()+", "+h.vaultAccessToken:e.payment.getPaymentToken();if(!_)throw new kn(xn.MissingPaymentToken);return{additionalAction:t.additionalAction,authToken:_,customer:g,billingAddress:r&&xi(r),shippingAddress:c&&xi(c,d),shippingOption:l&&Ki(l,!0),cart:i&&zi(i),order:u&&Gi(u,v),orderMeta:v,payment:t.paymentData,paymentMethod:s&&this._transformPaymentMethod(s),quoteMeta:{request:(0,o.__assign)((0,o.__assign)({},m),{geoCountryCode:p&&p.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:(0,y.pick)(f&&f.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}},t.prototype.transformWithHostedFormData=function(t,e,n){var r=e.additionalAction,i=e.authToken,a=e.checkout,u=e.config,s=e.order,c=e.orderMeta,d=e.payment,l=void 0===d?{}:d,f=e.paymentMethod,p=e.paymentMethodMeta,h=a&&a.consignments[0],m=h&&h.shippingAddress,v=h&&h.selectedShippingOption;return{additionalAction:r,authToken:i,paymentMethod:f&&this._transformPaymentMethod(f),customer:s&&s.billingAddress&&a&&Ui(a.customer,s.billingAddress),billingAddress:s&&s.billingAddress&&xi(s.billingAddress),shippingAddress:m&&a&&xi(m,a.consignments),shippingOption:v&&Ki(v,!0),cart:a&&zi(a),order:s&&Gi(s,c),orderMeta:c,payment:this._transformHostedInputValues(t,l,n),quoteMeta:{request:(0,o.__assign)((0,o.__assign)({},p),{geoCountryCode:u&&u.context.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:u&&(0,y.pick)(u.storeConfig.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}},t.prototype._transformPaymentMethod=function(t){return"multi-option"!==t.method||t.gateway?t.initializationData&&t.initializationData.gateway?(0,o.__assign)((0,o.__assign)({},t),{id:t.initializationData.gateway}):t.id===ji.BRAINTREE_VENMO?(0,o.__assign)((0,o.__assign)({},t),{id:ji.BRAINTREE_PAYPAL}):t:(0,o.__assign)((0,o.__assign)({},t),{gateway:t.id})},t.prototype._transformHostedInputValues=function(t,e,n){return"instrumentId"in e?(0,o.__assign)((0,o.__assign)({},e),{ccCvv:t.cardCodeVerification,ccNumber:t.cardNumberVerification&&this._cardNumberFormatter.unformat(t.cardNumberVerification),hostedFormNonce:n}):(0,o.__assign)((0,o.__assign)({},e),{ccCvv:t.cardCode,ccExpiry:this._cardExpiryFormatter.toObject(t.cardExpiry||""),ccName:t.cardName||"",ccNumber:this._cardNumberFormatter.unformat(t.cardNumber||""),hostedFormNonce:n})},t.prototype._mapShippingAddress=function(t,e){var n,r,i,o;if(e){var a=null===(r=null===(n=e.initializationData)||void 0===n?void 0:n.bopis)||void 0===r?void 0:r.enabled,u=null===(o=null===(i=e.initializationData)||void 0===i?void 0:i.bopis)||void 0===o?void 0:o.requiredAddress,s=t.consignments.getConsignments(),c=null==s?void 0:s.every((function(t){return t.selectedPickupOption}));if(a&&c&&"none"===u)return}return t.shippingAddress.getShippingAddress()},t}();var $i;function Ji(t){return Ji="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ji(t)}!function(t){t.AvailableShippingOptions="consignments.availableShippingOptions",t.PhysicalItemsCategoryNames="cart.lineItems.physicalItems.categoryNames",t.DigitalItemsCategoryNames="cart.lineItems.digitalItems.categoryNames"}($i||($i={}));const Qi=function(){function t(t,e){this._consignmentRequestSender=t,this._checkoutRequestSender=e}return t.prototype.unassignItemsByAddress=function(t,e){var n=this;return function(r){var i=r.getState();if(!i.checkout.getCheckout())throw new kn(xn.MissingCheckout);var o=n._consignmentHasAddress(t)?t.address:t.shippingAddress,a=i.consignments.getConsignmentByAddress(o);if(!a)throw new Yr("No consignment found for the specified address");var u=n._removeLineItems(t.lineItems,a,i.cart.getCart());return u.length?n.updateConsignment({id:a.id,address:o,lineItems:u},e)(r):n.deleteConsignment(a.id,e)(r)}},t.prototype.assignItemsByAddress=function(t,e){var n=this;return function(r){var i=r.getState(),o=n._consignmentHasAddress(t)?t.address:t.shippingAddress,a=i.consignments.getConsignmentByAddress(o);return n._createOrUpdateConsignment({id:a&&a.id,address:o,lineItems:n._addLineItems(t.lineItems,a,i.cart.getCart())},e)(r)}},t.prototype.selectShippingOption=function(t,e){var n=this;return function(r){return Jn.y.create((function(i){var o=r.getState(),u=o.checkout.getCheckout(),s=o.consignments.getConsignments();if(!u)throw new kn(xn.MissingCheckout);if(!s||!s.length)throw new kn(xn.MissingConsignments);var c={id:s[0].id,shippingOptionId:t},d={id:s[0].id};i.next((0,a.PH)(Y.UpdateShippingOptionRequested,void 0,d)),n._consignmentRequestSender.updateConsignment(u.id,c,e).then((function(t){var e=t.body;i.next((0,a.PH)(Y.UpdateShippingOptionSucceeded,e,d)),i.complete()})).catch((function(t){i.error((0,a.bR)(Y.UpdateShippingOptionFailed,t,d))}))}))}},t.prototype.loadShippingOptions=function(t){var e=this;return function(n){return Jn.y.create((function(r){var i=n.getState().checkout.getCheckout();if(!i)throw new kn(xn.MissingCheckout);r.next((0,a.PH)(Y.LoadShippingOptionsRequested)),e._checkoutRequestSender.loadCheckout(i.id,(0,o.__assign)((0,o.__assign)({},t),{params:{include:[$i.AvailableShippingOptions]}})).then((function(t){var e=t.body;r.next((0,a.PH)(Y.LoadShippingOptionsSucceeded,e)),r.complete()})).catch((function(t){r.error((0,a.bR)(Y.LoadShippingOptionsFailed,t))}))}))}},t.prototype.updateAddress=function(t,e){var n=this;return function(r){var i=n._getUpdateAddressRequestBody(t,r),o=r.getState().consignments.getConsignments();return o&&o.length&&(i.id=o[0].id),n._createOrUpdateConsignment(i,e)(r)}},t.prototype.createConsignments=function(t,e){var n=this;return function(r){return Jn.y.create((function(i){var o=r.getState().checkout.getCheckout();if(!o||!o.id)throw new kn(xn.MissingCheckout);i.next((0,a.PH)(Y.CreateConsignmentsRequested)),n._consignmentRequestSender.createConsignments(o.id,t,e).then((function(t){var e=t.body;i.next((0,a.PH)(Y.CreateConsignmentsSucceeded,e)),i.complete()})).catch((function(t){i.error((0,a.bR)(Y.CreateConsignmentsFailed,t))}))}))}},t.prototype.updateConsignment=function(t,e){var n=this;return function(r){return Jn.y.create((function(i){var o=r.getState().checkout.getCheckout();if(!o||!o.id)throw new kn(xn.MissingCheckout);var u={id:t.id};i.next((0,a.PH)(Y.UpdateConsignmentRequested,void 0,u)),n._consignmentRequestSender.updateConsignment(o.id,t,e).then((function(t){var e=t.body;i.next((0,a.PH)(Y.UpdateConsignmentSucceeded,e,u)),i.complete()})).catch((function(t){i.error((0,a.bR)(Y.UpdateConsignmentFailed,t,u))}))}))}},t.prototype.deleteConsignment=function(t,e){var n=this;return function(r){return Jn.y.create((function(i){var o=r.getState().checkout.getCheckout(),u={id:t};if(!o||!o.id)throw new kn(xn.MissingCheckout);i.next((0,a.PH)(Y.DeleteConsignmentRequested,void 0,u)),n._consignmentRequestSender.deleteConsignment(o.id,t,e).then((function(t){var e=t.body;i.next((0,a.PH)(Y.DeleteConsignmentSucceeded,e,u)),i.complete()})).catch((function(t){i.error((0,a.bR)(Y.DeleteConsignmentFailed,t,u))}))}))}},t.prototype.updateShippingOption=function(t,e){var n=this;return function(r){return Jn.y.create((function(i){var o=r.getState().checkout.getCheckout();if(!o||!o.id)throw new kn(xn.MissingCheckout);var u={id:t.id};i.next((0,a.PH)(Y.UpdateShippingOptionRequested,void 0,u)),n._consignmentRequestSender.updateConsignment(o.id,t,e).then((function(t){var e=t.body;i.next((0,a.PH)(Y.UpdateShippingOptionSucceeded,e,u)),i.complete()})).catch((function(t){i.error((0,a.bR)(Y.UpdateShippingOptionFailed,t,u))}))}))}},t.prototype._createOrUpdateConsignment=function(t,e){var n=this;return function(r){var i=r.getState().checkout.getCheckout();if(!i||!i.id)throw new kn(xn.MissingCheckout);return n._isUpdateConsignmentRequest(t)?n.updateConsignment(t,e)(r):n.createConsignments([t],e)(r)}},t.prototype._getUpdateAddressRequestBody=function(t,e){var n=e.getState().cart.getCart();if(!n)throw new kn(xn.MissingCart);var r=n.lineItems,i=r.physicalItems,a=r.customItems,u=void 0===a?[]:a;return{address:t,lineItems:(0,o.__spreadArrays)(i,u).map((function(t){return{itemId:t.id,quantity:t.quantity}}))}},t.prototype._removeLineItems=function(t,e,n){if(!n)throw new kn(xn.MissingCart);return this._hydrateLineItems(e.lineItemIds,n).map((function(e){var n=(0,y.find)(t,(function(t){return t.itemId===e.itemId}));return(0,o.__assign)((0,o.__assign)({},e),{quantity:n?e.quantity-n.quantity:e.quantity})})).filter((function(t){return t.quantity>0}))},t.prototype._addLineItems=function(t,e,n){if(!e)return t;if(!n)throw new kn(xn.MissingCart);return t.concat(this._hydrateLineItems(e.lineItemIds,n)).filter((function(t){return t.quantity>0}))},t.prototype._hydrateLineItems=function(t,e){return t.map((function(t){var n=(0,y.find)(e.lineItems.physicalItems,(function(e){return e.id===t}));return{itemId:t,quantity:n?n.quantity:0}}))},t.prototype._isUpdateConsignmentRequest=function(t){return!!t.id},t.prototype._consignmentHasAddress=function(t){return"object"===Ji(t)&&"address"in t},t}();var Xi=["consignments.availableShippingOptions","cart.lineItems.physicalItems.options","cart.lineItems.digitalItems.options","customer","promotions.banners"];const to=function(){function t(t){this._requestSender=t}return t.prototype.createConsignments=function(t,e,n){var r=void 0===n?{}:n,i=r.timeout,a=r.params,u=(void 0===a?{}:a).include,s="/api/storefront/checkouts/"+t+"/consignments",c=(0,o.__assign)({Accept:nr.JsonV1},ir);return this._requestSender.post(s,{body:e,params:{include:Sr(Xi,u)},headers:c,timeout:i})},t.prototype.updateConsignment=function(t,e,n){var r=void 0===n?{}:n,i=r.timeout,a=r.params,u=(void 0===a?{}:a).include,s=e.id,c=(0,o.__rest)(e,["id"]),d="/api/storefront/checkouts/"+t+"/consignments/"+s,l=(0,o.__assign)({Accept:nr.JsonV1},ir);return this._requestSender.put(d,{body:c,params:{include:Sr(Xi,u)},headers:l,timeout:i})},t.prototype.deleteConsignment=function(t,e,n){var r=(void 0===n?{}:n).timeout,i="/api/storefront/checkouts/"+t+"/consignments/"+e,a=(0,o.__assign)({Accept:nr.JsonV1},ir),u=br(Xi);return this._requestSender.delete(i,{params:{include:u},headers:a,timeout:r})},t}(),eo=function(){function t(t,e){this._googleRecaptcha=t,this._requestSender=e}return t.prototype.initialize=function(t){var e=this;return function(n){return(0,sr.z)((0,cr.of)((0,a.PH)(bn.InitializeRequested,void 0)),(0,dr.P)((function(){return(0,o.__awaiter)(e,void 0,void 0,(function(){var e,r,i,u,s;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:return e=t?t.containerId:"spamProtectionContainer",t||document.getElementById(e)||((r=document.createElement("div")).setAttribute("id",e),document.body.appendChild(r)),i=n.getState(),u=i.config.getStoreConfigOrThrow(),s=u.checkoutSettings.googleRecaptchaSitekey,[4,this._googleRecaptcha.load(e,s)];case 1:return o.sent(),[2,(0,a.PH)(bn.InitializeSucceeded)]}}))}))}))).pipe((0,A.K)((function(t){return pr(bn.InitializeFailed,t)})))}},t.prototype.verifyCheckoutSpamProtection=function(){var t=this;return function(e){return(0,dr.P)((function(){var n=e.getState().checkout.getCheckout();if(!n)throw new kn(xn.MissingCheckout);return(0,sr.z)((0,cr.of)((0,a.PH)(bn.VerifyCheckoutRequested)),(0,P.D)(t.execute()(e)).pipe((0,xr.w)((function(e){return kr(e)&&e.payload?(0,P.D)(t._requestSender.validate(n.id,e.payload.token)).pipe((0,xr.w)((function(t){var n=t.body;return(0,sr.z)((0,cr.of)(e),(0,cr.of)((0,a.PH)(bn.VerifyCheckoutSucceeded,n)))}))):(0,cr.of)(e)})))).pipe((0,A.K)((function(t){return pr(bn.VerifyCheckoutFailed,t)})))}))}},t.prototype.execute=function(){var t=this;return function(e){return(0,sr.z)((0,cr.of)((0,a.PH)(bn.ExecuteRequested)),t.initialize()(e),t._googleRecaptcha.execute().pipe((0,Vr.q)(1)).pipe((0,xr.w)((function(e){var n=e.error,r=e.token;return(0,o.__awaiter)(t,void 0,void 0,(function(){return(0,o.__generator)(this,(function(t){if(n instanceof Qr)throw n;if(n||!r)throw new ui;return[2,(0,a.PH)(bn.ExecuteSucceeded,{token:r})]}))}))})))).pipe((0,A.K)((function(t){return pr(bn.ExecuteFailed,t)})))}},t}(),no=function(){function t(t){this._requestSender=t}return t.prototype.validate=function(t,e,n){var r=(void 0===n?{}:n).timeout,i="/api/storefront/checkouts/"+t+"/spam-protection",a=(0,o.__assign)({Accept:nr.JsonV1},ir);return this._requestSender.post(i,{body:{token:e},headers:a,timeout:r})},t}(),ro=function(){function t(t){this._storeCreditRequestSender=t}return t.prototype.applyStoreCredit=function(t,e){var n=this;return function(r){return(0,sr.z)((0,cr.of)((0,a.PH)(dn.ApplyStoreCreditRequested)),(0,dr.P)((function(){return(0,o.__awaiter)(n,void 0,void 0,(function(){var n,i,u;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(n=r.getState(),!(i=n.checkout.getCheckout()))throw new kn(xn.MissingCheckout);return[4,t?this._storeCreditRequestSender.applyStoreCredit(i.id,e):this._storeCreditRequestSender.removeStoreCredit(i.id,e)];case 1:return u=o.sent().body,[2,(0,a.PH)(dn.ApplyStoreCreditSucceeded,u)]}}))}))}))).pipe((0,A.K)((function(t){return pr(dn.ApplyStoreCreditFailed,t)})))}},t}(),io=function(){function t(t){this._requestSender=t}return t.prototype.applyStoreCredit=function(t,e){var n=(void 0===e?{}:e).timeout,r="/api/storefront/checkouts/"+t+"/store-credit",i=(0,o.__assign)({Accept:nr.JsonV1},ir);return this._requestSender.post(r,{headers:i,timeout:n,params:{include:br(wr)}})},t.prototype.removeStoreCredit=function(t,e){var n=(void 0===e?{}:e).timeout,r="/api/storefront/checkouts/"+t+"/store-credit",i=(0,o.__assign)({Accept:nr.JsonV1},ir);return this._requestSender.delete(r,{headers:i,timeout:n,params:{include:br(wr)}})},t}(),oo=function(t){function e(e){var n=t.call(this,e)||this;return n.name="UpdateSubscriptionsError",n.type="update_subscriptions",n}return(0,o.__extends)(e,t),e}(p),ao=function(){function t(t){this._subscriptionsRequestSender=t}return t.prototype.updateSubscriptions=function(t,e){var n=this;return(0,sr.z)((0,cr.of)((0,a.PH)(E.UpdateSubscriptionsRequested)),(0,dr.P)((function(){return(0,o.__awaiter)(n,void 0,void 0,(function(){var n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._subscriptionsRequestSender.updateSubscriptions(t,e)];case 1:return n=r.sent().body,[2,(0,a.PH)(E.UpdateSubscriptionsSucceeded,n)]}}))}))}))).pipe((0,A.K)((function(t){return pr(E.UpdateSubscriptionsFailed,new oo(t))})))},t}(),uo=function(){function t(t){this._requestSender=t}return t.prototype.updateSubscriptions=function(t,e){var n=(void 0===e?{}:e).timeout,r=(0,o.__assign)({Accept:nr.JsonV1},ir);return this._requestSender.post("/api/storefront/subscriptions",{body:t,headers:r,timeout:n})},t}();function so(t){return so="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},so(t)}var co=(0,y.memoize)((function(t){return Array.isArray(t)?t.map((function(t){return lo(t)})):F(t)?Object.keys(t).reduce((function(e,n){var r;return(0,o.__assign)((0,o.__assign)({},e),((r={})[n]=lo(t[n]),r))}),{}):t}));co.cache=new WeakMap;var lo=function(t){return"object"===so(t)&&null!==t?co(t):t};function fo(t){return function(){for(var e=[],n=0;n55?55:t<25?25:t}function Pa(t){var e=t.billingAddress,n=t.email,r=t.firstName,i=t.lastName,o=t.phone,a=t.shippingAddress,u=e||a;return{email:n,first_name:r,last_name:i,phone_number:o,address_line_1:null==u?void 0:u.line1,address_line_2:null==u?void 0:u.line2,city:null==u?void 0:u.city,state:null==u?void 0:u.state,country_code:null==u?void 0:u.countryCode,postal_code:null==u?void 0:u.postalCode}}function Aa(t){var e=t.email,n=t.phone,r=t.shippingAddress,i=((null==r?void 0:r.recipientName)||"").split(" ");return{email:e,first_name:i[0]||"",last_name:i[1]||"",phone_number:n,address_line_1:null==r?void 0:r.line1,address_line_2:null==r?void 0:r.line2,city:null==r?void 0:r.city,state:null==r?void 0:r.state,country_code:null==r?void 0:r.countryCode,postal_code:null==r?void 0:r.postalCode}}const Oa=function(){function t(t,e,n,r,i,o){this._store=t,this._checkoutActionCreator=e,this._cartRequestSender=n,this._braintreeSDKCreator=r,this._formPoster=i,this._window=o}return t.prototype.initialize=function(t){var e,n;return(0,o.__awaiter)(this,void 0,void 0,(function(){var r,i,a,u,s,c,d,l,f,p,h,y,m=this;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(r=t.braintreepaypal,i=t.containerId,a=t.methodId,s=(u=r||{}).messagingContainerId,c=u.onError,!a)throw new Yr('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new Yr('Unable to initialize payment because "options.containerId" argument is not provided.');if(!r)throw new Yr('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');if(!r.buyNowInitializeOptions)return[3,1];if(d=this._store.getState(),l=d.paymentMethods.getPaymentMethodOrThrow(a),!r.currencyCode)throw new Yr('Unable to initialize payment because "options.braintreepaypal.currencyCode" argument is not provided.');return f=r.currencyCode,[3,3];case 1:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 2:d=o.sent(),l=d.paymentMethods.getPaymentMethodOrThrow(a),f=d.cart.getCartOrThrow().currency.code,o.label=3;case 3:if(!l.clientToken)throw new kn(xn.MissingPaymentMethod);return p={currency:f,intent:null===(e=l.initializationData)||void 0===e?void 0:e.intent,isCreditEnabled:null===(n=l.initializationData)||void 0===n?void 0:n.isCreditEnabled},h=function(t){m._renderPayPalComponents(t,r,i,a,Boolean(l.config.testMode))},y=function(t){return m._handleError(t,i,s,c)},this._braintreeSDKCreator.initialize(l.clientToken),[4,this._braintreeSDKCreator.getPaypalCheckout(p,h,y)];case 4:return o.sent(),[2]}}))}))},t.prototype.deinitialize=function(){return this._braintreeSDKCreator.teardown(),Promise.resolve()},t.prototype._renderPayPalComponents=function(t,e,n,r,i){var o=e.messagingContainerId;this._renderPayPalMessages(o),this._renderPayPalButton(t,e,n,r,i)},t.prototype._renderPayPalButton=function(t,e,n,r,i){var o=this,a=e.style,u=e.shouldProcessPayment,s=e.onAuthorizeError,c=this._window.paypal,d=null==c?void 0:c.FUNDING.PAYPAL;if(c&&d){var l=a?Ea(a):{},f=c.Buttons({env:i?"sandbox":"production",commit:!1,fundingSource:d,style:l,createOrder:function(){return o._setupPayment(t,e,r)},onApprove:function(e){return o._tokenizePayment(e,t,r,u,s)}});f.isEligible()&&f.render("#"+n)}else this._removeElement(n)},t.prototype._renderPayPalMessages=function(t){var e=t&&Boolean(document.getElementById(t)),n=this._window.paypal;if(n&&e){var r=this._store.getState().cart.getCartOrThrow();n.Messages({amount:r.cartAmount,placement:"cart"}).render("#"+t)}else this._removeElement(t)},t.prototype._setupPayment=function(t,e,n){var r,i;return(0,o.__awaiter)(this,void 0,void 0,(function(){var a,u,s,c,d,l,f,p,h,y,m,v;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:a=e.buyNowInitializeOptions,u=e.shippingAddress,s=e.onPaymentError,o.label=1;case 1:return o.trys.push([1,7,,8]),d=this,[4,this._createBuyNowCart({buyNowInitializeOptions:a})];case 2:return d._buyNowCart=o.sent(),this._buyNowCart?(c=this._store.getState(),[3,5]):[3,3];case 3:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 4:c=o.sent(),o.label=5;case 5:return l=c.customer.getCustomer(),f=c.paymentMethods.getPaymentMethodOrThrow(n),p=this._buyNowCart?this._buyNowCart.cartAmount:c.checkout.getCheckoutOrThrow().outstandingBalance,h=null!==(r=e.currencyCode)&&void 0!==r?r:c.config.getStoreConfigOrThrow().currency.code,y=u||(null==l?void 0:l.addresses[0]),m=y?Ca(y):void 0,[4,t.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:m,amount:p,currency:h,offerCredit:!1,intent:null===(i=f.initializationData)||void 0===i?void 0:i.intent})];case 6:return[2,o.sent()];case 7:throw v=o.sent(),s&&s(v),v;case 8:return[2]}}))}))},t.prototype._createBuyNowCart=function(t){var e=t.buyNowInitializeOptions;return(0,o.__awaiter)(this,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if("function"!=typeof(null==e?void 0:e.getBuyNowCartRequestBody))return[3,4];if(!(t=e.getBuyNowCartRequestBody()))throw new kn(xn.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._cartRequestSender.createBuyNowCart(t)];case 2:return[2,n.sent().body];case 3:throw n.sent(),new ga;case 4:return[2]}}))}))},t.prototype._tokenizePayment=function(t,e,n,r,i){var a;return(0,o.__awaiter)(this,void 0,void 0,(function(){var u,s,c,d,l,f;return(0,o.__generator)(this,(function(p){switch(p.label){case 0:return p.trys.push([0,3,,4]),[4,this._braintreeSDKCreator.getDataCollector({paypal:!0})];case 1:return u=p.sent().deviceData,[4,e.tokenizePayment(t)];case 2:return s=p.sent(),c=s.details,d=s.nonce,l=null===(a=this._buyNowCart)||void 0===a?void 0:a.id,this._formPoster.postForm("/checkout.php",(0,o.__assign)({payment_type:"paypal",provider:n,action:r?"process_payment":"set_external_checkout",nonce:d,device_data:u,billing_address:JSON.stringify(Pa(c)),shipping_address:JSON.stringify(Aa(c))},l&&{cart_id:l})),[2,s];case 3:throw f=p.sent(),i&&i(f),f;case 4:return[2]}}))}))},t.prototype._handleError=function(t,e,n,r){this._removeElement(e),this._removeElement(n),r&&r(t)},t.prototype._removeElement=function(t){var e=t&&document.getElementById(t);e&&e.remove()},t}();var Ta,xa,Ra,ka,Ma;!function(t){t.HORIZONTAL="horizontal",t.VERTICAL="vertical"}(Ta||(Ta={})),function(t){t.SMALL="small",t.MEDIUM="medium",t.LARGE="large",t.RESPONSIVE="responsive"}(xa||(xa={})),function(t){t.GOLD="gold",t.BLUE="blue",t.SIlVER="silver",t.BLACK="black"}(Ra||(Ra={})),function(t){t.CHECKOUT="checkout",t.PAY="pay",t.BUYNOW="buynow",t.PAYPAL="paypal",t.CREDIT="credit"}(ka||(ka={})),function(t){t.PILL="pill",t.RECT="rect"}(Ma||(Ma={}));const Na=function(){function t(t,e,n,r,i,o){this._store=t,this._checkoutActionCreator=e,this._cartRequestSender=n,this._braintreeSDKCreator=r,this._formPoster=i,this._window=o}return t.prototype.initialize=function(t){var e,n;return(0,o.__awaiter)(this,void 0,void 0,(function(){var r,i,a,u,s,c,d,l,f,p=this;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(r=t.braintreepaypalcredit,i=t.containerId,!(a=t.methodId))throw new Yr('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new Yr('Unable to initialize payment because "options.containerId" argument is not provided.');if(!r)throw new Yr('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');if(!r.buyNowInitializeOptions)return[3,1];if(u=this._store.getState(),s=u.paymentMethods.getPaymentMethodOrThrow(a),!r.currencyCode)throw new Yr('Unable to initialize payment because "options.braintreepaypalcredit.currencyCode" argument is not provided.');return c=r.currencyCode,[3,3];case 1:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 2:u=o.sent(),s=u.paymentMethods.getPaymentMethodOrThrow(a),c=u.cart.getCartOrThrow().currency.code,o.label=3;case 3:if(!s.clientToken)throw new kn(xn.MissingPaymentMethod);return d={currency:c,intent:null===(e=s.initializationData)||void 0===e?void 0:e.intent,isCreditEnabled:null===(n=s.initializationData)||void 0===n?void 0:n.isCreditEnabled},l=function(t){return p._renderPayPalButton(t,r,i,a,Boolean(s.config.testMode))},f=function(t){return p._handleError(t,i,r.onError)},this._braintreeSDKCreator.initialize(s.clientToken),[4,this._braintreeSDKCreator.getPaypalCheckout(d,l,f)];case 4:return o.sent(),[2]}}))}))},t.prototype.deinitialize=function(){return this._braintreeSDKCreator.teardown(),Promise.resolve()},t.prototype._renderPayPalButton=function(t,e,n,r,i){var a=this,u=e.style,s=e.shouldProcessPayment,c=e.onAuthorizeError,d=this._window.paypal,l=!1;if(d){var f=[d.FUNDING.PAYLATER,d.FUNDING.CREDIT],p=u?Ea(u):{};f.forEach((function(u){var f=u===d.FUNDING.CREDIT?(0,o.__assign)({label:ka.CREDIT},p):p;if(!l){var h=d.Buttons({env:i?"sandbox":"production",commit:!1,fundingSource:u,style:f,createOrder:function(){return a._setupPayment(t,e,r)},onApprove:function(e){return a._tokenizePayment(e,t,r,s,c)}});h.isEligible()&&(h.render("#"+n),l=!0)}}))}d&&l||this._removeElement(n)},t.prototype._setupPayment=function(t,e,n){var r,i;return(0,o.__awaiter)(this,void 0,void 0,(function(){var a,u,s,c,d,l,f,p,h,y,m,v;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:a=e.onPaymentError,u=e.shippingAddress,s=e.buyNowInitializeOptions,o.label=1;case 1:return o.trys.push([1,7,,8]),d=this,[4,this._createBuyNowCart({buyNowInitializeOptions:s})];case 2:return d._buyNowCart=o.sent(),this._buyNowCart?(c=this._store.getState(),[3,5]):[3,3];case 3:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 4:c=o.sent(),o.label=5;case 5:return l=c.customer.getCustomer(),f=c.paymentMethods.getPaymentMethodOrThrow(n),p=this._buyNowCart?this._buyNowCart.cartAmount:c.checkout.getCheckoutOrThrow().outstandingBalance,h=null!==(r=e.currencyCode)&&void 0!==r?r:c.config.getStoreConfigOrThrow().currency.code,y=u||(null==l?void 0:l.addresses[0]),m=y?Ca(y):void 0,[4,t.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:m,amount:p,currency:h,offerCredit:!0,intent:null===(i=f.initializationData)||void 0===i?void 0:i.intent})];case 6:return[2,o.sent()];case 7:throw v=o.sent(),a&&a(v),v;case 8:return[2]}}))}))},t.prototype._createBuyNowCart=function(t){var e=t.buyNowInitializeOptions;return(0,o.__awaiter)(this,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if("function"!=typeof(null==e?void 0:e.getBuyNowCartRequestBody))return[3,4];if(!(t=e.getBuyNowCartRequestBody()))throw new kn(xn.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._cartRequestSender.createBuyNowCart(t)];case 2:return[2,n.sent().body];case 3:throw n.sent(),new ga;case 4:return[2]}}))}))},t.prototype._tokenizePayment=function(t,e,n,r,i){var a;return(0,o.__awaiter)(this,void 0,void 0,(function(){var u,s,c,d,l,f;return(0,o.__generator)(this,(function(p){switch(p.label){case 0:return p.trys.push([0,3,,4]),[4,this._braintreeSDKCreator.getDataCollector({paypal:!0})];case 1:return u=p.sent().deviceData,[4,e.tokenizePayment(t)];case 2:return s=p.sent(),c=s.details,d=s.nonce,l=null===(a=this._buyNowCart)||void 0===a?void 0:a.id,this._formPoster.postForm("/checkout.php",(0,o.__assign)({payment_type:"paypal",provider:n,action:r?"process_payment":"set_external_checkout",nonce:d,device_data:u,billing_address:JSON.stringify(Pa(c)),shipping_address:JSON.stringify(Aa(c))},l&&{cart_id:l})),[2,s];case 3:throw f=p.sent(),i&&i(f),f;case 4:return[2]}}))}))},t.prototype._handleError=function(t,e,n){this._removeElement(e),n&&n(t)},t.prototype._removeElement=function(t){var e=t&&document.getElementById(t);e&&e.remove()},t}();var Da={backgroundColor:"#3D95CE",backgroundPosition:"50% 50%",backgroundSize:"80px auto",backgroundImage:'url("/app/assets/img/payment-providers/venmo-logo-white.svg")',backgroundRepeat:"no-repeat",borderRadius:"4px",cursor:"pointer",transition:"0.2s ease",minHeight:"40px",minWidth:"150px",height:"100%",width:"100%"};const La=function(){function t(t,e,n,r,i){this._store=t,this._paymentMethodActionCreator=e,this._cartRequestSender=n,this._braintreeSDKCreator=r,this._formPoster=i,this._onError=y.noop}return t.prototype.initialize=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n,r,i,a,u=this;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(e=t.braintreevenmo,n=t.containerId,!(r=t.methodId))throw new Yr('Unable to initialize payment because "options.methodId" argument is not provided.');return[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(r))];case 1:if(i=o.sent(),!(a=i.paymentMethods.getPaymentMethodOrThrow(r)).clientToken)throw new kn(xn.MissingPaymentMethod);if(!n)throw new Yr('Unable to initialize payment because "options.containerId" argument is not provided.');return this._onError=(null==e?void 0:e.onError)||this._handleError,this._braintreeSDKCreator.initialize(a.clientToken),[4,this._braintreeSDKCreator.getVenmoCheckout((function(t){return u._handleInitializationVenmoSuccess(t,n,null==e?void 0:e.buyNowInitializeOptions)}),(function(t){return u._handleInitializationVenmoError(t,n)}))];case 2:return o.sent(),[2]}}))}))},t.prototype.deinitialize=function(){return this._braintreeSDKCreator.teardown(),Promise.resolve()},t.prototype._handleError=function(t){throw new Error(t.message)},t.prototype._handleInitializationVenmoSuccess=function(t,e,n){return this._renderVenmoButton(t,e,n)},t.prototype._handleInitializationVenmoError=function(t,e){return this._removeVenmoContainer(e),this._onError(t)},t.prototype._removeVenmoContainer=function(t){var e=document.getElementById(t);e&&e.remove()},t.prototype._renderVenmoButton=function(t,e,n){var r=this,i=document.getElementById(e);if(!i)throw new Yr("Unable to create wallet button without valid container ID.");i.setAttribute("aria-label","Venmo"),Object.assign(i.style,Da),i.addEventListener("click",(function(){return(0,o.__awaiter)(r,void 0,void 0,(function(){var e,r=this;return(0,o.__generator)(this,(function(a){switch(a.label){case 0:return i.setAttribute("disabled","true"),[4,this._createBuyNowCart(n)];case 1:return e=a.sent(),t.tokenize&&t.tokenize((function(t,n){return(0,o.__awaiter)(r,void 0,void 0,(function(){return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return i.removeAttribute("disabled"),t?[2,this._onError(t)]:[4,this._handlePostForm(n,null==e?void 0:e.id)];case 1:return r.sent(),[2]}}))}))})),[2]}}))}))})),i.addEventListener("mouseenter",(function(){i.style.backgroundColor="#0a7fc2"})),i.addEventListener("mouseleave",(function(){i.style.backgroundColor=Da.backgroundColor}))},t.prototype._createBuyNowCart=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if("function"!=typeof(null==t?void 0:t.getBuyNowCartRequestBody))return[3,4];if(!(e=t.getBuyNowCartRequestBody()))throw new kn(xn.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._cartRequestSender.createBuyNowCart(e)];case 2:return[2,n.sent().body];case 3:throw n.sent(),new ga;case 4:return[2]}}))}))},t.prototype._handlePostForm=function(t,e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r,i;return(0,o.__generator)(this,(function(a){switch(a.label){case 0:return[4,this._braintreeSDKCreator.getDataCollector()];case 1:return n=a.sent().deviceData,r=t.nonce,i=t.details,this._formPoster.postForm("/checkout.php",(0,o.__assign)({nonce:r,provider:ji.BRAINTREE_VENMO,payment_type:"paypal",device_data:n,action:"set_external_checkout",billing_address:JSON.stringify(Pa(i)),shipping_address:JSON.stringify(Aa(i))},e&&{cart_id:e})),[2]}}))}))},t}();const za=function(t){function e(e){var n=t.call(this,e||"Invalid arguments have been provided.")||this;return n.name="InvalidArgumentError",n.type="invalid_argument",n}return(0,o.__extends)(e,t),e}(u);var ja;!function(t){t[t.CheckoutButtonNotInitialized=0]="CheckoutButtonNotInitialized",t[t.CustomerNotInitialized=1]="CustomerNotInitialized",t[t.PaymentNotInitialized=2]="PaymentNotInitialized",t[t.ShippingNotInitialized=3]="ShippingNotInitialized",t[t.SpamProtectionNotInitialized=4]="SpamProtectionNotInitialized"}(ja||(ja={}));const Ua=function(t){function e(e){var n=t.call(this,function(t){switch(t){case ja.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case ja.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case ja.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case ja.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;return n.subtype=e,n.name="NotInitializedError",n.type="not_initialized",n}return(0,o.__extends)(e,t),e}(u);var Fa;!function(t){t[t.MissingBillingAddress=0]="MissingBillingAddress",t[t.MissingCart=1]="MissingCart",t[t.MissingCheckout=2]="MissingCheckout",t[t.MissingConsignments=3]="MissingConsignments",t[t.MissingCustomer=4]="MissingCustomer",t[t.MissingCheckoutConfig=5]="MissingCheckoutConfig",t[t.MissingOrder=6]="MissingOrder",t[t.MissingOrderConfig=7]="MissingOrderConfig",t[t.MissingOrderId=8]="MissingOrderId",t[t.MissingPayment=9]="MissingPayment",t[t.MissingPaymentId=10]="MissingPaymentId",t[t.MissingPaymentInstrument=11]="MissingPaymentInstrument",t[t.MissingPaymentMethod=12]="MissingPaymentMethod",t[t.MissingPaymentRedirectUrl=13]="MissingPaymentRedirectUrl",t[t.MissingPaymentStatus=14]="MissingPaymentStatus",t[t.MissingPaymentToken=15]="MissingPaymentToken",t[t.MissingShippingAddress=16]="MissingShippingAddress"}(Fa||(Fa={}));const qa=function(t){function e(e){var n=t.call(this,function(t){switch(t){case Fa.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case Fa.MissingCart:return"Unable to proceed because cart data is unavailable.";case Fa.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case Fa.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case Fa.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case Fa.MissingCheckoutConfig:case Fa.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case Fa.MissingOrder:return"Unable to proceed because order data is unavailable.";case Fa.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case Fa.MissingPayment:return"Unable to proceed because payment data is unavailable.";case Fa.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case Fa.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case Fa.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(e))||this;return n.subtype=e,n.name="MissingDataError",n.type="missing_data",n}return(0,o.__extends)(e,t),e}(u),Ba=function(){function t(t,e,n,r,i){this._store=t,this._formPoster=e,this._checkoutActionCreator=n,this._googlePayPaymentProcessor=r,this._cartRequestSender=i}return t.prototype.initialize=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n,r,i,a,u,s,c,d;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(e=t.containerId,n=t.methodId,r=t.currencyCode,i=this._getGooglePayOptions(t),a=i.buyNowInitializeOptions,!e||!n)throw new za('Unable to proceed because "containerId" argument is not provided.');if(u=this._store.getState(),s=u.paymentMethods.getPaymentMethod(n),c=((null==s?void 0:s.config)||{}).testMode,this._methodId=n,this._isBuyNowFlow=!!a,!this._isBuyNowFlow)return[3,2];if(!r)throw new za('Unable to initialize payment because "options.currencyCode" argument is not provided.');return d=i.buyNowInitializeOptions,this._googlePayPaymentProcessor.updateBuyNowFlowFlag(this._isBuyNowFlow),[4,this._googlePayPaymentProcessor.initialize(this._getMethodId(),this._getGooglePayClientOptions(r,c,d))];case 1:return o.sent(),[3,5];case 2:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 3:return o.sent(),[4,this._googlePayPaymentProcessor.initialize(this._getMethodId())];case 4:o.sent(),o.label=5;case 5:return this._walletButton=this._createSignInButton(e,i,r),[2]}}))}))},t.prototype.deinitialize=function(){return this._walletButton&&this._walletButton.parentNode&&(this._walletButton.parentNode.removeChild(this._walletButton),this._walletButton=void 0),this._googlePayPaymentProcessor.deinitialize()},t.prototype._getGooglePayClientOptions=function(t,e,n){var r=this;return{environment:e?"TEST":"PRODUCTION",paymentDataCallbacks:{onPaymentDataChanged:function(e){var i=e.callbackTrigger;return(0,o.__awaiter)(r,void 0,void 0,(function(){var e,r,a,u,s;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(i!==Wo.INITIALIZE)return[2];o.label=1;case 1:return o.trys.push([1,5,,6]),e=this,[4,this._createBuyNowCart(n)];case 2:return e._buyNowCart=o.sent(),this._buyNowCart?(r=this._buyNowCart,a=r.id,u=r.cartAmount,[4,this._store.dispatch(this._checkoutActionCreator.loadCheckout(a))]):[3,4];case 3:return o.sent(),[2,{newTransactionInfo:{currencyCode:t,totalPrice:String(u),totalPriceStatus:Ko.FINAL}}];case 4:return[3,6];case 5:throw s=o.sent(),new ga(s);case 6:return[2]}}))}))}}}},t.prototype._createSignInButton=function(t,e,n){var r=this,i=document.getElementById(t),o=e.buttonType,a=e.buttonColor;if(!i)throw new za("Unable to create sign-in button without valid container ID.");var u=this._googlePayPaymentProcessor.createButton((function(t){return r._handleWalletButtonClick(t,n)}),o,a);return i.appendChild(u),u},t.prototype._getMethodId=function(){if(!this._methodId)throw new Ua(ja.PaymentNotInitialized);return this._methodId},t.prototype._getGooglePayOptions=function(t){if(t.methodId===ji.GOOGLEPAY_ADYENV2&&t.googlepayadyenv2)return t.googlepayadyenv2;if(t.methodId===ji.GOOGLEPAY_ADYENV3&&t.googlepayadyenv3)return t.googlepayadyenv3;if(t.methodId===ji.GOOGLEPAY_AUTHORIZENET&&t.googlepayauthorizenet)return t.googlepayauthorizenet;if(t.methodId===ji.GOOGLEPAY_BNZ&&t.googlepaybnz)return t.googlepaybnz;if(t.methodId===ji.GOOGLEPAY_BRAINTREE&&t.googlepaybraintree)return t.googlepaybraintree;if(t.methodId===ji.GOOGLEPAY_CHECKOUTCOM&&t.googlepaycheckoutcom)return t.googlepaycheckoutcom;if(t.methodId===ji.GOOGLEPAY_CYBERSOURCEV2&&t.googlepaycybersourcev2)return t.googlepaycybersourcev2;if(t.methodId===ji.GOOGLEPAY_ORBITAL&&t.googlepayorbital)return t.googlepayorbital;if(t.methodId===ji.GOOGLEPAY_STRIPE&&t.googlepaystripe)return t.googlepaystripe;if(t.methodId===ji.GOOGLEPAY_STRIPEUPE&&t.googlepaystripeupe)return t.googlepaystripeupe;if(t.methodId===ji.GOOGLEPAY_WORLDPAYACCESS&&t.googlepayworldpayaccess)return t.googlepayworldpayaccess;throw new za},t.prototype._createBuyNowCart=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if("function"!=typeof(null==t?void 0:t.getBuyNowCartRequestBody))return[3,4];if(!(e=t.getBuyNowCartRequestBody()))throw new qa(Fa.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._cartRequestSender.createBuyNowCart(e)];case 2:return[2,n.sent().body];case 3:throw n.sent(),new ga;case 4:return[2]}}))}))},t.prototype._handleWalletButtonClick=function(t,e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:t.preventDefault(),i.label=1;case 1:return i.trys.push([1,7,,8]),this._isBuyNowFlow&&e&&this._googlePayPaymentProcessor.updatePaymentDataRequest({transactionInfo:{currencyCode:e,totalPrice:"0",totalPriceStatus:Ko.ESTIMATED},callbackIntents:[Zo.OFFER]}),[4,this._googlePayPaymentProcessor.displayWallet()];case 2:return n=i.sent(),[4,this._googlePayPaymentProcessor.handleSuccess(n)];case 3:return i.sent(),xo(this._store.getState().cart.getCartOrThrow())>0&&n.shippingAddress?[4,this._googlePayPaymentProcessor.updateShippingAddress(n.shippingAddress)]:[3,5];case 4:i.sent(),i.label=5;case 5:return[4,this._onPaymentSelectComplete()];case 6:return i.sent(),[3,8];case 7:if((r=i.sent())&&"CANCELED"!==r.message)throw r;return[3,8];case 8:return[2]}}))}))},t.prototype._onPaymentSelectComplete=function(){var t,e=null===(t=this._buyNowCart)||void 0===t?void 0:t.id;this._formPoster.postForm("/checkout.php",(0,o.__assign)({headers:(0,o.__assign)({Accept:"text/html","Content-Type":"application/x-www-form-urlencoded"},ir)},e&&{action:"set_external_checkout",provider:this._methodId,cart_id:e}))},(0,o.__decorate)([Zr],t.prototype,"_handleWalletButtonClick",null),t}();var Ga={es:["es_es","es_mx","es_pe","es_co","es_ar","es_cl"],en:["en_us","en_gb","en_ca","en_es","en_fr","en_ie","en_sg","en_au","en_nz","en_my","en_hk","en_th","en_ae","en_sa","en_qa","en_kw","en_za"],pt:["pt_br"],zu:["zu_za"],ar:["ar_sa","ar_ae","ar_qa","ar_kw"],zh:["zh_sg","zh_hk"],ms:["ms_my"],uk:["uk_ua"],sv:["sv_se"],hr:["hr_hr"],pl:["pl_pl"],nl:["nl_be"],it:["it_it"],de:["de_de"],fr:["fr_fr","fr_ca"]};function Va(t){var e=t.replace("-","_").toLowerCase().split("_"),n=e[0],r=n+"_"+e[1],i=Ga[n];return i?i.indexOf(r)>-1?r:i[0]:"en_us"}const Ya=function(){function t(t,e,n,r){this._store=t,this._checkoutActionCreator=e,this._masterpassScriptLoader=n,this._locale=r}return t.prototype.initialize=function(t){var e=this,n=t.containerId,r=t.methodId;if(!n||!r)throw new Yr('Unable to proceed because "containerId" argument is not provided.');return this._methodId=r,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()).then((function(t){var n=t.paymentMethods.getPaymentMethod(r);if(!n||!n.initializationData.checkoutId)throw new kn(xn.MissingPaymentMethod);var i={useMasterpassSrc:n.initializationData.isMasterpassSrcEnabled,language:Va(e._locale),testMode:n.config.testMode,checkoutId:n.initializationData.checkoutId};return e._masterpassScriptLoader.load(i)})).then((function(t){e._masterpassClient=t,e._signInButton=e._createSignInButton(n)}))},t.prototype.deinitialize=function(){return this._signInButton&&this._signInButton.parentNode&&(this._signInButton.removeEventListener("click",this._handleWalletButtonClick),this._signInButton.parentNode.removeChild(this._signInButton),this._signInButton=void 0),Promise.resolve()},t.prototype._createSignInButton=function(t){var e=document.getElementById(t),n=this._store.getState(),r=this._methodId?n.paymentMethods.getPaymentMethod(this._methodId):null,i=n.config.getStoreConfig();if(!e)throw new Error("Need a container to place the button");if(!r)throw new kn(xn.MissingPaymentMethod);if(!i)throw new Yr("Unable to retrieve store configuration");var o=document.createElement("input");if(o.type="image",r.initializationData.isMasterpassSrcEnabled){var a=r.config.testMode?"sandbox.":"",u=r.initializationData.checkoutId,s=["locale="+Va(this._locale),"paymentmethod=master,visa,amex,discover","checkoutid="+u];o.src=["https://"+a+"src.mastercard.com/assets/img/btn/src_chk_btn_126x030px.svg",s.join("&")].join("?")}else o.src="https://static.masterpass.com/dyn/img/btn/global/mp_chk_btn_160x037px.svg";return e.appendChild(o),o.addEventListener("click",this._handleWalletButtonClick),o},t.prototype._createMasterpassPayload=function(){var t=this._store.getState(),e=t.checkout.getCheckout(),n=this._methodId?t.paymentMethods.getPaymentMethod(this._methodId):null;if(!e)throw new kn(xn.MissingCheckout);if(!n)throw new kn(xn.MissingPaymentMethod);return{checkoutId:n.initializationData.checkoutId,allowedCardTypes:n.initializationData.allowedCardTypes,amount:e.cart.cartAmount.toString(),currency:e.cart.currency.code,cartId:e.cart.id,callbackUrl:("cart",window.location.origin+"/checkout.php?action=set_external_checkout&provider=masterpass&gateway=stripe&origin=cart")}},t.prototype._handleWalletButtonClick=function(){if(!this._masterpassClient)throw new ai(ni.CheckoutButtonNotInitialized);this._masterpassClient.checkout(this._createMasterpassPayload())},(0,o.__decorate)([Zr],t.prototype,"_handleWalletButtonClick",null),t}(),Ha=function(){function t(t,e,n,r,i){void 0===i&&(i=""),this._store=t,this._checkoutActionCreator=e,this._paypalScriptLoader=n,this._formPoster=r,this._host=i}return t.prototype.initialize=function(t){var e=this,n=t.paypal,r=this._store.getState(),i=this._paymentMethod=r.paymentMethods.getPaymentMethod(t.methodId);if(!n)throw new Yr;if(!i)throw new kn(xn.MissingPaymentMethod);return this._paypalScriptLoader.loadPaypal(i.config.merchantId).then((function(r){var a,u,s;if(!i||!i.config.merchantId)throw new kn(xn.MissingPaymentMethod);var c=i.config.merchantId,d=i.config.testMode?"sandbox":"production",l=((a={})[d]=n.clientId,a),f=r.FUNDING.CREDIT||"credit",p=n.allowCredit?[f]:[],h=n.allowCredit?[]:[f];return r.Button.render({env:d,client:l,commit:n.shouldProcessPayment,funding:{allowed:p,disallowed:h},style:(0,o.__assign)((0,o.__assign)({shape:Ma.RECT},(0,y.pick)(n.style,"layout","color","label","shape","tagline","fundingicons")),{size:"paypalexpress"===i.id&&"small"===(null===(u=n.style)||void 0===u?void 0:u.size)?xa.RESPONSIVE:null===(s=n.style)||void 0===s?void 0:s.size}),payment:function(t,r){return e._setupPayment(c,r,n.onPaymentError)},onAuthorize:function(t,r){return e._tokenizePayment(t,r,n.shouldProcessPayment,n.onAuthorizeError)}},t.containerId)}))},t.prototype.deinitialize=function(){return this._paymentMethod=void 0,Promise.resolve()},t.prototype._setupPayment=function(t,e,n){var r=this;if(!e)throw new ai(ni.CheckoutButtonNotInitialized);return this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()).then((function(n){var i=n.cart.getCart(),a=i?i.id:"";return e.request.post(r._host+"/api/storefront/payment/paypalexpress",{merchantId:t,cartId:a},{headers:(0,o.__assign)({"X-API-INTERNAL":rr},ir)})})).then((function(t){return t.id})).catch((function(t){throw n&&n(t),t}))},t.prototype._tokenizePayment=function(t,e,n,r){var i=this;if(!this._paymentMethod)throw new ai(ni.CheckoutButtonNotInitialized);if(!e)throw new ai(ni.CheckoutButtonNotInitialized);if(!t.paymentID||!t.payerID)throw new kn(xn.MissingPayment);var o=this._paymentMethod.id;return e.payment.get(t.paymentID).then((function(e){i._formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:o,action:n?"process_payment":"set_external_checkout",paymentId:t.paymentID,payerId:t.payerID,payerInfo:JSON.stringify(e.payer.payer_info)})}))},t}();function Wa(){try{return"production"}catch(t){return"development"}}n(64701);const Ka=function(){function t(t){this._console=t}return t.prototype.log=function(){for(var t=[],e=0;e0}));a.length>1&&a[0].matches===a[1].matches&&"development"===Wa()&&Ja.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.");var u=a[0];if(u&&u.token)return u.token;if(this._useFallback){var s=null===(n=o.find((function(t){return t.default})))||void 0===n?void 0:n.token;if(s)return s}throw new Error("Unable to resolve to a registered token with the provided token.")},t}();function Xa(t,e){return Object.assign(t,{resolveIds:e})}const tu=function(t){function e(e){var n=t.call(this,e||"Payment process was cancelled.")||this;return n.name="PaymentMethodCancelledError",n.type="payment_cancelled",n}return(0,o.__extends)(e,t),e}(u);const eu=function(t){function e(e){var n=t.call(this,e||"An unexpected error has occurred during buy now cart creation process. Please try again later.")||this;return n.name="BuyNowCartCreationError",n.type="buy_now_cart_creation_error",n}return(0,o.__extends)(e,t),e}(u);function nu(t){if(!function(t){return"ApplePaySession"in t}(t))throw new Error("Apple pay is not supported")}const ru=function(){function t(){}return t.prototype.create=function(t){return nu(window),new ApplePaySession(1,t)},t}();var iu;!function(t){t.Subtotal="Subtotal",t.Shipping="Shipping"}(iu||(iu={}));const ou=function(){function t(t,e,n){this._requestSender=t,this._paymentIntegrationService=e,this._sessionFactory=n,this._onAuthorizeCallback=y.noop,this._subTotalLabel=iu.Subtotal,this._shippingLabel=iu.Shipping}return t.prototype.initialize=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n,r,i,a,u,s,c;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(e=t.methodId,n=t.containerId,r=t.applepay,nu(window),!e||!r)throw new qa(Fa.MissingPaymentMethod);return i=r.buttonClassName,a=r.onPaymentAuthorize,u=r.buyNowInitializeOptions,s=r.requiresShipping,this._requiresShipping=s,this._buyNowInitializeOptions=u,this._onAuthorizeCallback=a,u?[3,2]:[4,this._paymentIntegrationService.loadDefaultCheckout()];case 1:o.sent(),o.label=2;case 2:return[4,this._paymentIntegrationService.loadPaymentMethod(e)];case 3:return o.sent(),c=this._paymentIntegrationService.getState(),this._paymentMethod=c.getPaymentMethodOrThrow(e),[4,this._paymentIntegrationService.verifyCheckoutSpamProtection()];case 4:return o.sent(),this._applePayButton=this._createButton(n,i),this._applePayButton.addEventListener("click",this._handleWalletButtonClick.bind(this)),[2,Promise.resolve()]}}))}))},t.prototype.deinitialize=function(){return Promise.resolve()},t.prototype._createButton=function(t,e){void 0===e&&(e="apple-pay-checkout-button");var n=document.getElementById(t);if(!n)throw new za("Unable to create wallet button without valid container ID.");document.body.classList.add("apple-pay-supported");var r=document.createElement("div");return r.setAttribute("class",e),r.setAttribute("role","button"),r.setAttribute("aria-label","Apple Pay button"),n.appendChild(r),r},t.prototype._handleWalletButtonClick=function(t){var e;return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r,i,a,u,s,c,d,l,f,p,h;return(0,o.__generator)(this,(function(o){if(t.preventDefault(),!this._paymentMethod||!this._paymentMethod.initializationData)throw new qa(Fa.MissingPaymentMethod);return this._buyNowInitializeOptions&&"function"==typeof this._buyNowInitializeOptions.getBuyNowCartRequestBody?(n=this._paymentMethod.initializationData,r=n.countryCode,i=n.currencyCode,a=n.merchantCapabilities,u=n.supportedNetworks,s=n.storeName,p=this._getRequestWithEmptyTotal(r,i,u,a),this._requiresShipping&&(null===(e=p.requiredShippingContactFields)||void 0===e||e.push("postalAddress")),h=this._sessionFactory.create(p),this._handleApplePayEvents(h,this._paymentMethod,s),h.begin()):(c=this._paymentIntegrationService.getState(),d=c.getCartOrThrow(),l=c.getStoreConfigOrThrow(),f=c.getCheckoutOrThrow(),p=this._getBaseRequest(d,f,l,this._paymentMethod),h=this._sessionFactory.create(p),this._handleApplePayEvents(h,this._paymentMethod,l.storeProfile.storeName),h.begin()),[2]}))}))},t.prototype._getRequestWithEmptyTotal=function(t,e,n,r){return{countryCode:t,currencyCode:e,supportedNetworks:n,merchantCapabilities:r,total:{label:"",amount:"0",type:"pending"},requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"]}},t.prototype._getBaseRequest=function(t,e,n,r){var i,o=n.storeProfile,a=o.storeCountryCode,u=o.storeName,s=t.currency,c=s.code,d=s.decimalPlaces,l=r.initializationData,f=l.merchantCapabilities,p=l.supportedNetworks,h=t.lineItems.physicalItems.length>0,y={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:a,currencyCode:c,merchantCapabilities:f,supportedNetworks:p,lineItems:[],total:h?{label:u,amount:""+e.grandTotal.toFixed(d),type:"pending"}:{label:u,amount:""+e.grandTotal.toFixed(d),type:"final"}};if(h)null===(i=y.requiredShippingContactFields)||void 0===i||i.push("postalAddress");else{var m=[{label:this._subTotalLabel,amount:""+e.subtotal.toFixed(d)}];e.taxes.forEach((function(t){return m.push({label:t.name,amount:""+t.amount.toFixed(d)})})),y.lineItems=m}return y},t.prototype._handleApplePayEvents=function(t,e,n){var r=this;t.onvalidatemerchant=function(n){return(0,o.__awaiter)(r,void 0,void 0,(function(){var r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this._onValidateMerchant(e,n)];case 1:return r=i.sent().body,t.completeMerchantValidation(r),[3,3];case 2:throw i.sent(),new Error("Merchant validation failed");case 3:return[2]}}))}))},this._buyNowInitializeOptions&&!this._requiresShipping&&(t.onpaymentmethodselected=function(){return(0,o.__awaiter)(r,void 0,void 0,(function(){return(0,o.__generator)(this,(function(e){switch(e.label){case 0:return[4,this._createBuyNowCart()];case 1:return e.sent(),this._handlePaymentMethodSelected(t),[2]}}))}))}),t.onshippingcontactselected=function(e){return(0,o.__awaiter)(r,void 0,void 0,(function(){return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return this._buyNowInitializeOptions&&this._requiresShipping?[4,this._createBuyNowCart()]:[3,2];case 1:r.sent(),r.label=2;case 2:return[4,this._handleShippingContactSelected(t,n,e)];case 3:return r.sent(),[2]}}))}))},t.onshippingmethodselected=function(e){return(0,o.__awaiter)(r,void 0,void 0,(function(){return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._handleShippingMethodSelected(t,n,e)];case 1:return r.sent(),[2]}}))}))},t.oncancel=function(){return(0,o.__awaiter)(r,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return n.trys.push([0,3,,4]),t="/remote-checkout/"+e.id+"/signout",[4,this._requestSender.get(t)];case 1:return n.sent(),[4,this._paymentIntegrationService.loadCheckout()];case 2:return[2,n.sent()];case 3:throw n.sent(),new tu;case 4:return[2]}}))}))},t.onpaymentauthorized=function(n){return(0,o.__awaiter)(r,void 0,void 0,(function(){return(0,o.__generator)(this,(function(r){return[2,this._onPaymentAuthorized(n,t,e)]}))}))}},t.prototype._createBuyNowCart=function(){var t,e;return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:if(i.trys.push([0,3,,4]),!(n=null===(e=null===(t=this._buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody)||void 0===e?void 0:e.call(t)))throw new qa(Fa.MissingCart);return[4,this._paymentIntegrationService.createBuyNowCart(n)];case 1:return r=i.sent(),[4,this._paymentIntegrationService.loadCheckout(r.id)];case 2:return i.sent(),[3,4];case 3:throw i.sent(),new eu;case 4:return[2]}}))}))},t.prototype._handlePaymentMethodSelected=function(t){var e=this._paymentIntegrationService.getState(),n=e.getCartOrThrow(),r=e.getStoreConfigOrThrow(),i=e.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new qa(Fa.MissingPaymentMethod);var o=this._getBaseRequest(n,i,r,this._paymentMethod);delete o.total.type,t.completePaymentMethodSelection({newTotal:o.total,newLineItems:o.lineItems})},t.prototype._handleShippingContactSelected=function(t,e,n){var r;return(0,o.__awaiter)(this,void 0,void 0,(function(){var i,a,u,s,c,d,l,f,p,h,y,m;return(0,o.__generator)(this,(function(v){switch(v.label){case 0:i=this._transformContactToAddress(n.shippingContact),v.label=1;case 1:return v.trys.push([1,3,,4]),[4,this._paymentIntegrationService.updateShippingAddress(i)];case 2:return v.sent(),[3,4];case 3:throw v.sent(),t.abort(),new Error("Shipping address update failed");case 4:if(a=this._paymentIntegrationService.getState(),u=a.getCartOrThrow().currency.decimalPlaces,s=a.getCheckoutOrThrow(),c=null===(r=s.consignments[0].selectedShippingOption)||void 0===r?void 0:r.id,d=s.consignments[0].availableShippingOptions,l=null==d?void 0:d.find((function(t){return t.id===c})),f=null==d?void 0:d.filter((function(t){return t.id!==c})),p=l?[{label:l.description,amount:""+l.cost.toFixed(u),detail:l.additionalDescription,identifier:l.id}]:[],f&&(0,o.__spreadArrays)(f.filter((function(t){return t.isRecommended})),f.filter((function(t){return!t.isRecommended}))).forEach((function(t){return p.push({label:t.description,amount:""+t.cost.toFixed(u),detail:t.additionalDescription,identifier:t.id})})),!(d instanceof Array))throw new Error("Shipping options not available.");if(0===d.length)return t.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:e,amount:""+s.grandTotal.toFixed(u)},[]),[2];h=d.find((function(t){return t.isRecommended})),y=h?h.id:d[0].id,m=l?l.id:y,v.label=5;case 5:return v.trys.push([5,7,,8]),[4,this._updateShippingOption(m)];case 6:return v.sent(),[3,8];case 7:throw v.sent(),new Error("Shipping options update failed");case 8:return a=this._paymentIntegrationService.getState(),s=a.getCheckoutOrThrow(),t.completeShippingContactSelection({newShippingMethods:p,newTotal:{type:"final",label:e,amount:""+s.grandTotal.toFixed(u)},newLineItems:this._getUpdatedLineItems(s,u)}),[2]}}))}))},t.prototype._handleShippingMethodSelected=function(t,e,n){return(0,o.__awaiter)(this,void 0,void 0,(function(){var r,i,a,u;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:r=n.shippingMethod.identifier,o.label=1;case 1:return o.trys.push([1,3,,4]),[4,this._updateShippingOption(r)];case 2:return o.sent(),[3,4];case 3:throw o.sent(),t.abort(),new Error("Shipping option selection update failed.");case 4:return i=this._paymentIntegrationService.getState(),a=i.getCartOrThrow().currency.decimalPlaces,u=i.getCheckoutOrThrow(),t.completeShippingMethodSelection({newTotal:{type:"final",label:e,amount:""+u.grandTotal.toFixed(a)},newLineItems:this._getUpdatedLineItems(u,a)}),[2]}}))}))},t.prototype._getUpdatedLineItems=function(t,e){var n=[{label:this._subTotalLabel,amount:""+t.subtotal.toFixed(e)}];return t.taxes.forEach((function(t){return n.push({label:t.name,amount:""+t.amount.toFixed(e)})})),n.push({label:this._shippingLabel,amount:""+t.shippingCostTotal.toFixed(e)}),n},t.prototype._updateShippingOption=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(e){return[2,this._paymentIntegrationService.selectShippingOption(t)]}))}))},t.prototype._onValidateMerchant=function(t,e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n;return(0,o.__generator)(this,(function(r){return n=["validationUrl="+e.validationURL,"merchantIdentifier="+t.initializationData.merchantId,"displayName="+t.initializationData.storeName,"domainName="+window.location.hostname].join("&"),[2,this._requestSender.post((i=t.initializationData.paymentsUrl,i+"/api/public/v1/payments/applepay/validate_merchant"),{credentials:!1,headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","X-XSRF-TOKEN":null},body:n})];var i}))}))},t.prototype._onPaymentAuthorized=function(t,e,n){return(0,o.__awaiter)(this,void 0,void 0,(function(){var r,i,a,u,s,c,d,l,f,p,h,y;return(0,o.__generator)(this,(function(m){switch(m.label){case 0:r=t.payment,i=r.token,a=r.billingContact,u=r.shippingContact,s=this._paymentIntegrationService.getState(),c=s.getCartOrThrow(),d=c.lineItems.physicalItems.length>0,l={methodId:n.id,paymentData:{formattedPayload:{apple_pay_token:{payment_data:i.paymentData,payment_method:i.paymentMethod,transaction_id:i.transactionIdentifier}}}},f=this._transformContactToAddress(a),p=this._transformContactToAddress(u),h=null==u?void 0:u.emailAddress,y=(null==u?void 0:u.phoneNumber)||"",m.label=1;case 1:return m.trys.push([1,7,,8]),[4,this._paymentIntegrationService.updateBillingAddress((0,o.__assign)((0,o.__assign)({},f),{email:h,phone:y}))];case 2:return m.sent(),d?[4,this._paymentIntegrationService.updateShippingAddress(p)]:[3,4];case 3:m.sent(),m.label=4;case 4:return[4,this._paymentIntegrationService.submitOrder({useStoreCredit:!1})];case 5:return m.sent(),[4,this._paymentIntegrationService.submitPayment(l)];case 6:return m.sent(),e.completePayment(ApplePaySession.STATUS_SUCCESS),[2,this._onAuthorizeCallback()];case 7:throw m.sent(),e.completePayment(ApplePaySession.STATUS_FAILURE),new Error("Payment cannot complete");case 8:return[2]}}))}))},t.prototype._transformContactToAddress=function(t){return{firstName:(null==t?void 0:t.givenName)||"",lastName:(null==t?void 0:t.familyName)||"",city:(null==t?void 0:t.locality)||"",company:"",address1:(null==t?void 0:t.addressLines)&&t.addressLines[0]||"",address2:(null==t?void 0:t.addressLines)&&t.addressLines[1]||"",postalCode:(null==t?void 0:t.postalCode)||"",countryCode:(null==t?void 0:t.countryCode)||"",phone:(null==t?void 0:t.phoneNumber)||"",stateOrProvince:(null==t?void 0:t.administrativeArea)||"",stateOrProvinceCode:(null==t?void 0:t.administrativeArea)||"",customFields:[]}},t}(),au=Xa((function(t){var n=t.getState().getHost;return new ou((0,e.createRequestSender)({host:n()}),t,new ru)}),[{id:"applepay"}]);var uu=n(15373);const su=function(t){function e(e){var n=t.call(this,e||"Not implemented.")||this;return n.name="NotImplementedError",n.type="not_implemented",n}return(0,o.__extends)(e,t),e}(u);var cu,du,lu;!function(t){t.SandboxMode="bolt_sandbox",t.StagingMode="bolt_staging",t.DevelopmentMode="bolt_development"}(cu||(cu={})),function(t){t.Small="small",t.Medium="medium",t.Large="large"}(du||(du={})),function(t){t.Pill="pill",t.Rect="rect"}(lu||(lu={}));const fu=function(){function t(t,e,n){void 0===n&&(n=window),this.paymentIntegrationService=t,this.boltScriptLoader=e,this.boltHostWindow=n}return t.prototype.initialize=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n,r,i,a,u,s,c,d,l,f,p,h;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(e=t.bolt,n=t.containerId,r=t.methodId,a=(i=e||{}).buyNowInitializeOptions,u=i.style,!r)throw new za('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new za('Unable to initialize payment because "options.containerId" argument is not provided.');if(!e)throw new za('Unable to initialize payment because "options.bolt" argument is not provided.');if(!Boolean(a))throw new su("Only buy now flow is implemented for Bolt button");if(!(null==a?void 0:a.storefrontApiToken)||"string"!=typeof a.storefrontApiToken)throw new za('Unable to initialize payment because "options.storefrontApiToken" argument is not provided.');return s=this.paymentIntegrationService.getState(),c=s.getPaymentMethodOrThrow(r),d=c.initializationData,l=c.config,p=(f=d||{}).publishableKey,h=f.developerConfig,[4,this.boltScriptLoader.loadBoltClient(p,l.testMode,h,"BigCommerce",a.storefrontApiToken)];case 1:return o.sent(),this.renderButton(n,c,u),[2]}}))}))},t.prototype.deinitialize=function(){return Promise.resolve()},t.prototype.renderButton=function(t,e,n){var r;"function"==typeof(null===(r=this.boltHostWindow.BoltConnect)||void 0===r?void 0:r.setupProductPageCheckout)&&(this.addButtonContainer(t,e,n),this.boltHostWindow.BoltConnect.setupProductPageCheckout())},t.prototype.addButtonContainer=function(t,e,n){var r=document.getElementById(t);if(r){var i=document.createElement("div"),o=document.createElement("object");i.setAttribute("id","product-page-checkout-wrapper"),i.setAttribute("class","bolt-button-wrapper"),i.setAttribute("style","display:none"),i.setAttribute("data-tid","product-page-checkout-wrapper"),o.setAttribute("data",this.getBoltObjectData(e,n)),o.setAttribute("class","bolt-product-checkout-button"),i.append(o),r.innerHTML="",r.append(i)}},t.prototype.getBoltObjectData=function(t,e){var n=t.initializationData,r=t.config,i=n||{},o=i.publishableKey,a=i.developerConfig,u=this.boltScriptLoader.getDomainURL(!!r.testMode,a),s=this.getButtonHeight(null==e?void 0:e.size),c=this.getButtonBorderRadius(null==e?void 0:e.shape,s);return(0,uu.stringifyUrl)({url:"https://"+u+"/v1/checkout_button",query:{publishable_key:o,variant:"ppc",height:s,border_radius:c}})},t.prototype.getButtonHeight=function(t){if(t)switch(t){case du.Small:return 25;case du.Large:return 45;case du.Medium:default:return 40}},t.prototype.getButtonBorderRadius=function(t,e){if(t)switch(t){case lu.Pill:return e?Math.round(e/2):void 0;case lu.Rect:default:return 4}},t}();const pu=function(t){function e(e){var n=t.call(this,e||"Unable to proceed because the client library of a payment method is not loaded or ready to be used.")||this;return n.name="PaymentMethodClientUnavailableError",n.type="payment_method_client_unavailable",n}return(0,o.__extends)(e,t),e}(u),hu=function(){function t(t,e){void 0===e&&(e=window),this.scriptLoader=t,this.boltHostWindow=e}return t.prototype.loadBoltClient=function(t,e,n,r,i){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(this.boltHostWindow.BoltCheckout)return[2,this.boltHostWindow.BoltCheckout];if(!t)throw new za('Unable to initialize payment because "publishableKey" argument is not provided.');return[4,this.scriptLoader.loadScript("//"+this.getDomainURL(!!e,n)+"/connect-bigcommerce.js",this.getScriptOptions("bolt-connect",t,r,i))];case 1:return o.sent(),[4,this.scriptLoader.loadScript("//"+this.getDomainURL(!!e,n)+"/track.js",this.getScriptOptions("bolt-track",t))];case 2:if(o.sent(),!this.boltHostWindow.BoltCheckout)throw new pu;return[2,this.boltHostWindow.BoltCheckout]}}))}))},t.prototype.loadBoltEmbedded=function(t,e,n){return(0,o.__awaiter)(this,void 0,void 0,(function(){var r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:return r={async:!0,attributes:{id:"bolt-embedded"}},[4,this.scriptLoader.loadScript("//"+this.getDomainURL(!!e,n)+"/embed.js",r)];case 1:if(i.sent(),!this.boltHostWindow.Bolt)throw new pu;return[2,this.boltHostWindow.Bolt(t)]}}))}))},t.prototype.getDomainURL=function(t,e){if(!t)return"connect.bolt.com";if(e)switch(e.developerMode){case cu.StagingMode:return"connect-staging.bolt.com";case cu.DevelopmentMode:return"connect."+e.developerDomain}return"connect-sandbox.bolt.com"},t.prototype.getScriptOptions=function(t,e,n,r){return{async:!0,attributes:(0,o.__assign)((0,o.__assign)({id:t,"data-publishable-key":e},n&&{"data-shopping-cart-id":n}),r&&{"data-storefront-api-token":r})}},t}(),yu=Xa((function(t){return new fu(t,new hu((0,ar.Vr)()))}),[{id:"bolt"}]);var mu,vu,gu,_u,bu,Su,wu;!function(t){t.BuyNow="BUY_NOW"}(mu||(mu={})),function(t){t.AUTHORIZE="authorize",t.CAPTURE="capture"}(vu||(vu={})),function(t){t.paypal="paypal",t.checkout="checkout",t.buynow="buynow",t.pay="pay",t.installment="installment"}(gu||(gu={})),function(t){t.gold="gold",t.blue="blue",t.silver="silver",t.black="black",t.white="white"}(_u||(_u={})),function(t){t.pill="pill",t.rect="rect"}(bu||(bu={})),function(t){t.OXXO="oxxo"}(Su||(Su={})),function(t){t.Approved="APPROVED",t.Created="CREATED",t.PayerActionRequired="PAYER_ACTION_REQUIRED"}(wu||(wu={}));const Cu=function(){function t(t,e,n,r){this.formPoster=t,this.paymentIntegrationService=e,this.paypalCommerceRequestSender=n,this.paypalCommerceScriptLoader=r}return t.prototype.loadPayPalSdk=function(t,e,n){return(0,o.__awaiter)(this,void 0,void 0,(function(){var r,i,a,u;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:return r=this.paymentIntegrationService.getState(),i=e||r.getCartOrThrow().currency.code,a=r.getPaymentMethodOrThrow(t),u=this,[4,this.paypalCommerceScriptLoader.getPayPalSDK(a,i,n)];case 1:return u.paypalSdk=o.sent(),[2,this.paypalSdk]}}))}))},t.prototype.getPayPalSdkOrThrow=function(){if(!this.paypalSdk)throw new pu;return this.paypalSdk},t.prototype.createBuyNowCartOrThrow=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:if(!(e=t.getBuyNowCartRequestBody()))throw new qa(Fa.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.paymentIntegrationService.createBuyNowCart(e)];case 2:return[2,n.sent()];case 3:throw n.sent(),new eu;case 4:return[2]}}))}))},t.prototype.createOrder=function(t,e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return n=this.paymentIntegrationService.getState().getCartOrThrow().id,[4,this.paypalCommerceRequestSender.createOrder(t,(0,o.__assign)({cartId:n},e))];case 1:return[2,r.sent().orderId]}}))}))},t.prototype.updateOrder=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t,e,n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:t=this.paymentIntegrationService.getState(),e=t.getCartOrThrow(),n=t.getConsignmentsOrThrow()[0],r.label=1;case 1:return r.trys.push([1,3,,4]),[4,this.paypalCommerceRequestSender.updateOrder({availableShippingOptions:n.availableShippingOptions,cartId:e.id,selectedShippingOption:n.selectedShippingOption})];case 2:return r.sent(),[3,4];case 3:throw r.sent(),new c;case 4:return[2]}}))}))},t.prototype.getOrderStatus=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,this.paypalCommerceRequestSender.getOrderStatus()];case 1:return[2,t.sent().status];case 2:throw t.sent(),new c;case 3:return[2]}}))}))},t.prototype.tokenizePayment=function(t,e){var n=this.paymentIntegrationService.getState().getCartOrThrow();if(!e)throw new qa(Fa.MissingOrderId);return this.formPoster.postForm("/checkout.php",(0,o.__assign)({payment_type:"paypal",action:"set_external_checkout",provider:t,order_id:e},n.source===mu.BuyNow&&{cart_id:n.id}))},t.prototype.submitPayment=function(t,e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return n={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:t,paypal_account:{order_id:e}}},[4,this.paymentIntegrationService.submitPayment({methodId:t,paymentData:n})];case 1:return r.sent(),[2]}}))}))},t.prototype.getShippingOptionOrThrow=function(t){var e=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],n=e.availableShippingOptions||[],r=n.find((function(t){return t.isRecommended})),i=(t?n.find((function(e){return e.id===t})):n.find((function(t){var n;return t.id===(null===(n=e.selectedShippingOption)||void 0===n?void 0:n.id)})))||r||n[0];if(!i)throw new Error("Your order can't be shipped to this address");return i},t.prototype.getAddress=function(t){return{firstName:(null==t?void 0:t.firstName)||"",lastName:(null==t?void 0:t.lastName)||"",email:(null==t?void 0:t.email)||"",phone:"",company:"",address1:(null==t?void 0:t.address1)||"",address2:"",city:(null==t?void 0:t.city)||"",countryCode:(null==t?void 0:t.countryCode)||"",postalCode:(null==t?void 0:t.postalCode)||"",stateOrProvince:"",stateOrProvinceCode:(null==t?void 0:t.stateOrProvinceCode)||"",customFields:[]}},t.prototype.getBillingAddressFromOrderDetails=function(t){var e=t.payer;return this.getAddress({firstName:e.name.given_name,lastName:e.name.surname,email:e.email_address,address1:e.address.address_line_1,city:e.address.admin_area_2,countryCode:e.address.country_code,postalCode:e.address.postal_code,stateOrProvinceCode:e.address.admin_area_1})},t.prototype.getShippingAddressFromOrderDetails=function(t){var e,n,r=t.payer,i=(null===(n=null===(e=t.purchase_units[0])||void 0===e?void 0:e.shipping)||void 0===n?void 0:n.address)||{};return this.getAddress({firstName:r.name.given_name,lastName:r.name.surname,email:r.email_address,address1:i.address_line_1,city:i.admin_area_2,countryCode:i.country_code,postalCode:i.postal_code,stateOrProvinceCode:i.admin_area_1})},t.prototype.getValidButtonStyle=function(t){var e=t||{},n=e.color,r=e.height,i=e.label,o=e.shape,a={color:n&&_u[n]?n:void 0,height:this.getValidHeight(r),label:i&&gu[i]?i:void 0,shape:o&&bu[o]?o:void 0};return(0,y.omitBy)(a,y.isNil)},t.prototype.getValidHeight=function(t){return t&&"number"==typeof t?t>55?55:t<25?25:t:40},t.prototype.removeElement=function(t){var e=t&&document.getElementById(t);e&&e.remove()},t}();var Eu,Iu="This API endpoint is for internal use only and may change in the future";!function(t){t.Json="application/json",t.JsonV1="application/vnd.bc.v1+json"}(Eu||(Eu={}));const Pu=Eu;var Au={"X-Checkout-SDK-Version":"1.398.2"};const Ou=function(){function t(t){this.requestSender=t}return t.prototype.createOrder=function(t,e){return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r,i;return(0,o.__generator)(this,(function(a){switch(a.label){case 0:return n="/api/storefront/payment/"+t,r=e,i=(0,o.__assign)({"X-API-INTERNAL":Iu,"Content-Type":Pu.Json},Au),[4,this.requestSender.post(n,{headers:i,body:r})];case 1:return[2,a.sent().body]}}))}))},t.prototype.updateOrder=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:return e=t,n=(0,o.__assign)({"X-API-INTERNAL":Iu,"Content-Type":Pu.Json},Au),[4,this.requestSender.put("/api/storefront/initialization/paypalcommerce",{headers:n,body:e})];case 1:return[2,r.sent().body]}}))}))},t.prototype.getOrderStatus=function(){return(0,o.__awaiter)(this,void 0,void 0,(function(){var t;return(0,o.__generator)(this,(function(e){switch(e.label){case 0:return t=(0,o.__assign)({"X-API-INTERNAL":Iu,"Content-Type":Pu.Json},Au),[4,this.requestSender.get("/api/storefront/initialization/paypalcommerce",{headers:t})];case 1:return[2,e.sent().body]}}))}))},t}(),Tu=function(){function t(t){this.scriptLoader=t,this.window=window}return t.prototype.getPayPalSDK=function(t,e,n){return(0,o.__awaiter)(this,void 0,void 0,(function(){var r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:return this.paypalSdk?[3,2]:(r=this,[4,this.loadPayPalSDK(this.getPayPalSdkScriptConfigOrThrow(t,e,n))]);case 1:r.paypalSdk=i.sent(),i.label=2;case 2:return[2,this.paypalSdk]}}))}))},t.prototype.loadPayPalSDK=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){return(0,o.__generator)(this,(function(e){switch(e.label){case 0:return this.window.paypalLoadScript?[3,2]:[4,this.scriptLoader.loadScript("https://unpkg.com/@paypal/paypal-js@5.0.5/dist/iife/paypal-js.min.js",{async:!0,attributes:{}})];case 1:if(e.sent(),!this.window.paypalLoadScript)throw new pu;e.label=2;case 2:return[4,this.window.paypalLoadScript(t)];case 3:if(e.sent(),!this.window.paypal)throw new pu;return[2,this.window.paypal]}}))}))},t.prototype.getPayPalSdkScriptConfigOrThrow=function(t,e,n){void 0===n&&(n=!0);var r=t.id,i=t.clientToken,a=t.initializationData;if(!(null==a?void 0:a.clientId))throw new qa(Fa.MissingPaymentMethod);var u=a.intent,s=a.clientId,c=a.merchantId,d=a.buyerCountry,l=a.attributionId,f=a.isVenmoEnabled,p=a.isHostedCheckoutEnabled,h=a.isPayPalCreditAvailable,y=a.isDeveloperModeApplicable,m=a.availableAlternativePaymentMethods,v=void 0===m?[]:m,g=a.enabledAlternativePaymentMethods,_=void 0===g?[]:g,b=p||n,S="paypalcommercecreditcards"===r,w=S?["card"]:[],C=S?[]:["card"],E=h?["credit","paylater"]:[],I=h?[]:["credit","paylater"],P=n||!b,A=P&&f?["venmo"]:[],O=P&&f?[]:["venmo"],T=P?_:[],x=P?v.filter((function(t){return!_.includes(t)})):v,R=(0,o.__spreadArrays)(C,I,O,x),k=(0,o.__spreadArrays)(w,E,A,T);return(0,o.__assign)({"client-id":s,"data-partner-attribution-id":l,"data-client-token":i,"merchant-id":c,"enable-funding":k.length>0?k:void 0,"disable-funding":R.length>0?R:void 0,commit:b,components:["buttons","hosted-fields","messages","payment-fields"],currency:e,intent:u},y&&{"buyer-country":d})},t}(),xu=function(t){var n=t.getState().getHost;return new Cu((0,i.createFormPoster)(),t,new Ou((0,e.createRequestSender)({host:n()})),new Tu((0,ar.Vr)()))},Ru=function(){function t(t,e){this.paymentIntegrationService=t,this.paypalCommerceIntegrationService=e}return t.prototype.initialize=function(t){var e;return(0,o.__awaiter)(this,void 0,void 0,(function(){var n,r,i,a,u;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(n=t.paypalcommerce,r=t.containerId,i=t.methodId,a=Boolean(null==n?void 0:n.buyNowInitializeOptions),!i)throw new za('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new za('Unable to initialize payment because "options.containerId" argument is not provided.');if(!n)throw new za('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');if(a&&!n.currencyCode)throw new za('Unable to initialize payment because "options.paypalcommerce.currencyCode" argument is not provided.');if(a&&"function"!=typeof(null===(e=n.buyNowInitializeOptions)||void 0===e?void 0:e.getBuyNowCartRequestBody))throw new za('Unable to initialize payment because "options.paypalcommerce.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');return a?[3,2]:[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:o.sent(),o.label=2;case 2:return u=a?n.currencyCode:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,[4,this.paypalCommerceIntegrationService.loadPayPalSdk(i,u,!1)];case 3:return o.sent(),this.renderButton(r,i,n),[2]}}))}))},t.prototype.deinitialize=function(){return Promise.resolve()},t.prototype.renderButton=function(t,e,n){var r=this,i=n.buyNowInitializeOptions,a=n.style,u=n.onComplete,s=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),c=(this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData||{}).isHostedCheckoutEnabled,d={createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommerce")},onApprove:function(t){var n=t.orderID;return r.paypalCommerceIntegrationService.tokenizePayment(e,n)}},l={onClick:function(){return r.handleClick(i)},onCancel:function(){return r.paymentIntegrationService.loadDefaultCheckout()}},f={onShippingAddressChange:function(t){return r.onShippingAddressChange(t)},onShippingOptionsChange:function(t){return r.onShippingOptionsChange(t)},onApprove:function(t,n){return r.onHostedCheckoutApprove(t,n,e,u)}},p=(0,o.__assign)((0,o.__assign)((0,o.__assign)({fundingSource:s.FUNDING.PAYPAL,style:this.paypalCommerceIntegrationService.getValidButtonStyle(a)},d),i&&l),c&&f),h=s.Buttons(p);h.isEligible()?h.render("#"+t):this.paypalCommerceIntegrationService.removeElement(t)},t.prototype.handleClick=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return t?[4,this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(t)]:[3,3];case 1:return e=n.sent(),[4,this.paymentIntegrationService.loadCheckout(e.id)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},t.prototype.onHostedCheckoutApprove=function(t,e,n,r){return(0,o.__awaiter)(this,void 0,void 0,(function(){var i,a,u,s,c,d;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(!t.orderID)throw new qa(Fa.MissingOrderId);return i=this.paymentIntegrationService.getState(),a=i.getCartOrThrow(),[4,e.order.get()];case 1:u=o.sent(),o.label=2;case 2:return o.trys.push([2,9,,10]),s=this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(u),[4,this.paymentIntegrationService.updateBillingAddress(s)];case 3:return o.sent(),a.lineItems.physicalItems.length>0?(c=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(u),[4,this.paymentIntegrationService.updateShippingAddress(c)]):[3,6];case 4:return o.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:o.sent(),o.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return o.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,t.orderID)];case 8:return o.sent(),r&&"function"==typeof r&&r(),[2,!0];case 9:throw d=o.sent(),new Error(d);case 10:return[2]}}))}))},t.prototype.onShippingAddressChange=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:e=this.paypalCommerceIntegrationService.getAddress({city:t.shippingAddress.city,countryCode:t.shippingAddress.country_code,postalCode:t.shippingAddress.postal_code,stateOrProvinceCode:t.shippingAddress.state}),i.label=1;case 1:return i.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(e)];case 2:return i.sent(),[4,this.paymentIntegrationService.updateShippingAddress(e)];case 3:return i.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return i.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return i.sent(),[3,7];case 6:throw r=i.sent(),new Error(r);case 7:return[2]}}))}))},t.prototype.onShippingOptionsChange=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(t.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(e.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:throw n=r.sent(),new Error(n);case 5:return[2]}}))}))},t}(),ku=Xa((function(t){return new Ru(t,xu(t))}),[{id:"paypalcommerce"}]),Mu=function(){function t(t,e){this.paymentIntegrationService=t,this.paypalCommerceIntegrationService=e}return t.prototype.initialize=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n,r,i,a,u,s,c,d;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(e=t.paypalcommercecredit,n=t.containerId,r=t.methodId,a=(i=e||{}).buyNowInitializeOptions,u=i.currencyCode,s=i.messagingContainerId,c=!!a,!r)throw new za('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new za('Unable to initialize payment because "options.containerId" argument is not provided.');if(!e)throw new za('Unable to initialize payment because "options.paypalcommercecredit" argument is not provided.');if(c&&!u)throw new za('Unable to initialize payment because "options.paypalcommercecredit.currencyCode" argument is not provided.');if(c&&"function"!=typeof(null==a?void 0:a.getBuyNowCartRequestBody))throw new za('Unable to initialize payment because "options.paypalcommercecredit.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');return c?[3,2]:[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:o.sent(),o.label=2;case 2:return d=c?u:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,[4,this.paypalCommerceIntegrationService.loadPayPalSdk(r,d,!1)];case 3:return o.sent(),this.renderButton(n,r,e),this.renderMessages(s),[2]}}))}))},t.prototype.deinitialize=function(){return Promise.resolve()},t.prototype.renderButton=function(t,e,n){var r=this,i=n.buyNowInitializeOptions,a=n.style,u=n.onComplete,s=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),c=(this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData||{}).isHostedCheckoutEnabled,d={createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommercecredit")},onApprove:function(t){var n=t.orderID;return r.paypalCommerceIntegrationService.tokenizePayment(e,n)}},l={onClick:function(){return r.handleClick(i)},onCancel:function(){return r.paymentIntegrationService.loadDefaultCheckout()}},f={onShippingAddressChange:function(t){return r.onShippingAddressChange(t)},onShippingOptionsChange:function(t){return r.onShippingOptionsChange(t)},onApprove:function(t,n){return r.onHostedCheckoutApprove(t,n,e,u)}},p=[s.FUNDING.PAYLATER,s.FUNDING.CREDIT],h=!1;p.forEach((function(e){if(!h){var n=(0,o.__assign)((0,o.__assign)((0,o.__assign)({fundingSource:e,style:r.paypalCommerceIntegrationService.getValidButtonStyle(a)},d),i&&l),c&&f),u=s.Buttons(n);u.isEligible()&&(u.render("#"+t),h=!0)}})),h||this.paypalCommerceIntegrationService.removeElement(t)},t.prototype.handleClick=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return t?[4,this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(t)]:[3,3];case 1:return e=n.sent(),[4,this.paymentIntegrationService.loadCheckout(e.id)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},t.prototype.onHostedCheckoutApprove=function(t,e,n,r){return(0,o.__awaiter)(this,void 0,void 0,(function(){var i,a,u,s,c,d;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(!t.orderID)throw new qa(Fa.MissingOrderId);return i=this.paymentIntegrationService.getState(),a=i.getCartOrThrow(),[4,e.order.get()];case 1:u=o.sent(),o.label=2;case 2:return o.trys.push([2,9,,10]),s=this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(u),[4,this.paymentIntegrationService.updateBillingAddress(s)];case 3:return o.sent(),a.lineItems.physicalItems.length>0?(c=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(u),[4,this.paymentIntegrationService.updateShippingAddress(c)]):[3,6];case 4:return o.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:o.sent(),o.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return o.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,t.orderID)];case 8:return o.sent(),r&&"function"==typeof r&&r(),[2,!0];case 9:throw d=o.sent(),new Error(d);case 10:return[2]}}))}))},t.prototype.onShippingAddressChange=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:e=this.paypalCommerceIntegrationService.getAddress({city:t.shippingAddress.city,countryCode:t.shippingAddress.country_code,postalCode:t.shippingAddress.postal_code,stateOrProvinceCode:t.shippingAddress.state}),i.label=1;case 1:return i.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(e)];case 2:return i.sent(),[4,this.paymentIntegrationService.updateShippingAddress(e)];case 3:return i.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return i.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return i.sent(),[3,7];case 6:throw r=i.sent(),new Error(r);case 7:return[2]}}))}))},t.prototype.onShippingOptionsChange=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n;return(0,o.__generator)(this,(function(r){switch(r.label){case 0:e=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(t.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(e.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:throw n=r.sent(),new Error(n);case 5:return[2]}}))}))},t.prototype.renderMessages=function(t){var e=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();if(t&&document.getElementById(t)){var n={amount:this.paymentIntegrationService.getState().getCartOrThrow().cartAmount,placement:"cart",style:{layout:"text"}};e.Messages(n).render("#"+t)}},t}(),Nu=Xa((function(t){return new Mu(t,xu(t))}),[{id:"paypalcommercecredit"}]),Du=function(){function t(t,e){this.paymentIntegrationService=t,this.paypalCommerceIntegrationService=e}return t.prototype.initialize=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n,r,i,a,u,s,c;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(e=t.paypalcommercevenmo,n=t.containerId,r=t.methodId,a=(i=e||{}).buyNowInitializeOptions,u=i.currencyCode,s=!!a,!r)throw new za('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new za('Unable to initialize payment because "options.containerId" argument is not provided.');if(!e)throw new za('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');if(s&&!u)throw new za('Unable to initialize payment because "options.paypalcommercevenmo.currencyCode" argument is not provided.');if(s&&"function"!=typeof(null==a?void 0:a.getBuyNowCartRequestBody))throw new za('Unable to initialize payment because "options.paypalcommercevenmo.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');return s?[3,2]:[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:o.sent(),o.label=2;case 2:return c=s?u:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,[4,this.paypalCommerceIntegrationService.loadPayPalSdk(r,c,!1)];case 3:return o.sent(),this.renderButton(n,r,e),[2]}}))}))},t.prototype.deinitialize=function(){return Promise.resolve()},t.prototype.renderButton=function(t,e,n){var r=this,i=n.buyNowInitializeOptions,a=n.style,u=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),s=u.FUNDING.VENMO,c={createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommercevenmo")},onApprove:function(t){var n=t.orderID;return r.paypalCommerceIntegrationService.tokenizePayment(e,n)}},d={onClick:function(){return r.handleClick(i)},onCancel:function(){return r.paymentIntegrationService.loadDefaultCheckout()}},l=(0,o.__assign)((0,o.__assign)({fundingSource:s,style:this.getValidVenmoButtonStyles(a)},c),i&&d),f=u.Buttons(l);f.isEligible()?f.render("#"+t):this.paypalCommerceIntegrationService.removeElement(t)},t.prototype.getValidVenmoButtonStyles=function(t){var e=this.paypalCommerceIntegrationService.getValidButtonStyle(t);return e.color===_u.gold?(0,o.__assign)((0,o.__assign)({},e),{color:void 0}):e},t.prototype.handleClick=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return t?[4,this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(t)]:[3,3];case 1:return e=n.sent(),[4,this.paymentIntegrationService.loadCheckout(e.id)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},t}(),Lu=Xa((function(t){return new Du(t,xu(t))}),[{id:"paypalcommercevenmo"}]),zu=function(){function t(t,e){this.paymentIntegrationService=t,this.paypalCommerceIntegrationService=e}return t.prototype.initialize=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n,r,i,a,u,s,c,d;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(e=t.paypalcommercealternativemethods,n=t.containerId,r=t.methodId,a=(i=e||{}).apm,u=i.buyNowInitializeOptions,s=i.currencyCode,c=!!u,!r)throw new za('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new za('Unable to initialize payment because "options.containerId" argument is not provided.');if(!e)throw new za('Unable to initialize payment because "options.paypalcommercealternativemethods" argument is not provided.');if(!a)throw new za('Unable to initialize payment because "options.paypalcommercealternativemethods.apm" argument is not provided.');if(c&&!s)throw new za('Unable to initialize payment because "options.paypalcommercealternativemethods.currencyCode" argument is not provided.');if(c&&"function"!=typeof(null==u?void 0:u.getBuyNowCartRequestBody))throw new za('Unable to initialize payment because "options.paypalcommercealternativemethods.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');return c?[3,2]:[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:o.sent(),o.label=2;case 2:return d=c?s:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,[4,this.paypalCommerceIntegrationService.loadPayPalSdk(r,d,!1)];case 3:return o.sent(),this.renderButton(n,r,e),[2]}}))}))},t.prototype.deinitialize=function(){return Promise.resolve()},t.prototype.renderButton=function(t,e,n){var r=this,i=n.apm,a=n.buyNowInitializeOptions,u=n.style,s=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();if(!Object.values(s.FUNDING).includes(i))throw new za('Unable to initialize PayPal button because "options.paypalcommercealternativemethods.apm" argument is not valid funding source.');var c={createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommercealternativemethod")},onApprove:function(t){var n=t.orderID;return r.paypalCommerceIntegrationService.tokenizePayment(e,n)}},d={onClick:function(){return r.handleClick(a)},onCancel:function(){return r.paymentIntegrationService.loadDefaultCheckout()}},l=(0,o.__assign)((0,o.__assign)({fundingSource:i,style:this.paypalCommerceIntegrationService.getValidButtonStyle(u)},c),a&&d),f=s.Buttons(l);f.isEligible()?f.render("#"+t):this.paypalCommerceIntegrationService.removeElement(t)},t.prototype.handleClick=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return t?[4,this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(t)]:[3,3];case 1:return e=n.sent(),[4,this.paymentIntegrationService.loadCheckout(e.id)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},t}(),ju=Xa((function(t){return new zu(t,xu(t))}),[{id:"paypalcommercealternativemethods"}]);var Uu,Fu,qu,Bu,Gu;!function(t){t.HORIZONTAL="horizontal",t.VERTICAL="vertical"}(Uu||(Uu={})),function(t){t.SMALL="small",t.MEDIUM="medium",t.LARGE="large",t.RESPONSIVE="responsive"}(Fu||(Fu={})),function(t){t.GOLD="gold",t.BLUE="blue",t.SIlVER="silver",t.BLACK="black"}(qu||(qu={})),function(t){t.CHECKOUT="checkout",t.PAY="pay",t.BUYNOW="buynow",t.PAYPAL="paypal",t.CREDIT="credit"}(Bu||(Bu={})),function(t){t.PILL="pill",t.RECT="rect"}(Gu||(Gu={}));const Vu=function(){function t(t,e,n){this.paymentIntegrationService=t,this.paypalExpressScriptLoader=e,this.formPoster=n}return t.prototype.initialize=function(t){return(0,o.__awaiter)(this,void 0,void 0,(function(){var e,n,r;return(0,o.__generator)(this,(function(i){switch(i.label){case 0:if(e=this.paymentIntegrationService.getState(),n=e.getPaymentMethodOrThrow(t.methodId),!t.paypal)throw new za;if(!n.config.merchantId)throw new qa(Fa.MissingPaymentMethod);return[4,this.paypalExpressScriptLoader.loadPaypalSDK(n.config.merchantId)];case 1:return r=i.sent(),this.renderButton(t,r),[2]}}))}))},t.prototype.deinitialize=function(){return Promise.resolve()},t.prototype.renderButton=function(t,e){var n,r=this,i=t.containerId,o=t.methodId,a=t.paypal,u=a.allowCredit,s=a.clientId,c=a.onPaymentError,d=a.shouldProcessPayment,l=a.style,f=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t.methodId);if(!f.config.merchantId)throw new qa(Fa.MissingPaymentMethod);var p=f.config.merchantId,h=f.config.testMode?"sandbox":"production",y=((n={})[h]=s,n),m=e.FUNDING.CREDIT||"credit",v=u?[m]:[],g=u?[]:[m];return e.Button.render({env:h,client:y,commit:d,funding:{allowed:v,disallowed:g},style:this.getStyle(l),payment:function(t,e){return r.setupPayment(p,e,c)},onAuthorize:function(t,e){return r.tokenizePayment(t,o,e,d)}},i)},t.prototype.getStyle=function(t){var e=t||{},n=e.color,r=e.fundingicons,i=e.label,o=e.layout,a=e.shape,u=e.size,s=e.tagline;return{color:n,fundingicons:r,label:i,layout:o,shape:a||Gu.RECT,size:"small"===u?Fu.RESPONSIVE:u,tagline:s}},t.prototype.setupPayment=function(t,e,n){return(0,o.__awaiter)(this,void 0,void 0,(function(){var r,i,a,u;return(0,o.__generator)(this,(function(s){switch(s.label){case 0:if(!e)throw new Ua(ja.CheckoutButtonNotInitialized);s.label=1;case 1:return s.trys.push([1,4,,5]),[4,this.paymentIntegrationService.loadDefaultCheckout()];case 2:return r=s.sent(),i=r.getCartOrThrow().id,a=r.getHost()||"",[4,e.request.post(a+"/api/storefront/payment/paypalexpress",{merchantId:t,cartId:i},{headers:(0,o.__assign)({"X-API-INTERNAL":Iu},Au)})];case 3:return[2,s.sent().id];case 4:throw u=s.sent(),n&&n(u),u;case 5:return[2]}}))}))},t.prototype.tokenizePayment=function(t,e,n,r){return(0,o.__awaiter)(this,void 0,void 0,(function(){var i,a,u;return(0,o.__generator)(this,(function(o){switch(o.label){case 0:if(!n)throw new Ua(ja.CheckoutButtonNotInitialized);if(!t.paymentID||!t.payerID)throw new qa(Fa.MissingPayment);return i=this.paymentIntegrationService.getState(),a=i.getPaymentMethodOrThrow(e),[4,n.payment.get(t.paymentID)];case 1:return u=o.sent(),[2,this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:a.id,action:r?"process_payment":"set_external_checkout",paymentId:t.paymentID,payerId:t.payerID,payerInfo:JSON.stringify(u.payer.payer_info)})]}}))}))},t}();const Yu=function(){function t(t){this.scriptLoader=t,this.window=window}return t.prototype.loadPaypalSDK=function(t){return void 0===t&&(t=""),(0,o.__awaiter)(this,void 0,void 0,(function(){var e;return(0,o.__generator)(this,(function(n){switch(n.label){case 0:return e=(0,o.__assign)({async:!0,attributes:{"data-merchant-id":t}},t&&{attributes:{"data-merchant-id":t}}),[4,this.scriptLoader.loadScript("//www.paypalobjects.com/api/checkout.min.js",e)];case 1:if(n.sent(),!this.window.paypal)throw new pu;return[2,this.window.paypal]}}))}))},t}(),Hu=Xa((function(t){return new Vu(t,new Yu((0,ar.Vr)()),(0,i.createFormPoster)())}),[{id:"paypalexpress"}]);function Wu(n){var r=null!=n?n:{},o=r.host,a=r.locale,u=void 0===a?"en":a,s=$n(),c=(0,e.createRequestSender)({host:o}),d=(0,i.createFormPoster)({host:o}),l=function(e,n){void 0===n&&(n=t);for(var r=new Qa,i=function(t){if(!function(t){return"resolveIds"in t}(t))return"continue";for(var n=0,i=t.resolveIds;n{"use strict";var e={780:e=>{e.exports=require("iframe-resizer")},252:e=>{e.exports=require("iframe-resizer/js/iframeResizer.contentWindow")}},t={};function n(r){var i=t[r];if(void 0!==i)return i.exports;var o=t[r]={exports:{}};return e[r](o,o.exports,n),o.exports}n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var r={};(()=>{n.r(r),n.d(r,{createBodlService:()=>rg,createCheckoutButtonInitializer:()=>lf,createCheckoutService:()=>iy,createCurrencyService:()=>qf,createEmbeddedCheckoutMessenger:()=>Tf,createLanguageService:()=>Ff,createStepTracker:()=>Qf,createTimeout:()=>o.createTimeout,embedCheckout:()=>bf});var e={};n.r(e),n.d(e,{createApplePayCustomerStrategy:()=>Ie,createBoltCustomerStrategy:()=>Ue,createBraintreePaypalCustomerStrategy:()=>nt,createPayPalCommerceCreditCustomerStrategy:()=>At,createPayPalCommerceCustomerStrategy:()=>bt,createPayPalCommerceVenmoCustomerStrategy:()=>Tt});var t={};n.r(t),n.d(t,{createAdyenV2PaymentStrategy:()=>Ta,createAdyenV3PaymentStrategy:()=>Va,createApplePayPaymentStrategy:()=>ja,createBlueSnapDirectAPMPaymentStrategy:()=>bs,createBlueSnapDirectCreditCardPaymentStrategy:()=>gs,createBlueSnapDirectEcpPaymentStrategy:()=>Cs,createBoltPaymentStrategy:()=>Rs,createBraintreeLocalMethodsPaymentStrategy:()=>Hs,createBraintreePaypalAchPaymentStrategy:()=>Fs,createCreditCardPaymentStrategy:()=>Ws,createExternalPaymentStrategy:()=>Zs,createLegacyPaymentStrategy:()=>$s,createNoPaymentStrategy:()=>nc,createOfflinePaymentStrategy:()=>oc,createOffsitePaymentStrategy:()=>dc,createPayPalCommerceAlternativeMethodsPaymentStrategy:()=>Ic,createPayPalCommerceCreditCardsPaymentStrategy:()=>Ac,createPayPalCommerceCreditPaymentStrategy:()=>yc,createPayPalCommercePaymentStrategy:()=>hc,createPayPalCommerceVenmoPaymentStrategy:()=>vc,createSezzlePaymentStrategy:()=>kc,createSquareV2PaymentStrategy:()=>Bc});var i={};n.r(i),n.d(i,{createApplePayButtonStrategy:()=>By,createBoltButtonStrategy:()=>qy,createPayPalCommerceAlternativeMethodsButtonStrategy:()=>$y,createPayPalCommerceButtonStrategy:()=>Hy,createPayPalCommerceCreditButtonStrategy:()=>Wy,createPayPalCommerceVenmoButtonStrategy:()=>Zy,createPaypalExpressButtonStrategy:()=>df});const o=require("@bigcommerce/request-sender"),a=require("@bigcommerce/script-loader"),s=require("tslib"),c=require("@bigcommerce/data-store"),u=require("rxjs"),d=require("rxjs/operators");function l(e,t,n){return(r=t)&&r.type&&r.error?(0,u.concat)((0,u.of)(t),(0,u.throwError)((0,c.createErrorAction)(e,t.payload,n))):(0,u.throwError)((0,c.createErrorAction)(e,t,n));var r}const p=function(e){function t(t){var n,r,i=this.constructor,o=e.call(this,t||"An unexpected error has occurred.")||this;return o.name="StandardError",o.type="standard",n=o,r=i.prototype,Object.setPrototypeOf?Object.setPrototypeOf(n,r):n.__proto__=r,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(o,i):o.stack=new Error(o.message).stack,o}return(0,s.__extends)(t,e),t}(Error);var h;!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"}(h||(h={}));const m=function(e){function t(t){var n=e.call(this,function(e){switch(e){case h.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case h.MissingCart:return"Unable to proceed because cart data is unavailable.";case h.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case h.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case h.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case h.MissingCheckoutConfig:case h.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case h.MissingOrder:return"Unable to proceed because order data is unavailable.";case h.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case h.MissingPayment:return"Unable to proceed because payment data is unavailable.";case h.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case h.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case h.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(t))||this;return n.subtype=t,n.name="MissingDataError",n.type="missing_data",n}return(0,s.__extends)(t,e),t}(p);var _;!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"}(_||(_={}));const y=function(e){function t(t){var n=e.call(this,t||"Unable to continue as a guest because the customer is already signed in.")||this;return n.name="UnableToContinueAsGuestError",n.type="unable_to_continue_as_guest",n}return(0,s.__extends)(t,e),t}(p);var f=function(){function e(e,t){this._requestSender=e,this._subscriptionActionCreator=t}return e.prototype.continueAsGuest=function(e,t){var n=this;return function(r){var i=r.getState(),o=i.checkout.getCheckout();if(!o)throw new m(h.MissingCheckout);var a=i.customer.getCustomer();if(a&&!a.isGuest)throw new y;var p,f=i.billingAddress.getBillingAddress();if(f){f.country;var g=(0,s.__rest)(f,["country"]);p=(0,s.__assign)((0,s.__assign)({},g),e)}else p=e;return(0,u.merge)((0,u.concat)((0,u.of)((0,c.createAction)(_.ContinueAsGuestRequested)),(0,u.defer)((function(){return(0,s.__awaiter)(n,void 0,void 0,(function(){var e;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return[4,this._createOrUpdateBillingAddress(o.id,p,t)];case 1:return e=n.sent().body,[2,(0,c.createAction)(_.ContinueAsGuestSucceeded,e)]}}))}))}))).pipe((0,d.catchError)((function(e){return l(_.ContinueAsGuestFailed,e)}))),n._updateCustomerConsent(e,t))}},e.prototype.updateAddress=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o=r.getState(),a=o.checkout.getCheckout();if(!a)throw new m(h.MissingCheckout);i.next((0,c.createAction)(_.UpdateBillingAddressRequested));var u=o.billingAddress.getBillingAddress(),d=(0,s.__assign)((0,s.__assign)({},e),{email:void 0===e.email&&u?u.email:e.email});u&&u.id&&(d.id=u.id),n._createOrUpdateBillingAddress(a.id,d,t).then((function(e){var t=e.body;i.next((0,c.createAction)(_.UpdateBillingAddressSucceeded,t)),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(_.UpdateBillingAddressFailed,e))}))}))}},e.prototype._updateCustomerConsent=function(e,t){var n=e.email,r=e.acceptsAbandonedCartEmails,i=e.acceptsMarketingNewsletter;return null==r&&null==i?(0,u.empty)():this._subscriptionActionCreator.updateSubscriptions({email:n,acceptsMarketingNewsletter:i||!1,acceptsAbandonedCartEmails:r||!1},t)},e.prototype._createOrUpdateBillingAddress=function(e,t,n){return t.id?this._requestSender.updateAddress(e,t,n):this._requestSender.createAddress(e,t,n)},e}();const g=f;var v;!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(v||(v={}));const w=v;var C={"X-Checkout-SDK-Version":"1.398.1"},S={include:["cart.lineItems.physicalItems.options","cart.lineItems.digitalItems.options","customer","promotions.banners"].join(",")},I=function(){function e(e){this._requestSender=e}return e.prototype.createAddress=function(e,t,n){var r=(void 0===n?{}:n).timeout,i="/api/storefront/checkouts/"+e+"/billing-address",o=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.post(i,{body:t,params:S,headers:o,timeout:r})},e.prototype.updateAddress=function(e,t,n){var r=(void 0===n?{}:n).timeout,i=t.id,o=(0,s.__rest)(t,["id"]),a="/api/storefront/checkouts/"+e+"/billing-address/"+i,c=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.put(a,{params:S,body:o,headers:c,timeout:r})},e}();const b=I;var P;!function(e){e.ClearError="CLEAR_ERROR"}(P||(P={}));const E=function(){function e(){}return e.prototype.clearError=function(e){return{type:P.ClearError,payload:e}},e}();function A(){try{return process.env.NODE_ENV||0}catch(e){return"development"}}var O=function(){function e(e){this._console=e}return e.prototype.log=function(){for(var e=[],t=0;t=400&&e.status<500)throw new q(e);throw e}))},e}();const H=G;var Y;!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"}(Y||(Y={}));var j=function(){function e(e){this._couponRequestSender=e}return e.prototype.applyCoupon=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o=r.getState().checkout.getCheckout();if(!o)throw new m(h.MissingCheckout);i.next((0,c.createAction)(Y.ApplyCouponRequested)),n._couponRequestSender.applyCoupon(o.id,e,t).then((function(e){var t=e.body;i.next((0,c.createAction)(Y.ApplyCouponSucceeded,t)),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(Y.ApplyCouponFailed,e))}))}))}},e.prototype.removeCoupon=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o=r.getState().checkout.getCheckout();if(!o)throw new m(h.MissingCheckout);i.next((0,c.createAction)(Y.RemoveCouponRequested)),n._couponRequestSender.removeCoupon(o.id,e,t).then((function(e){var t=e.body;i.next((0,c.createAction)(Y.RemoveCouponSucceeded,t)),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(Y.RemoveCouponFailed,e))}))}))}},e}();const W=j,K=["cart.lineItems.physicalItems.options","cart.lineItems.digitalItems.options","customer","customer.customerGroup","payments","promotions.banners"];var J;!function(e){e.AvailableShippingOptions="consignments.availableShippingOptions",e.PhysicalItemsCategoryNames="cart.lineItems.physicalItems.categoryNames",e.DigitalItemsCategoryNames="cart.lineItems.digitalItems.categoryNames"}(J||(J={}));const Z=require("lodash");function Q(e){return(0,Z.uniq)(e).join(",")}var X=function(){function e(e){this._requestSender=e}return e.prototype.applyCoupon=function(e,t,n){var r=(void 0===n?{}:n).timeout,i="/api/storefront/checkouts/"+e+"/coupons",o=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.post(i,{headers:o,timeout:r,params:{include:Q((0,s.__spreadArrays)(K,[J.AvailableShippingOptions]))},body:{couponCode:t}})},e.prototype.removeCoupon=function(e,t,n){var r=(void 0===n?{}:n).timeout,i="/api/storefront/checkouts/"+e+"/coupons/"+t,o=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.delete(i,{headers:o,timeout:r,params:{include:Q((0,s.__spreadArrays)(K,[J.AvailableShippingOptions]))}})},e}();const $=X;var ee;!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"}(ee||(ee={}));var te=function(){function e(e){this._giftCertificateRequestSender=e}return e.prototype.applyGiftCertificate=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o=r.getState().checkout.getCheckout();if(!o)throw new m(h.MissingCheckout);i.next((0,c.createAction)(ee.ApplyGiftCertificateRequested)),n._giftCertificateRequestSender.applyGiftCertificate(o.id,e,t).then((function(e){var t=e.body;i.next((0,c.createAction)(ee.ApplyGiftCertificateSucceeded,t)),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(ee.ApplyGiftCertificateFailed,e))}))}))}},e.prototype.removeGiftCertificate=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o=r.getState().checkout.getCheckout();if(!o)throw new m(h.MissingCheckout);i.next((0,c.createAction)(ee.RemoveGiftCertificateRequested)),n._giftCertificateRequestSender.removeGiftCertificate(o.id,e,t).then((function(e){var t=e.body;i.next((0,c.createAction)(ee.RemoveGiftCertificateSucceeded,t)),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(ee.RemoveGiftCertificateFailed,e))}))}))}},e}();const ne=te;var re=function(){function e(e){this._requestSender=e}return e.prototype.applyGiftCertificate=function(e,t,n){var r=(void 0===n?{}:n).timeout,i="/api/storefront/checkouts/"+e+"/gift-certificates",o=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.post(i,{headers:o,timeout:r,params:{include:Q(K)},body:{giftCertificateCode:t}})},e.prototype.removeGiftCertificate=function(e,t,n){var r=(void 0===n?{}:n).timeout,i="/api/storefront/checkouts/"+e+"/gift-certificates/"+t,o=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.delete(i,{headers:o,timeout:r,params:{include:Q(K)}})},e}();const ie=re;function oe(e){return"resolveIds"in e}const ae=function(e){function t(t){var n=e.call(this,t||"Invalid arguments have been provided.")||this;return n.name="InvalidArgumentError",n.type="invalid_argument",n}return(0,s.__extends)(t,e),t}(p);var se=function(){function e(e){var t,n,r;this._factories={},this._instances={},this._defaultToken=null!==(t=null==e?void 0:e.defaultToken)&&void 0!==t?t:"default",this._useFallback=null===(n=null==e?void 0:e.useFallback)||void 0===n||n,this._tokenResolver=null!==(r=null==e?void 0:e.tokenResolver)&&void 0!==r?r:function(e){return e}}return e.prototype.get=function(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)}},e.prototype.register=function(e,t){if(this._hasFactory(e))throw new ae("'"+e+"' is already registered.");this._factories[e]=t},e.prototype._hasFactory=function(e){return!!this._factories[e]},e.prototype._hasInstance=function(e){return!!this._instances[e]},e.prototype._getInstance=function(e,t){if(!this._hasInstance(t)){var n=this._tokenResolver(e,Object.keys(this._factories)),r=n&&this._factories[n];if(!r)throw new ae("'"+e+"' is not registered.");this._instances[t]=r()}return this._instances[t]},e}();const ce=se;var ue=function(){function e(e){void 0===e&&(e=!1),this._useFallback=e,this._registry=new ce({tokenResolver:this._resolveToken.bind(this),useFallback:this._useFallback})}return e.prototype.get=function(e){return this._registry.get(this._encodeToken(e))},e.prototype.register=function(e,t){this._registry.register(this._encodeToken(e),t)},e.prototype._encodeToken=function(e){return btoa(JSON.stringify(e))},e.prototype._decodeToken=function(e){return JSON.parse(atob(e))},e.prototype._resolveToken=function(e,t){var n,r=this,i=this._decodeToken(e),o=[];t.forEach((function(e){for(var t=r._decodeToken(e),n={token:e,matches:0,default:!1},a=0,s=Object.entries(t);a0}));a.length>1&&a[0].matches===a[1].matches&&"development"===A()&&R().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.");var s=a[0];if(s&&s.token)return s.token;if(this._useFallback){var c=null===(n=o.find((function(e){return e.default})))||void 0===n?void 0:n.token;if(c)return c}throw new Error("Unable to resolve to a registered token with the provided token.")},e}();const de=ue;function le(e,t){return Object.assign(e,{resolveIds:t})}const pe=function(e){function t(t){var n,r,i=this.constructor,o=e.call(this,t||"An unexpected error has occurred.")||this;return o.name="StandardError",o.type="standard",n=o,r=i.prototype,Object.setPrototypeOf?Object.setPrototypeOf(n,r):n.__proto__=r,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(o,i):o.stack=new Error(o.message).stack,o}return(0,s.__extends)(t,e),t}(Error);var he;!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"}(he||(he={}));const me=function(e){function t(t){var n=e.call(this,function(e){switch(e){case he.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case he.MissingCart:return"Unable to proceed because cart data is unavailable.";case he.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case he.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case he.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case he.MissingCheckoutConfig:case he.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case he.MissingOrder:return"Unable to proceed because order data is unavailable.";case he.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case he.MissingPayment:return"Unable to proceed because payment data is unavailable.";case he.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case he.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case he.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(t))||this;return n.subtype=t,n.name="MissingDataError",n.type="missing_data",n}return(0,s.__extends)(t,e),t}(pe),_e=function(e){function t(t){var n=e.call(this,t||"Not implemented.")||this;return n.name="NotImplementedError",n.type="not_implemented",n}return(0,s.__extends)(t,e),t}(pe);const ye=function(e){function t(t){var n=e.call(this,t||"Invalid arguments have been provided.")||this;return n.name="InvalidArgumentError",n.type="invalid_argument",n}return(0,s.__extends)(t,e),t}(pe),fe=function(e){function t(t){var n=e.call(this,t||"Payment process was cancelled.")||this;return n.name="PaymentMethodCancelledError",n.type="payment_cancelled",n}return(0,s.__extends)(t,e),t}(pe);function ge(e){if(!function(e){return"ApplePaySession"in e}(e))throw new Error("Apple pay is not supported")}const ve=function(){function e(){}return e.prototype.create=function(e){return ge(window),new ApplePaySession(1,e)},e}();var we;!function(e){e.Subtotal="Subtotal",e.Shipping="Shipping"}(we||(we={}));var Ce=function(){function e(e,t,n){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=n,this._onAuthorizeCallback=Z.noop,this._onError=Z.noop,this._subTotalLabel=we.Subtotal,this._shippingLabel=we.Shipping}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.methodId,n=e.applepay,ge(window),!t||!n)throw new me(he.MissingPaymentMethod);return r=n.container,i=n.shippingLabel,o=n.subtotalLabel,a=n.onError,c=void 0===a?Z.noop:a,u=n.onPaymentAuthorize,this._shippingLabel=i||we.Shipping,this._subTotalLabel=o||we.Subtotal,this._onAuthorizeCallback=u,this._onError=c,[4,this._paymentIntegrationService.loadPaymentMethod(t)];case 1:return s.sent(),d=this._paymentIntegrationService.getState(),this._paymentMethod=d.getPaymentMethodOrThrow(t),[4,this._paymentIntegrationService.verifyCheckoutSpamProtection()];case 2:return s.sent(),this._applePayButton=this._createButton(r),this._applePayButton.addEventListener("click",this._handleWalletButtonClick.bind(this)),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.signIn=function(){throw new _e('In order to sign in via Apple, the shopper must click on "Apple Pay" button.')},e.prototype.signOut=function(){throw new _e("Need to do signout via apple.")},e.prototype.executePaymentMethodCheckout=function(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()},e.prototype._createButton=function(e){var t=document.getElementById(e);if(!t)throw new ye("Unable to create sign-in button without valid container ID.");var n=document.createElement("button");return n.setAttribute("type","button"),n.setAttribute("aria-label","Apple Pay"),t.appendChild(n),n},e.prototype._handleWalletButtonClick=function(e){e.preventDefault();var t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow(),r=t.getStoreConfigOrThrow(),i=t.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new me(he.MissingPaymentMethod);var o=this._getBaseRequest(n,i,r,this._paymentMethod),a=this._sessionFactory.create(o);this._handleApplePayEvents(a,this._paymentMethod,r),a.begin()},e.prototype._getBaseRequest=function(e,t,n,r){var i,o=n.storeProfile,a=o.storeCountryCode,s=o.storeName,c=e.currency,u=c.code,d=c.decimalPlaces,l=r.initializationData,p=l.merchantCapabilities,h=l.supportedNetworks,m=e.lineItems.physicalItems.length>0,_={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:a,currencyCode:u,merchantCapabilities:p,supportedNetworks:h,lineItems:[],total:m?{label:s,amount:""+t.grandTotal.toFixed(d),type:"pending"}:{label:s,amount:""+t.grandTotal.toFixed(d),type:"final"}};if(m)null===(i=_.requiredShippingContactFields)||void 0===i||i.push("postalAddress");else{var y=[{label:this._subTotalLabel,amount:""+t.subtotal.toFixed(d)}];t.taxes.forEach((function(e){return y.push({label:e.name,amount:""+e.amount.toFixed(d)})})),_.lineItems=y}return _},e.prototype._handleApplePayEvents=function(e,t,n){var r=this;e.onvalidatemerchant=function(n){return(0,s.__awaiter)(r,void 0,void 0,(function(){var r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),[4,this._onValidateMerchant(t,n)];case 1:return r=o.sent().body,e.completeMerchantValidation(r),[3,3];case 2:return i=o.sent(),this._onError(i),[3,3];case 3:return[2]}}))}))},e.onshippingcontactselected=function(t){return(0,s.__awaiter)(r,void 0,void 0,(function(){return(0,s.__generator)(this,(function(r){return[2,this._handleShippingContactSelected(e,n,t)]}))}))},e.onshippingmethodselected=function(t){return(0,s.__awaiter)(r,void 0,void 0,(function(){return(0,s.__generator)(this,(function(r){return[2,this._handleShippingMethodSelected(e,n,t)]}))}))},e.oncancel=function(){return(0,s.__awaiter)(r,void 0,void 0,(function(){var e;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return n.trys.push([0,3,,4]),e="/remote-checkout/"+t.id+"/signout",[4,this._requestSender.get(e)];case 1:return n.sent(),[4,this._paymentIntegrationService.loadCheckout()];case 2:return[2,n.sent()];case 3:return n.sent(),[2,this._onError(new fe)];case 4:return[2]}}))}))},e.onpaymentauthorized=function(n){return(0,s.__awaiter)(r,void 0,void 0,(function(){return(0,s.__generator)(this,(function(r){return[2,this._onPaymentAuthorized(n,e,t)]}))}))}},e.prototype._handleShippingContactSelected=function(e,t,n){var r;return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u,d,l,p,h,m,_,y,f,g,v;return(0,s.__generator)(this,(function(w){switch(w.label){case 0:i=this._transformContactToAddress(n.shippingContact),w.label=1;case 1:return w.trys.push([1,3,,4]),[4,this._paymentIntegrationService.updateShippingAddress(i)];case 2:return w.sent(),[3,4];case 3:return o=w.sent(),e.abort(),[2,this._onError(o)];case 4:if(a=t.storeProfile.storeName,c=this._paymentIntegrationService.getState(),u=c.getCartOrThrow().currency.decimalPlaces,d=c.getCheckoutOrThrow(),l=null===(r=d.consignments[0].selectedShippingOption)||void 0===r?void 0:r.id,p=d.consignments[0].availableShippingOptions,h=null==p?void 0:p.find((function(e){return e.id===l})),m=null==p?void 0:p.filter((function(e){return e.id!==l})),_=h?[{label:h.description,amount:""+h.cost.toFixed(u),detail:h.additionalDescription,identifier:h.id}]:[],m&&(0,s.__spreadArrays)(m.filter((function(e){return e.isRecommended})),m.filter((function(e){return!e.isRecommended}))).forEach((function(e){return _.push({label:e.description,amount:""+e.cost.toFixed(u),detail:e.additionalDescription,identifier:e.id})})),!(p instanceof Array))throw new Error("Shipping options not available.");if(0===p.length)return e.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:a,amount:""+d.grandTotal.toFixed(u)},[]),[2];y=p.find((function(e){return e.isRecommended})),f=y?y.id:p[0].id,g=h?h.id:f,w.label=5;case 5:return w.trys.push([5,7,,8]),[4,this._updateShippingOption(g)];case 6:return w.sent(),[3,8];case 7:return v=w.sent(),[2,this._onError(v)];case 8:return c=this._paymentIntegrationService.getState(),d=c.getCheckoutOrThrow(),e.completeShippingContactSelection({newShippingMethods:_,newTotal:{type:"final",label:a,amount:""+d.grandTotal.toFixed(u)},newLineItems:this._getUpdatedLineItems(d,u)}),[2]}}))}))},e.prototype._handleShippingMethodSelected=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:r=t.storeProfile.storeName,i=n.shippingMethod.identifier,s.label=1;case 1:return s.trys.push([1,3,,4]),[4,this._updateShippingOption(i)];case 2:return s.sent(),[3,4];case 3:return o=s.sent(),e.abort(),[2,this._onError(o)];case 4:return a=this._paymentIntegrationService.getState(),c=a.getCartOrThrow().currency.decimalPlaces,u=a.getCheckoutOrThrow(),e.completeShippingMethodSelection({newTotal:{type:"final",label:r,amount:""+u.grandTotal.toFixed(c)},newLineItems:this._getUpdatedLineItems(u,c)}),[2]}}))}))},e.prototype._getUpdatedLineItems=function(e,t){var n=[{label:this._subTotalLabel,amount:""+e.subtotal.toFixed(t)}];return e.taxes.forEach((function(e){return n.push({label:e.name,amount:""+e.amount.toFixed(t)})})),n.push({label:this._shippingLabel,amount:""+e.shippingCostTotal.toFixed(t)}),n},e.prototype._updateShippingOption=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){return[2,this._paymentIntegrationService.selectShippingOption(e)]}))}))},e.prototype._onValidateMerchant=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n;return(0,s.__generator)(this,(function(r){return n=["validationUrl="+t.validationURL,"merchantIdentifier="+e.initializationData.merchantId,"displayName="+e.initializationData.storeName,"domainName="+window.location.hostname].join("&"),[2,this._requestSender.post((i=e.initializationData.paymentsUrl,i+"/api/public/v1/payments/applepay/validate_merchant"),{credentials:!1,headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","X-XSRF-TOKEN":null},body:n})];var i}))}))},e.prototype._onPaymentAuthorized=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d,l,p,h,m,_,y;return(0,s.__generator)(this,(function(f){switch(f.label){case 0:r=e.payment,i=r.token,o=r.billingContact,a=r.shippingContact,c=this._paymentIntegrationService.getState(),u=c.getCartOrThrow(),d=u.lineItems.physicalItems.length>0,l={methodId:n.id,paymentData:{formattedPayload:{apple_pay_token:{payment_data:i.paymentData,payment_method:i.paymentMethod,transaction_id:i.transactionIdentifier}}}},p=this._transformContactToAddress(o),h=this._transformContactToAddress(a),m=null==a?void 0:a.emailAddress,_=(null==a?void 0:a.phoneNumber)||"",f.label=1;case 1:return f.trys.push([1,7,,8]),[4,this._paymentIntegrationService.updateBillingAddress((0,s.__assign)((0,s.__assign)({},p),{email:m,phone:_}))];case 2:return f.sent(),d?[4,this._paymentIntegrationService.updateShippingAddress(h)]:[3,4];case 3:f.sent(),f.label=4;case 4:return[4,this._paymentIntegrationService.submitOrder({useStoreCredit:!1})];case 5:return f.sent(),[4,this._paymentIntegrationService.submitPayment(l)];case 6:return f.sent(),t.completePayment(ApplePaySession.STATUS_SUCCESS),[2,this._onAuthorizeCallback()];case 7:return y=f.sent(),t.completePayment(ApplePaySession.STATUS_FAILURE),[2,this._onError(y)];case 8:return[2]}}))}))},e.prototype._transformContactToAddress=function(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:[]}},e}();const Se=Ce,Ie=le((function(e){var t=e.getState().getHost;return new Se((0,o.createRequestSender)({host:t()}),e,new ve)}),[{id:"applepay"}]),be=function(e){function t(t){var n=e.call(this,t||"Unable to proceed because the client library of a payment method has thrown an unexpected error.")||this;return n.name="PaymentMethodFailedError",n.type="payment_method_client_invalid",n}return(0,s.__extends)(t,e),t}(pe);var Pe;!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"}(Pe||(Pe={}));const Ee=function(e){function t(t){var n=e.call(this,function(e){switch(e){case Pe.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case Pe.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case Pe.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case Pe.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."}}(t))||this;return n.subtype=t,n.name="NotInitializedError",n.type="not_initialized",n}return(0,s.__extends)(t,e),t}(pe);var Ae={body:{},headers:{},status:0},Oe=function(e){function t(t,n){var r=void 0===n?{}:n,i=r.message,o=r.errors,a=this,s=t||Ae,c=s.body,u=s.headers,d=s.status;return(a=e.call(this,i||"An unexpected error has occurred.")||this).name="RequestError",a.type="request",a.body=c,a.headers=u,a.status=d,a.errors=o||[],a}return(0,s.__extends)(t,e),t}(pe);const ke=Oe,Te=function(e){function t(t){var n=e.call(this,t,{message:"There is a problem processing your payment. Please try again later."})||this;return n.name="PaymentMethodInvalidError",n.type="payment_method_invalid",n}return(0,s.__extends)(t,e),t}(ke);var Me=function(){function e(e,t){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.boltHostWindow=window}return e.prototype.initialize=function(e){var t;return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d,l;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(n=e.methodId,r=e.bolt,i=(r||{}).onInit,!n)throw new ye('Unable to proceed because "methodId" argument is not provided.');return[4,this.paymentIntegrationService.loadPaymentMethod(n)];case 1:if(s.sent(),o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n),!(null===(t=o.initializationData)||void 0===t?void 0:t.publishableKey))throw new me(he.MissingPaymentMethod);return a=o.initializationData,c=a.developerConfig,u=a.publishableKey,[4,this.boltScriptLoader.loadBoltClient(u,o.config.testMode,c)];case 2:return s.sent(),i&&"function"==typeof i?(d=this.getCustomerEmail(),[4,this.hasBoltAccount(d)]):[3,4];case 3:l=s.sent(),i(l,d),s.label=4;case 4:return[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.signIn=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return[4,this.paymentIntegrationService.signInCustomer(e,t)];case 1:return n.sent(),[2,Promise.resolve()]}}))}))},e.prototype.signOut=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this.paymentIntegrationService.signOutCustomer(e)];case 1:return t.sent(),[2,Promise.resolve()]}}))}))},e.prototype.executePaymentMethodCheckout=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a;return(0,s.__generator)(this,(function(s){if(n=(t=e||{}).continueWithCheckoutCallback,r=void 0===n?u.noop:n,i=t.checkoutPaymentMethodExecuted,o=t.methodId,a=this.getCustomerEmail(),!o)throw new ye('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof r)throw new ye('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');return a?[2,this.openBoltCheckoutModalOrThrow(a,o,r,i)]:(r(),[2])}))}))},e.prototype.openBoltCheckoutModalOrThrow=function(e,t,n,r){var i;return(0,s.__awaiter)(this,void 0,void 0,(function(){var o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:o=this.getBoltClientOrThrow(),a=this.paymentIntegrationService.getState().getPaymentMethod(t),s.label=1;case 1:return s.trys.push([1,8,,9]),(null===(i=null==a?void 0:a.initializationData)||void 0===i?void 0:i.embeddedOneClickEnabled)?[4,this.hasBoltAccount(e)]:[3,6];case 2:return(c=s.sent())?(u={close:function(){n()}},[4,o.openCheckout(e,u)]):[3,4];case 3:return s.sent(),[3,5];case 4:n(),s.label=5;case 5:return"function"==typeof r&&r({hasBoltAccount:c}),[3,7];case 6:n(),s.label=7;case 7:return[3,9];case 8:if("string"==typeof(l=d=s.sent()).message&&"string"==typeof l.type&&("string"==typeof l.subtype||!l.subtype)&&l instanceof Error&&"MissingDataError"!==d.name&&"NotInitializedError"!==d.name)throw new be(d.message);throw d;case 9:return[2]}var l}))}))},e.prototype.getBoltClientOrThrow=function(){var e=this.boltHostWindow.BoltCheckout;if(!e)throw new Ee(Pe.PaymentNotInitialized);return e},e.prototype.hasBoltAccount=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:t=this.getBoltClientOrThrow(),n.label=1;case 1:return n.trys.push([1,3,,4]),[4,t.hasBoltAccount(e)];case 2:return[2,n.sent()];case 3:throw n.sent(),new Te;case 4:return[2]}}))}))},e.prototype.getCustomerEmail=function(){var e=this.paymentIntegrationService.getState(),t=e.getCustomer(),n=e.getBillingAddress();return(null==t?void 0:t.email)||(null==n?void 0:n.email)||""},e}();const De=Me,Re=function(e){function t(t){var n=e.call(this,t||"Unable to proceed because the client library of a payment method is not loaded or ready to be used.")||this;return n.name="PaymentMethodClientUnavailableError",n.type="payment_method_client_unavailable",n}return(0,s.__extends)(t,e),t}(pe);var ze,Ne,Le;!function(e){e.SandboxMode="bolt_sandbox",e.StagingMode="bolt_staging",e.DevelopmentMode="bolt_development"}(ze||(ze={})),function(e){e.Small="small",e.Medium="medium",e.Large="large"}(Ne||(Ne={})),function(e){e.Pill="pill",e.Rect="rect"}(Le||(Le={}));var Fe=function(){function e(e,t){void 0===t&&(t=window),this.scriptLoader=e,this.boltHostWindow=t}return e.prototype.loadBoltClient=function(e,t,n,r,i){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(this.boltHostWindow.BoltCheckout)return[2,this.boltHostWindow.BoltCheckout];if(!e)throw new ye('Unable to initialize payment because "publishableKey" argument is not provided.');return[4,this.scriptLoader.loadScript("//"+this.getDomainURL(!!t,n)+"/connect-bigcommerce.js",this.getScriptOptions("bolt-connect",e,r,i))];case 1:return o.sent(),[4,this.scriptLoader.loadScript("//"+this.getDomainURL(!!t,n)+"/track.js",this.getScriptOptions("bolt-track",e))];case 2:if(o.sent(),!this.boltHostWindow.BoltCheckout)throw new Re;return[2,this.boltHostWindow.BoltCheckout]}}))}))},e.prototype.loadBoltEmbedded=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return r={async:!0,attributes:{id:"bolt-embedded"}},[4,this.scriptLoader.loadScript("//"+this.getDomainURL(!!t,n)+"/embed.js",r)];case 1:if(i.sent(),!this.boltHostWindow.Bolt)throw new Re;return[2,this.boltHostWindow.Bolt(e)]}}))}))},e.prototype.getDomainURL=function(e,t){if(!e)return"connect.bolt.com";if(t)switch(t.developerMode){case ze.StagingMode:return"connect-staging.bolt.com";case ze.DevelopmentMode:return"connect."+t.developerDomain}return"connect-sandbox.bolt.com"},e.prototype.getScriptOptions=function(e,t,n,r){return{async:!0,attributes:(0,s.__assign)((0,s.__assign)({id:e,"data-publishable-key":t},n&&{"data-shopping-cart-id":n}),r&&{"data-storefront-api-token":r})}},e}();const Be=Fe,Ue=le((function(e){return new De(e,new Be((0,a.getScriptLoader)()))}),[{id:"bolt"}]),xe=require("@bigcommerce/form-poster");var qe;function Ve(e){return Boolean("object"==typeof e&&null!==e&&("type"in e||"message"in e||"code"in e))}!function(e){e.Sandbox="sandbox",e.Production="production"}(qe||(qe={}));var Ge,He,Ye,je,We,Ke=["buttons","messages"];!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(Ge||(Ge={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(He||(He={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black"}(Ye||(Ye={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(je||(je={})),function(e){e.PILL="pill",e.RECT="rect"}(We||(We={}));var Je=function(){function e(e,t){this.braintreeScriptLoader=e,this.braintreeHostWindow=t,this.dataCollectors={}}return e.prototype.initialize=function(e){this.clientToken=e},e.prototype.getClient=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){var e;return(0,s.__generator)(this,(function(t){switch(t.label){case 0:if(!this.clientToken)throw new Ee(Pe.PaymentNotInitialized);return this.client?[3,2]:[4,this.braintreeScriptLoader.loadClient()];case 1:e=t.sent(),this.client=e.create({authorization:this.clientToken}),t.label=2;case 2:return[2,this.client]}}))}))},e.prototype.getPaypalCheckout=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u=this;return(0,s.__generator)(this,(function(d){switch(d.label){case 0:return[4,this.getClient()];case 1:return r=d.sent(),[4,this.braintreeScriptLoader.loadPaypalCheckout()];case 2:return i=d.sent(),o={client:r},a=function(r,i){if(r)return n(r);var o=(0,s.__assign)((0,s.__assign)({currency:e.currency},e.isCreditEnabled&&{"enable-funding":"paylater"}),{components:Ke.toString(),intent:e.intent});u.braintreeHostWindow.paypal?t(i):i.loadPayPalSDK(o,(function(){return t(i)}))},c=this,[4,i.create(o,a)];case 3:return c.paypalCheckout=d.sent(),[2,this.paypalCheckout]}}))}))},e.prototype.loadBraintreeLocalMethods=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return[4,this.getClient()];case 1:return n=i.sent(),[4,this.braintreeScriptLoader.loadBraintreeLocalMethods()];case 2:return r=i.sent(),this.braintreeLocalMethods||(this.braintreeLocalMethods=r.create({client:n,merchantAccountId:t},(function(t,n){if(t)throw new Error(t);e(n)}))),[2,this.braintreeLocalMethods]}}))}))},e.prototype.getUsBankAccount=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){var e,t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return this.usBankAccount?[3,3]:[4,this.getClient()];case 1:return e=n.sent(),[4,this.braintreeScriptLoader.loadUsBankAccount()];case 2:t=n.sent(),this.usBankAccount=t.create({client:e}),n.label=3;case 3:return[2,this.usBankAccount]}}))}))},e.prototype.getDataCollector=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(t=(null==e?void 0:e.paypal)?"paypal":"default",n=this.dataCollectors[t])return[3,7];o.label=1;case 1:return o.trys.push([1,5,,6]),[4,this.getClient()];case 2:return r=o.sent(),[4,this.braintreeScriptLoader.loadDataCollector()];case 3:return[4,o.sent().create((0,s.__assign)({client:r,kount:!0},e))];case 4:return n=o.sent(),[3,6];case 5:if(!Ve(i=o.sent())||"DATA_COLLECTOR_KOUNT_NOT_ENABLED"!==i.code)throw i;return n={deviceData:void 0,teardown:function(){return Promise.resolve()}},[3,6];case 6:this.dataCollectors[t]=n,o.label=7;case 7:return[2,n]}}))}))},e.prototype.getBraintreeEnv=function(e){return void 0===e&&(e=!1),e?qe.Sandbox:qe.Production},e.prototype.mapToBraintreeShippingAddressOverride=function(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}},e.prototype.mapToLegacyShippingAddress=function(e){var t=e.email,n=e.phone,r=e.shippingAddress,i=((null==r?void 0:r.recipientName)||"").split(" ");return{email:t,first_name:i[0]||"",last_name:i[1]||"",phone_number:n,address_line_1:null==r?void 0:r.line1,address_line_2:null==r?void 0:r.line2,city:null==r?void 0:r.city,state:null==r?void 0:r.state,country_code:null==r?void 0:r.countryCode,postal_code:null==r?void 0:r.postalCode}},e.prototype.mapToLegacyBillingAddress=function(e){var t=e.billingAddress,n=e.email,r=e.firstName,i=e.lastName,o=e.phone,a=e.shippingAddress,s=t||a;return{email:n,first_name:r,last_name:i,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}},e.prototype.removeElement=function(e){var t=e&&document.getElementById(e);t&&t.remove()},e.prototype.getSessionId=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){switch(e.label){case 0:return[4,this.getDataCollector()];case 1:return[2,e.sent().deviceData]}}))}))},e.prototype.teardown=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){switch(e.label){case 0:return[4,this.teardownModule(this.dataCollectors.default)];case 1:return e.sent(),[4,this.teardownModule(this.dataCollectors.paypal)];case 2:return e.sent(),this.dataCollectors={},[4,this.teardownModule(this.paypalCheckout)];case 3:return e.sent(),this.paypalCheckout=void 0,[2]}}))}))},e.prototype.teardownModule=function(e){return e?e.teardown():Promise.resolve()},e}();const Ze=Je;var Qe="3.81.0",Xe=function(){function e(e,t){this.scriptLoader=e,this.braintreeHostWindow=t}return e.prototype.loadClient=function(){var e;return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this.scriptLoader.loadScript("//js.braintreegateway.com/web/"+Qe+"/js/client.min.js")];case 1:if(t.sent(),!(null===(e=this.braintreeHostWindow.braintree)||void 0===e?void 0:e.client))throw new Re;return[2,this.braintreeHostWindow.braintree.client]}}))}))},e.prototype.loadPaypalCheckout=function(){var e;return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this.scriptLoader.loadScript("//js.braintreegateway.com/web/"+Qe+"/js/paypal-checkout.min.js")];case 1:if(t.sent(),!(null===(e=this.braintreeHostWindow.braintree)||void 0===e?void 0:e.paypalCheckout))throw new Re;return[2,this.braintreeHostWindow.braintree.paypalCheckout]}}))}))},e.prototype.loadBraintreeLocalMethods=function(){var e;return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this.scriptLoader.loadScript("//js.braintreegateway.com/web/"+Qe+"/js/local-payment.min.js")];case 1:if(t.sent(),!(null===(e=this.braintreeHostWindow.braintree)||void 0===e?void 0:e.localPayment))throw new Re;return[2,this.braintreeHostWindow.braintree.localPayment]}}))}))},e.prototype.loadDataCollector=function(){var e;return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this.scriptLoader.loadScript("//js.braintreegateway.com/web/"+Qe+"/js/data-collector.min.js")];case 1:if(t.sent(),!(null===(e=this.braintreeHostWindow.braintree)||void 0===e?void 0:e.dataCollector))throw new Re;return[2,this.braintreeHostWindow.braintree.dataCollector]}}))}))},e.prototype.loadUsBankAccount=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){switch(e.label){case 0:return[4,this.scriptLoader.loadScript("//js.braintreegateway.com/web/"+Qe+"/js/us-bank-account.min.js")];case 1:if(e.sent(),!this.braintreeHostWindow.braintree||!this.braintreeHostWindow.braintree.usBankAccount)throw new Re;return[2,this.braintreeHostWindow.braintree.usBankAccount]}}))}))},e}();const $e=Xe;var et=function(){function e(e,t,n,r){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=n,this.braintreeHostWindow=r}return e.prototype.initialize=function(e){var t,n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d,l,p,h,m,_,y=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(r=e.braintreepaypal,i=e.methodId,a=(o=r||{}).container,c=o.buttonHeight,u=o.onError,!i)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new ye('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');if(!a)throw new ye('Unable to initialize payment because "options.braintreepaypal.container" argument is not provided.');return[4,this.paymentIntegrationService.loadPaymentMethod(i)];case 1:if(s.sent(),d=this.paymentIntegrationService.getState(),!(l=d.getPaymentMethodOrThrow(i)).clientToken)throw new me(he.MissingPaymentMethod);return p=d.getCartOrThrow().currency.code,h={currency:p,intent:null===(t=l.initializationData)||void 0===t?void 0:t.intent,isCreditEnabled:null===(n=l.initializationData)||void 0===n?void 0:n.isCreditEnabled},m=function(e){y.renderPayPalButton(e,r,a,i,Boolean(l.config.testMode),c)},_=function(e){return y.handleError(e,a,u)},this.braintreeIntegrationService.initialize(l.clientToken),[4,this.braintreeIntegrationService.getPaypalCheckout(h,m,_)];case 2:return s.sent(),[2]}}))}))},e.prototype.deinitialize=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){switch(e.label){case 0:return[4,this.braintreeIntegrationService.teardown()];case 1:return e.sent(),[2]}}))}))},e.prototype.signIn=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return[4,this.paymentIntegrationService.signInCustomer(e,t)];case 1:return n.sent(),[2]}}))}))},e.prototype.signOut=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this.paymentIntegrationService.signOutCustomer(e)];case 1:return t.sent(),[2]}}))}))},e.prototype.executePaymentMethodCheckout=function(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()},e.prototype.renderPayPalButton=function(e,t,n,r,i,o){var a=this;void 0===o&&(o=40);var s=this.braintreeHostWindow.paypal,c=null==s?void 0:s.FUNDING.PAYPAL;if(s&&c){var u=s.Buttons({env:this.braintreeIntegrationService.getBraintreeEnv(i),commit:!1,fundingSource:c,style:{height:o},createOrder:function(){return a.setupPayment(e,t,r)},onApprove:function(n){return a.tokenizePayment(n,e,r,t)}});u.isEligible()&&u.render("#"+n)}else this.braintreeIntegrationService.removeElement(n)},e.prototype.setupPayment=function(e,t,n){var r;return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u,d,l,p,h,m;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return s.trys.push([0,3,,4]),[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:return s.sent(),i=this.paymentIntegrationService.getState(),o=i.getCheckoutOrThrow().outstandingBalance,a=i.getCartOrThrow().currency.code,c=i.getCustomer(),u=i.getPaymentMethodOrThrow(n),d=null==c?void 0:c.addresses[0],l=d?this.braintreeIntegrationService.mapToBraintreeShippingAddressOverride(d):void 0,[4,e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:l,amount:o,currency:a,offerCredit:!1,intent:null===(r=u.initializationData)||void 0===r?void 0:r.intent})];case 2:return[2,s.sent()];case 3:return p=s.sent(),h=t.container,m=t.onError,this.handleError(p,h,m),[3,4];case 4:return[2]}}))}))},e.prototype.tokenizePayment=function(e,t,n,r){return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u,d,l,p,h;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return s.trys.push([0,3,,4]),[4,this.braintreeIntegrationService.getDataCollector({paypal:!0})];case 1:return i=s.sent().deviceData,[4,t.tokenizePayment(e)];case 2:return o=s.sent(),a=o.details,c=o.nonce,u=this.braintreeIntegrationService.mapToLegacyBillingAddress(a),d=this.braintreeIntegrationService.mapToLegacyShippingAddress(a),this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:n,action:"set_external_checkout",nonce:c,device_data:i,billing_address:JSON.stringify(u),shipping_address:JSON.stringify(d)}),[2,o];case 3:return l=s.sent(),p=r.container,h=r.onError,this.handleError(l,p,h),[3,4];case 4:return[2]}}))}))},e.prototype.handleError=function(e,t,n){if(this.braintreeIntegrationService.removeElement(t),!n||!Ve(e))throw e;n(e)},e}();const tt=et,nt=le((function(e){var t=window,n=new Ze(new $e((0,a.getScriptLoader)(),t),t);return new tt(e,(0,xe.createFormPoster)(),n,t)}),[{id:"braintreepaypal"}]),rt=function(e){function t(t){var n=e.call(this,t||"An unexpected error has occurred during buy now cart creation process. Please try again later.")||this;return n.name="BuyNowCartCreationError",n.type="buy_now_cart_creation_error",n}return(0,s.__extends)(t,e),t}(pe);var it,ot,at,st,ct,ut,dt;!function(e){e.BuyNow="BUY_NOW"}(it||(it={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(ot||(ot={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(at||(at={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(st||(st={})),function(e){e.pill="pill",e.rect="rect"}(ct||(ct={})),function(e){e.OXXO="oxxo"}(ut||(ut={})),function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED"}(dt||(dt={}));var lt=function(){function e(e,t,n,r){this.formPoster=e,this.paymentIntegrationService=t,this.paypalCommerceRequestSender=n,this.paypalCommerceScriptLoader=r}return e.prototype.loadPayPalSdk=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return r=this.paymentIntegrationService.getState(),i=t||r.getCartOrThrow().currency.code,o=r.getPaymentMethodOrThrow(e),a=this,[4,this.paypalCommerceScriptLoader.getPayPalSDK(o,i,n)];case 1:return a.paypalSdk=s.sent(),[2,this.paypalSdk]}}))}))},e.prototype.getPayPalSdkOrThrow=function(){if(!this.paypalSdk)throw new Re;return this.paypalSdk},e.prototype.createBuyNowCartOrThrow=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:if(!(t=e.getBuyNowCartRequestBody()))throw new me(he.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.paymentIntegrationService.createBuyNowCart(t)];case 2:return[2,n.sent()];case 3:throw n.sent(),new rt;case 4:return[2]}}))}))},e.prototype.createOrder=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return n=this.paymentIntegrationService.getState().getCartOrThrow().id,[4,this.paypalCommerceRequestSender.createOrder(e,(0,s.__assign)({cartId:n},t))];case 1:return[2,r.sent().orderId]}}))}))},e.prototype.updateOrder=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){var e,t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getConsignmentsOrThrow()[0],r.label=1;case 1:return r.trys.push([1,3,,4]),[4,this.paypalCommerceRequestSender.updateOrder({availableShippingOptions:n.availableShippingOptions,cartId:t.id,selectedShippingOption:n.selectedShippingOption})];case 2:return r.sent(),[3,4];case 3:throw r.sent(),new ke;case 4:return[2]}}))}))},e.prototype.getOrderStatus=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,this.paypalCommerceRequestSender.getOrderStatus()];case 1:return[2,e.sent().status];case 2:throw e.sent(),new ke;case 3:return[2]}}))}))},e.prototype.tokenizePayment=function(e,t){var n=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new me(he.MissingOrderId);return this.formPoster.postForm("/checkout.php",(0,s.__assign)({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},n.source===it.BuyNow&&{cart_id:n.id}))},e.prototype.submitPayment=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return n={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:e,paypal_account:{order_id:t}}},[4,this.paymentIntegrationService.submitPayment({methodId:e,paymentData:n})];case 1:return r.sent(),[2]}}))}))},e.prototype.getShippingOptionOrThrow=function(e){var t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],n=t.availableShippingOptions||[],r=n.find((function(e){return e.isRecommended})),i=e?n.find((function(t){return t.id===e})):n.find((function(e){var n;return e.id===(null===(n=t.selectedShippingOption)||void 0===n?void 0:n.id)})),o=i||r||n[0];if(!o)throw new Error("Your order can't be shipped to this address");return o},e.prototype.getAddress=function(e){return{firstName:(null==e?void 0:e.firstName)||"",lastName:(null==e?void 0:e.lastName)||"",email:(null==e?void 0:e.email)||"",phone:"",company:"",address1:(null==e?void 0:e.address1)||"",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:[]}},e.prototype.getBillingAddressFromOrderDetails=function(e){var t=e.payer;return this.getAddress({firstName:t.name.given_name,lastName:t.name.surname,email:t.email_address,address1:t.address.address_line_1,city:t.address.admin_area_2,countryCode:t.address.country_code,postalCode:t.address.postal_code,stateOrProvinceCode:t.address.admin_area_1})},e.prototype.getShippingAddressFromOrderDetails=function(e){var t,n,r=e.payer,i=(null===(n=null===(t=e.purchase_units[0])||void 0===t?void 0:t.shipping)||void 0===n?void 0:n.address)||{};return this.getAddress({firstName:r.name.given_name,lastName:r.name.surname,email:r.email_address,address1:i.address_line_1,city:i.admin_area_2,countryCode:i.country_code,postalCode:i.postal_code,stateOrProvinceCode:i.admin_area_1})},e.prototype.getValidButtonStyle=function(e){var t=e||{},n=t.color,r=t.height,i=t.label,o=t.shape,a={color:n&&st[n]?n:void 0,height:this.getValidHeight(r),label:i&&at[i]?i:void 0,shape:o&&ct[o]?o:void 0};return(0,Z.omitBy)(a,Z.isNil)},e.prototype.getValidHeight=function(e){return e&&"number"==typeof e?e>55?55:e<25?25:e:40},e.prototype.removeElement=function(e){var t=e&&document.getElementById(e);t&&t.remove()},e}();const pt=lt;var ht,mt="This API endpoint is for internal use only and may change in the future";!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(ht||(ht={}));const _t=ht;var yt={"X-Checkout-SDK-Version":"1.398.1"},ft=function(){function e(e){this.requestSender=e}return e.prototype.createOrder=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:return n="/api/storefront/payment/"+e,r=t,i=(0,s.__assign)({"X-API-INTERNAL":mt,"Content-Type":_t.Json},yt),[4,this.requestSender.post(n,{headers:i,body:r})];case 1:return[2,o.sent().body]}}))}))},e.prototype.updateOrder=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return t=e,n=(0,s.__assign)({"X-API-INTERNAL":mt,"Content-Type":_t.Json},yt),[4,this.requestSender.put("/api/storefront/initialization/paypalcommerce",{headers:n,body:t})];case 1:return[2,r.sent().body]}}))}))},e.prototype.getOrderStatus=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){var e;return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return e=(0,s.__assign)({"X-API-INTERNAL":mt,"Content-Type":_t.Json},yt),[4,this.requestSender.get("/api/storefront/initialization/paypalcommerce",{headers:e})];case 1:return[2,t.sent().body]}}))}))},e}();const gt=ft;var vt=function(){function e(e){this.scriptLoader=e,this.window=window}return e.prototype.getPayPalSDK=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return this.paypalSdk?[3,2]:(r=this,[4,this.loadPayPalSDK(this.getPayPalSdkScriptConfigOrThrow(e,t,n))]);case 1:r.paypalSdk=i.sent(),i.label=2;case 2:return[2,this.paypalSdk]}}))}))},e.prototype.loadPayPalSDK=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return this.window.paypalLoadScript?[3,2]:[4,this.scriptLoader.loadScript("https://unpkg.com/@paypal/paypal-js@5.0.5/dist/iife/paypal-js.min.js",{async:!0,attributes:{}})];case 1:if(t.sent(),!this.window.paypalLoadScript)throw new Re;t.label=2;case 2:return[4,this.window.paypalLoadScript(e)];case 3:if(t.sent(),!this.window.paypal)throw new Re;return[2,this.window.paypal]}}))}))},e.prototype.getPayPalSdkScriptConfigOrThrow=function(e,t,n){void 0===n&&(n=!0);var r=e.id,i=e.clientToken,o=e.initializationData;if(!(null==o?void 0:o.clientId))throw new me(he.MissingPaymentMethod);var a=o.intent,c=o.clientId,u=o.merchantId,d=o.buyerCountry,l=o.attributionId,p=o.isVenmoEnabled,h=o.isHostedCheckoutEnabled,m=o.isPayPalCreditAvailable,_=o.isDeveloperModeApplicable,y=o.availableAlternativePaymentMethods,f=void 0===y?[]:y,g=o.enabledAlternativePaymentMethods,v=void 0===g?[]:g,w=h||n,C="paypalcommercecreditcards"===r,S=C?["card"]:[],I=C?[]:["card"],b=m?["credit","paylater"]:[],P=m?[]:["credit","paylater"],E=n||!w,A=E&&p?["venmo"]:[],O=E&&p?[]:["venmo"],k=E?v:[],T=E?f.filter((function(e){return!v.includes(e)})):f,M=(0,s.__spreadArrays)(I,P,O,T),D=(0,s.__spreadArrays)(S,b,A,k);return(0,s.__assign)({"client-id":c,"data-partner-attribution-id":l,"data-client-token":i,"merchant-id":u,"enable-funding":D.length>0?D:void 0,"disable-funding":M.length>0?M:void 0,commit:w,components:["buttons","hosted-fields","messages","payment-fields"],currency:t,intent:a},_&&{"buyer-country":d})},e}();const wt=vt,Ct=function(e){var t=e.getState().getHost;return new pt((0,xe.createFormPoster)(),e,new gt((0,o.createRequestSender)({host:t()})),new wt((0,a.getScriptLoader)()))};var St=function(){function e(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.onError=Z.noop}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:if(t=e.paypalcommerce,!(n=e.methodId))throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new ye('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');if(!t.container)throw new ye('Unable to initialize payment because "options.paypalcommerce.container" argument is not provided.');return this.onError=t.onError||Z.noop,[4,this.paymentIntegrationService.loadPaymentMethod(n)];case 1:return r.sent(),[4,this.paypalCommerceIntegrationService.loadPayPalSdk(n)];case 2:return r.sent(),this.renderButton(n,t),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.signIn=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return[4,this.paymentIntegrationService.signInCustomer(e,t)];case 1:return n.sent(),[2,Promise.resolve()]}}))}))},e.prototype.signOut=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this.paymentIntegrationService.signOutCustomer(e)];case 1:return t.sent(),[2,Promise.resolve()]}}))}))},e.prototype.executePaymentMethodCheckout=function(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()},e.prototype.renderButton=function(e,t){var n=this,r=t.container,i=t.onComplete,o=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),a=(this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData||{}).isHostedCheckoutEnabled,c={createOrder:function(){return n.paypalCommerceIntegrationService.createOrder("paypalcommerce")},onApprove:function(t){var r=t.orderID;return n.paypalCommerceIntegrationService.tokenizePayment(e,r)}},u={onShippingAddressChange:function(e){return n.onShippingAddressChange(e)},onShippingOptionsChange:function(e){return n.onShippingOptionsChange(e)},onApprove:function(t,r){return n.onHostedCheckoutApprove(t,r,e,i)}},d=(0,s.__assign)((0,s.__assign)({fundingSource:o.FUNDING.PAYPAL,style:this.paypalCommerceIntegrationService.getValidButtonStyle()},c),a&&u),l=o.Buttons(d);l.isEligible()?l.render("#"+r):this.paypalCommerceIntegrationService.removeElement(r)},e.prototype.onHostedCheckoutApprove=function(e,t,n,r){return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!e.orderID)throw new me(he.MissingOrderId);return i=this.paymentIntegrationService.getState().getCartOrThrow(),[4,t.order.get()];case 1:o=s.sent(),s.label=2;case 2:return s.trys.push([2,9,,10]),a=this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(o),[4,this.paymentIntegrationService.updateBillingAddress(a)];case 3:return s.sent(),i.lineItems.physicalItems.length>0?(c=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(o),[4,this.paymentIntegrationService.updateShippingAddress(c)]):[3,6];case 4:return s.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:s.sent(),s.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return s.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,e.orderID)];case 8:return s.sent(),r&&"function"==typeof r&&r(),[3,10];case 9:return u=s.sent(),this.handleError(u),[3,10];case 10:return[2]}}))}))},e.prototype.onShippingAddressChange=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:t=this.paypalCommerceIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.country_code,postalCode:e.shippingAddress.postal_code,stateOrProvinceCode:e.shippingAddress.state}),i.label=1;case 1:return i.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(t)];case 2:return i.sent(),[4,this.paymentIntegrationService.updateShippingAddress(t)];case 3:return i.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return i.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return i.sent(),[3,7];case 6:return r=i.sent(),this.handleError(r),[3,7];case 7:return[2]}}))}))},e.prototype.onShippingOptionsChange=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:t=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(t.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:return n=r.sent(),this.handleError(n),[3,5];case 5:return[2]}}))}))},e.prototype.handleError=function(e){if("function"!=typeof this.onError)throw e;this.onError(e)},e}();const It=St,bt=le((function(e){return new It(e,Ct(e))}),[{id:"paypalcommerce"}]);var Pt=function(){function e(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.onError=Z.noop}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:if(t=e.paypalcommercecredit,!(n=e.methodId))throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new ye('Unable to initialize payment because "paypalcommercecredit" argument is not provided.');if(!t.container)throw new ye('Unable to initialize payment because "paypalcommercecredit.container" argument is not provided.');return this.onError=t.onError||Z.noop,[4,this.paymentIntegrationService.loadPaymentMethod(n)];case 1:return r.sent(),[4,this.paypalCommerceIntegrationService.loadPayPalSdk(n)];case 2:return r.sent(),this.renderButton(n,t),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.signIn=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return[4,this.paymentIntegrationService.signInCustomer(e,t)];case 1:return n.sent(),[2]}}))}))},e.prototype.signOut=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this.paymentIntegrationService.signOutCustomer(e)];case 1:return t.sent(),[2]}}))}))},e.prototype.executePaymentMethodCheckout=function(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()},e.prototype.renderButton=function(e,t){var n=this,r=t.container,i=t.onComplete,o=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),a=(this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData||{}).isHostedCheckoutEnabled,c={createOrder:function(){return n.paypalCommerceIntegrationService.createOrder("paypalcommercecredit")},onApprove:function(t){var r=t.orderID;return n.paypalCommerceIntegrationService.tokenizePayment(e,r)}},u={onShippingAddressChange:function(e){return n.onShippingAddressChange(e)},onShippingOptionsChange:function(e){return n.onShippingOptionsChange(e)},onApprove:function(t,r){return n.onHostedCheckoutApprove(t,r,e,i)}},d=[o.FUNDING.PAYLATER,o.FUNDING.CREDIT],l=!1;d.forEach((function(e){if(!l){var t=(0,s.__assign)((0,s.__assign)({fundingSource:e,style:n.paypalCommerceIntegrationService.getValidButtonStyle({color:st.gold})},c),a&&u),i=o.Buttons(t);i.isEligible()&&(i.render("#"+r),l=!0)}})),l||this.paypalCommerceIntegrationService.removeElement(r)},e.prototype.onHostedCheckoutApprove=function(e,t,n,r){return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!e.orderID)throw new me(he.MissingOrderId);return i=this.paymentIntegrationService.getState().getCartOrThrow(),[4,t.order.get()];case 1:o=s.sent(),s.label=2;case 2:return s.trys.push([2,9,,10]),a=this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(o),[4,this.paymentIntegrationService.updateBillingAddress(a)];case 3:return s.sent(),i.lineItems.physicalItems.length>0?(c=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(o),[4,this.paymentIntegrationService.updateShippingAddress(c)]):[3,6];case 4:return s.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:s.sent(),s.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return s.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,e.orderID)];case 8:return s.sent(),r&&"function"==typeof r&&r(),[3,10];case 9:return u=s.sent(),this.handleError(u),[3,10];case 10:return[2]}}))}))},e.prototype.onShippingAddressChange=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:t=this.paypalCommerceIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.country_code,postalCode:e.shippingAddress.postal_code,stateOrProvinceCode:e.shippingAddress.state}),i.label=1;case 1:return i.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(t)];case 2:return i.sent(),[4,this.paymentIntegrationService.updateShippingAddress(t)];case 3:return i.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return i.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return i.sent(),[3,7];case 6:return r=i.sent(),this.handleError(r),[3,7];case 7:return[2]}}))}))},e.prototype.onShippingOptionsChange=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:t=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(t.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:return n=r.sent(),this.handleError(n),[3,5];case 5:return[2]}}))}))},e.prototype.handleError=function(e){if("function"!=typeof this.onError)throw e;this.onError(e)},e}();const Et=Pt,At=le((function(e){return new Et(e,Ct(e))}),[{id:"paypalcommercecredit"}]);var Ot=function(){function e(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:if(t=e.paypalcommercevenmo,!(n=e.methodId))throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new ye('Unable to initialize payment because "paypalcommercevenmo" argument is not provided.');if(!t.container)throw new ye('Unable to initialize payment because "paypalcommercevenmo.container" argument is not provided.');return[4,this.paymentIntegrationService.loadPaymentMethod(n)];case 1:return r.sent(),[4,this.paypalCommerceIntegrationService.loadPayPalSdk(n)];case 2:return r.sent(),this.renderButton(n,t.container),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.signIn=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return[4,this.paymentIntegrationService.signInCustomer(e,t)];case 1:return n.sent(),[2]}}))}))},e.prototype.signOut=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this.paymentIntegrationService.signOutCustomer(e)];case 1:return t.sent(),[2]}}))}))},e.prototype.executePaymentMethodCheckout=function(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()},e.prototype.renderButton=function(e,t){var n=this,r=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),i={fundingSource:r.FUNDING.VENMO,style:this.paypalCommerceIntegrationService.getValidButtonStyle(),createOrder:function(){return n.paypalCommerceIntegrationService.createOrder("paypalcommercevenmo")},onApprove:function(t){var r=t.orderID;return n.paypalCommerceIntegrationService.tokenizePayment(e,r)}},o=r.Buttons(i);o.isEligible()?o.render("#"+t):this.paypalCommerceIntegrationService.removeElement(t)},e}();const kt=Ot,Tt=le((function(e){return new kt(e,Ct(e))}),[{id:"paypalcommercevenmo"}]);function Mt(t,n){void 0===n&&(n=e);for(var r=new de,i=function(e){if(!oe(e))return"continue";for(var n=0,i=e.resolveIds;n=400&&e.status<500)throw new q(e);throw e}))},e.prototype.updateCheckout=function(e,t,n){var r=void 0===n?{}:n,i=r.params,o=(void 0===i?{}:i).include,a=r.timeout,c="/api/storefront/checkout/"+e,u=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.put(c,{params:{include:xt(K,o)},body:t,headers:u,timeout:a})},e}();const Vt=qt;var Gt;!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"}(Gt||(Gt={}));var Ht=function(){function e(e,t,n){this._checkoutRequestSender=e,this._configActionCreator=t,this._formFieldsActionCreator=n}return e.prototype.loadCheckout=function(e,t){var n=this;return(0,u.concat)((0,u.of)((0,c.createAction)(Gt.LoadCheckoutRequested)),(0,u.merge)(this._configActionCreator.loadConfig((0,s.__assign)((0,s.__assign)({},t),{useCache:!0,params:(0,s.__assign)((0,s.__assign)({},null==t?void 0:t.params),{checkoutId:e})})),this._formFieldsActionCreator.loadFormFields((0,s.__assign)((0,s.__assign)({},t),{useCache:!0})),(0,u.defer)((function(){return n._checkoutRequestSender.loadCheckout(e,t).then((function(e){var t=e.body;return(0,c.createAction)(Gt.LoadCheckoutSucceeded,t)}))})))).pipe((0,d.catchError)((function(e){return l(Gt.LoadCheckoutFailed,e)})))},e.prototype.loadDefaultCheckout=function(e){var t=this;return function(n){return(0,u.concat)((0,u.of)((0,c.createAction)(Gt.LoadCheckoutRequested)),(0,u.merge)(t._configActionCreator.loadConfig(),t._formFieldsActionCreator.loadFormFields((0,s.__assign)((0,s.__assign)({},e),{useCache:!0}))),(0,u.defer)((function(){return(0,s.__awaiter)(t,void 0,void 0,(function(){var t,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(t=n.getState(),!(r=t.config.getContextConfig())||!r.checkoutId)throw new m(h.MissingCheckoutConfig);return[4,this._checkoutRequestSender.loadCheckout(r.checkoutId,e)];case 1:return i=o.sent().body,[2,(0,c.createAction)(Gt.LoadCheckoutSucceeded,i)]}}))}))}))).pipe((0,d.catchError)((function(e){return l(Gt.LoadCheckoutFailed,e)})))}},e.prototype.updateCheckout=function(e,t){var n=this;return function(r){return new u.Observable((function(i){var o=r.getState().checkout.getCheckout();if(!o)throw new m(h.MissingCheckout);i.next((0,c.createAction)(Gt.UpdateCheckoutRequested)),n._checkoutRequestSender.updateCheckout(o.id,e,t).then((function(e){var t=e.body;i.next((0,c.createAction)(Gt.UpdateCheckoutSucceeded,t)),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(Gt.UpdateCheckoutFailed,e))}))}))}},e.prototype.loadCurrentCheckout=function(e){var t=this;return function(n){var r=n.getState().checkout.getCheckout();if(!r)throw new m(h.MissingCheckout);return t.loadCheckout(r.id,e)}},e}();const Yt=Ht;var jt;!function(e){e.LoadFormFieldsRequested="LOAD_FORM_FIELDS_REQUESTED",e.LoadFormFieldsSucceeded="LOAD_FORM_FIELDS_SUCCEEDED",e.LoadFormFieldsFailed="LOAD_FORM_FIELDS_FAILED"}(jt||(jt={}));var Wt=function(){function e(e){this._formFieldsRequestSender=e}return e.prototype.loadFormFields=function(e){var t=this;return(0,u.concat)((0,u.of)((0,c.createAction)(jt.LoadFormFieldsRequested)),(0,u.defer)((function(){return(0,s.__awaiter)(t,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return[4,this._formFieldsRequestSender.loadFields(e)];case 1:return t=n.sent().body,[2,(0,c.createAction)(jt.LoadFormFieldsSucceeded,t)]}}))}))}))).pipe((0,d.catchError)((function(e){return l(jt.LoadFormFieldsFailed,e)})))},(0,s.__decorate)([N],e.prototype,"loadFormFields",null),e}();const Kt=Wt;var Jt=function(){function e(e){this._requestSender=e}return e.prototype.loadFields=function(e){var t=(void 0===e?{}:e).timeout;return this._requestSender.get("/api/storefront/form-fields",{timeout:t,headers:(0,s.__assign)({Accept:w.JsonV1,"X-API-INTERNAL":V},C)})},e}();const Zt=Jt;var Qt;!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"}(Qt||(Qt={}));var Xt=function(){function e(e){this._requestSender=e}return e.prototype.loadPaymentMethods=function(e){var t=this;return function(n){return u.Observable.create((function(r){var i=n.getState().cart.getCartOrThrow();r.next((0,c.createAction)(Qt.LoadPaymentMethodsRequested)),t._requestSender.loadPaymentMethods((0,s.__assign)((0,s.__assign)({},e),{params:(0,s.__assign)((0,s.__assign)({},null==e?void 0:e.params),{cartId:i.id})})).then((function(e){var n={deviceSessionId:e.headers["x-device-session-id"],sessionHash:e.headers["x-session-hash"]},i=e.body,o=Array.isArray(i)?t._filterApplePay(i):i;r.next((0,c.createAction)(Qt.LoadPaymentMethodsSucceeded,o,n)),r.complete()})).catch((function(e){r.error((0,c.createErrorAction)(Qt.LoadPaymentMethodsFailed,e))}))}))}},e.prototype.loadPaymentMethod=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o,a=null===(o=r.getState().cart.getCart())||void 0===o?void 0:o.id,u=a?(0,s.__assign)((0,s.__assign)({},null==t?void 0:t.params),{cartId:a}):(0,s.__assign)({},null==t?void 0:t.params);i.next((0,c.createAction)(Qt.LoadPaymentMethodRequested,void 0,{methodId:e})),n._requestSender.loadPaymentMethod(e,(0,s.__assign)((0,s.__assign)({},t),{params:u})).then((function(t){i.next((0,c.createAction)(Qt.LoadPaymentMethodSucceeded,t.body,{methodId:e})),i.complete()})).catch((function(t){i.error((0,c.createErrorAction)(Qt.LoadPaymentMethodFailed,t,{methodId:e}))}))}))}},e.prototype._filterApplePay=function(e){return(0,Z.filter)(e,(function(e){return!("applepay"===e.id&&!function(e){return"ApplePaySession"in e}(window))}))},(0,s.__decorate)([N],e.prototype,"loadPaymentMethod",null),e}();const $t=Xt;var en=function(){function e(e){this._requestSender=e}return e.prototype.loadPaymentMethods=function(e){var t=void 0===e?{}:e,n=t.timeout,r=t.params;return this._requestSender.get("/api/storefront/payments",{timeout:n,headers:(0,s.__assign)({Accept:w.JsonV1,"X-API-INTERNAL":V},C),params:r})},e.prototype.loadPaymentMethod=function(e,t){var n=void 0===t?{}:t,r=n.timeout,i=n.params,o="/api/storefront/payments/"+e;return this._requestSender.get(o,{timeout:r,headers:(0,s.__assign)({Accept:w.JsonV1,"X-API-INTERNAL":V},C),params:i})},e}();const tn=en;var nn=function(){function e(e){this._requestSender=e}return e.prototype.createBuyNowCart=function(e,t){var n=(void 0===t?{}:t).timeout,r=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.post("/api/storefront/carts",{body:e,headers:r,timeout:n})},e}();const rn=nn,on=function(){function e(){}return e.prototype.isEqual=function(e,t){return(0,Z.isEqual)(this._normalize(e),this._normalize(t))},e.prototype._normalize=function(e){return{cartAmount:e.cartAmount,currency:e.currency,id:e.id,lineItems:{digitalItems:e.lineItems.digitalItems.slice().sort((function(e,t){return(""+e.productId+e.variantId).localeCompare(""+t.productId+t.variantId)})).map((function(e){return{extendedSalePrice:e.extendedSalePrice,productId:e.productId,quantity:e.quantity,variantId:e.variantId}})),giftCertificates:e.lineItems.giftCertificates.slice().sort((function(e,t){return(""+e.id).localeCompare(""+t.id)})).map((function(e){return{amount:e.amount,recipient:e.recipient}})),physicalItems:e.lineItems.physicalItems.slice().sort((function(e,t){return(""+e.productId+e.variantId).localeCompare(""+t.productId+t.variantId)})).map((function(e){return{extendedSalePrice:e.extendedSalePrice,productId:e.productId,quantity:e.quantity,variantId:e.variantId,giftWrapping:e.giftWrapping}}))}}},e}(),an=function(e){function t(t,n){var r=e.call(this,"An update to your shopping cart has been detected and your available shipping costs have been updated.")||this;return r.name="CartChangedError",r.type="cart_changed",r.data={previous:t,updated:n},r}return(0,s.__extends)(t,e),t}(p),sn=function(){function e(e){this._checkoutRequestSender=e}return e.prototype.validate=function(e,t){var n=this;if(!e)throw new m(h.MissingCheckout);return this._checkoutRequestSender.loadCheckout(e.id,t).then((function(t){var r=new on;if(!(e.outstandingBalance===t.body.outstandingBalance&&n._compareCoupons(e.coupons,t.body.coupons)&&n._compareGiftCertificates(e.giftCertificates,t.body.giftCertificates)&&r.isEqual(e.cart,t.body.cart)))throw new an(n._getComparableCheckout(e),n._getComparableCheckout(t.body))}))},e.prototype._compareCoupons=function(e,t){return(0,Z.isEqual)((0,Z.map)(e,"code"),(0,Z.map)(t,"code"))},e.prototype._compareGiftCertificates=function(e,t){return(0,Z.isEqual)((0,Z.map)(e,"code"),(0,Z.map)(t,"code"))},e.prototype._getComparableCheckout=function(e){var t=e.cart,n=e.coupons,r=e.giftCertificates,i=e.outstandingBalance;return{cart:{cartAmount:t.cartAmount,currency:t.currency,lineItems:t.lineItems},coupons:n,giftCertificates:r,outstandingBalance:i}},e}(),cn=function(e){var t=this,n=new Promise((function(e,n){t.cancel=n}));this.promise=Promise.race([e,n])},un=function(e){function t(t){var n=e.call(this,t||"Unable to proceed because the required element is unexpectedly detached from the page.")||this;return n.name="UnexpectedDetachmentError",n.type="unexpected_detachment",n}return(0,s.__extends)(t,e),t}(p);var dn=function(){function e(e){this._mutationObserver=e}return e.prototype.ensurePresence=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:n=new cn(t),(r=this._mutationObserver.create((function(t){t.forEach((function(t){0!==Array.from(t.removedNodes).filter((function(t){return e.some((function(e){return t===e||t.contains(e)}))})).length&&n.cancel(new un)}))}))).observe(document.body,{childList:!0,subtree:!0}),a.label=1;case 1:return a.trys.push([1,3,,4]),[4,n.promise];case 2:return i=a.sent(),r.disconnect(),[2,i];case 3:throw o=a.sent(),r.disconnect(),o;case 4:return[2]}}))}))},e}();const ln=dn;var pn=function(){function e(e){void 0===e&&(e=window),this._window=e}return e.prototype.create=function(e){return new this._window.MutationObserver(e)},e}();function hn(e){if(!/^(https?:)?\/\//.test(e))throw new ae("The provided URL must be absolute.");var t=document.createElement("a");t.href=e;var n=t.port&&-1!==e.indexOf(t.hostname+":"+t.port)?t.port:"";return{hash:t.hash,hostname:t.hostname,href:t.href,origin:t.protocol+"//"+t.hostname+(n?":"+n:""),pathname:t.pathname,port:n,protocol:t.protocol,search:t.search}}function mn(e,t){return e.type===t}const _n=function(){function e(e,t){this._targetWindow=t,this._targetOrigin="*"===e?"*":hn(e).origin}return e.prototype.post=function(e,t){var n=this,r=this._targetWindow;if(window!==r){if(!r)throw new Error("Unable to post message because target window is not set.");var i=t&&(0,u.fromEvent)(window,"message").pipe((0,d.filter)((function(e){return e.origin===n._targetOrigin&&mn(e.data,e.data.type)&&-1!==[t.successType,t.errorType].indexOf(e.data.type)})),(0,d.map)((function(e){if(t.errorType===e.data.type)throw e.data;return e.data})),(0,d.take)(1)).toPromise();return r.postMessage(e,this._targetOrigin),i}},e.prototype.setTarget=function(e){this._targetWindow=e},e}();const yn=function(e,t,n){return t&&n?fn(0,t,n):function(e){var t=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return(0,s.__extends)(t,e),t}(e);return Object.getOwnPropertyNames(e.prototype).forEach((function(n){var r=Object.getOwnPropertyDescriptor(e.prototype,n);r&&"constructor"!==n&&Object.defineProperty(t.prototype,n,fn(e.prototype,n,r))})),t}(e)};function fn(e,t,n){if("function"!=typeof n.value)return n;var r=n.value;return{get:function(){var e=r.bind(this);return Object.defineProperty(this,t,(0,s.__assign)((0,s.__assign)({},n),{value:e})),e},set:function(e){r=e}}}const gn=function(){function e(e){var t;this._sourceOrigins=[hn(e).origin,(t=hn(e),hn(0===t.hostname.indexOf("www")?t.href:t.href.replace(t.hostname,"www."+t.hostname))).origin],this._isListening=!1,this._listeners={}}return e.prototype.listen=function(){this._isListening||(this._isListening=!0,window.addEventListener("message",this._handleMessage))},e.prototype.stopListen=function(){this._isListening&&(this._isListening=!1,window.removeEventListener("message",this._handleMessage))},e.prototype.addListener=function(e,t){var n=this._listeners[e];n||(this._listeners[e]=n=[]),-1===n.indexOf(t)&&n.push(t)},e.prototype.removeListener=function(e,t){var n=this._listeners[e];if(n){var r=n.indexOf(t);r>=0&&n.splice(r,1)}},e.prototype.trigger=function(e){var t=this._listeners[e.type];t&&t.forEach((function(t){return t(e)}))},e.prototype._handleMessage=function(e){-1!==this._sourceOrigins.indexOf(e.origin)&&mn(e.data,e.data.type)&&this.trigger(e.data)},(0,s.__decorate)([yn],e.prototype,"_handleMessage",null),e}(),vn=function(e){function t(){var t=e.call(this,"You haven't complete our spam protection challenge. Please try again.")||this;return t.name="SpamProtectionChallengeNotCompletedError",t.type="spam_protection_challenge_not_completed",t}return(0,s.__extends)(t,e),t}(p),wn=function(e){function t(){var t=e.call(this,"Please complete our human verification challenge and try again.")||this;return t.name="CardingProtectionChallengeNotCompletedError",t.type="carding_protection_challenge_not_completed",t}return(0,s.__extends)(t,e),t}(p),Cn=function(e){function t(){var t=e.call(this,"We were not able to verify that you are not a robot. Please try again.")||this;return t.name="CardingProtectionFailedError",t.type="carding_protection_failed",t}return(0,s.__extends)(t,e),t}(p);var Sn=function(){function e(e){this._googleRecaptcha=e}return e.prototype.handle=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){return"string"==typeof e?[2,this.handleWithRecaptchaSitekey(e,t)]:[2,this.handleWithPaymentHumanVerificationRequestError(e)]}))}))},e.prototype.handleWithPaymentHumanVerificationRequestError=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:if(!this._isPaymentHumanVerificationRequest(e))throw e;return[4,this._initialize(e.body.additional_action_required.data.key)];case 1:return t.sent(),[2,this._performRecaptcha()]}}))}))},e.prototype.handleWithRecaptchaSitekey=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){switch(n.label){case 0:if("recaptcha_v2"!==e)throw Error("Human verification method is not supported.");if(!t)throw Error("Recaptcha site key is missing.");return[4,this._initialize(t)];case 1:return n.sent(),[2,this._performRecaptcha()]}}))}))},e.prototype._performRecaptcha=function(){var e=this;return this._googleRecaptcha.execute().pipe((0,d.take)(1)).pipe((0,d.switchMap)((function(t){var n=t.error,r=t.token;return(0,s.__awaiter)(e,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){if(n instanceof vn)throw new wn;if(n||!r)throw new Cn;return[2,{type:"recaptcha_v2_verification",data:{human_verification_token:r}}]}))}))}))).toPromise()},e.prototype._initialize=function(e){var t="cardingProtectionContainer",n=document.getElementById(t);return n&&n.parentNode&&n.parentNode.removeChild(n),(n=document.createElement("div")).setAttribute("id",t),document.body.appendChild(n),this._googleRecaptcha.load(t,e)},e.prototype._isPaymentHumanVerificationRequest=function(e){var t=e.body||{},n=t.additional_action_required;return"additional_action_required"===t.status&&n&&"recaptcha_v2_verification"===n.type},e}();const In=Sn;var bn;!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"}(bn||(bn={}));const Pn=function(e){function t(t){var n=e.call(this,function(e){switch(e){case bn.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case bn.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case bn.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case bn.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."}}(t))||this;return n.subtype=t,n.name="NotInitializedError",n.type="not_initialized",n}return(0,s.__extends)(t,e),t}(p),En=function(e){function t(){var t=e.call(this,"We were not able to complete your spam protection verification. Please try again.")||this;return t.name="SpamProtectionFailedError",t.type="spam_protection_failed",t}return(0,s.__extends)(t,e),t}(p),An=function(e){function t(){var t=e.call(this,"Spam protection is not loaded. Please try again.")||this;return t.name="SpamProtectionNotLoadedError",t.type="spam_protection_failed",t}return(0,s.__extends)(t,e),t}(p),On=function(){function e(e,t){var n=this;this.googleRecaptchaScriptLoader=e,this.mutationObserverFactory=t,this._memoized=(0,z.memoize)((function(e,t,r){var i=new u.Subject;if(!r)throw new Error;return n._widgetId=e.render(r.id,{sitekey:t,size:"invisible",callback:function(){i.next({token:e.getResponse(n._widgetId)}),e.reset(n._widgetId)},"error-callback":function(){i.next({error:new En})}}),i}),{isEqual:function(e,t){return e===t}})}return e.prototype.load=function(e,t){var n=this;return this.googleRecaptchaScriptLoader.load().then((function(r){r&&(n._event$=n._memoized(r,t,document.getElementById(e)),n._recaptcha=r)}))},e.prototype.execute=function(){var e=this;return(0,u.defer)((function(){var t=e._event$,n=e._recaptcha;if(!t||!n)throw new Pn(bn.SpamProtectionNotInitialized);return(0,u.defer)((function(){var e=document.querySelector('iframe[src*="bframe"]');return e?(0,u.of)(e):(0,u.throwError)(new An)})).pipe((0,d.retryWhen)((function(e){return e.pipe((0,d.delay)(250),(0,d.switchMap)((function(e,t){return t<28?(0,u.of)(e):(0,u.throwError)(e)})))})),(0,d.switchMap)((function(r){return e._watchRecaptchaChallengeWindow(t,r),n.execute(e._widgetId),t})),(0,d.catchError)((function(e){return(0,u.of)({error:e})})))}))},e.prototype._watchRecaptchaChallengeWindow=function(e,t){var n=t.parentElement;if(!n)throw new An;var r=n.parentElement;if(!r)throw new An;this.mutationObserverFactory.create((function(){"hidden"===r.style.visibility&&e.next({error:new vn})})).observe(r,{attributes:!0,attributeFilter:["style"]})},e}(),kn=function(){function e(e,t){void 0===t&&(t=window),this._scriptLoader=e,this._window=t}return e.prototype.load=function(){return this._loadPromise||(this._loadPromise=this._loadScript()),this._loadPromise},e.prototype._loadScript=function(){var e=this,t="initRecaptcha",n=["onload="+t,"render=explicit"].join("&");return new Promise((function(r,i){e._window[t]=function(){return r(e._window.grecaptcha)},e._scriptLoader.loadScript("//www.google.com/recaptcha/api.js?"+n).catch((function(t){e._loadPromise=void 0,i(t)}))}))},e}();function Tn(e){return new On(new kn(e),new pn)}function Mn(e,t){var n=e.body.errors,r=void 0===n?[]:n;return new x(e,{message:Dn(r)||t,errors:r})}function Dn(e){if(Array.isArray(e))return e.reduce((function(e,t){return t&&t.message?(0,s.__spreadArrays)(e,[t.message]):e}),[]).join(" ")}const Rn=function(e){function t(t){var n=e.call(this,t||"Unable to proceed due to invalid configuration provided for the hosted payment form.")||this;return n.name="InvalidHostedFormConfigError",n.type="invalid_hosted_form_config",n}return(0,s.__extends)(t,e),t}(p),zn=function(e){function t(t){var n=e.call(this,t||"Unable to proceed due to an unknown error with the hosted payment form.")||this;return n.name="InvalidHostedFormError",n.type="invalid_hosted_form",n}return(0,s.__extends)(t,e),t}(p);var Nn=function(e){function t(t){var n=e.call(this,(0,s.__spreadArrays)(["Unable to proceed due to invalid user input values"],(0,Z.flatMap)((0,Z.values)(t),(function(e){return(0,Z.map)(e,(function(e){return e.message}))}))).join(". "))||this;return n.errors=t,n.name="InvalidHostedFormValueError",n.type="invalid_hosted_form_value",n}return(0,s.__extends)(t,e),t}(p);const Ln=Nn;var Fn,Bn;!function(e){e.AttachRequested="HOSTED_FIELD:ATTACH_REQUESTED",e.SubmitRequested="HOSTED_FIELD:SUBMITTED_REQUESTED",e.ValidateRequested="HOSTED_FIELD:VALIDATE_REQUESTED"}(Fn||(Fn={})),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"}(Bn||(Bn={}));var Un=function(){function e(e,t,n,r,i,o,a,s,c){this._type=e,this._containerId=t,this._placeholder=n,this._accessibilityLabel=r,this._styles=i,this._eventPoster=o,this._eventListener=a,this._detachmentObserver=s,this._cardInstrument=c,this._iframe=document.createElement("iframe"),this._iframe.src="/checkout/payment/hosted-field?version=1.398.1",this._iframe.style.border="none",this._iframe.style.height="100%",this._iframe.style.overflow="hidden",this._iframe.style.width="100%"}return e.prototype.getType=function(){return this._type},e.prototype.attach=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){var e,t,n=this;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:if(!(e=document.getElementById(this._containerId)))throw new Rn("Unable to proceed because the provided container ID is not valid.");return e.appendChild(this._iframe),this._eventListener.listen(),t=(0,u.fromEvent)(this._iframe,"load").pipe((0,d.switchMap)((function(e){var t=e.target;return(0,s.__awaiter)(n,void 0,void 0,(function(){var e;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:if(!(e=t&&t.contentWindow))throw new Error("The content window of the iframe cannot be accessed.");return this._eventPoster.setTarget(e),[4,this._eventPoster.post({type:Fn.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:Bn.AttachSucceeded,errorType:Bn.AttachFailed})];case 1:return n.sent(),[2]}}))}))})),(0,d.take)(1)).toPromise(),[4,this._detachmentObserver.ensurePresence([this._iframe],t)];case 1:return r.sent(),[2]}}))}))},e.prototype.detach=function(){this._iframe.parentElement&&(this._iframe.parentElement.removeChild(this._iframe),this._eventListener.stopListen())},e.prototype.submitForm=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),n=this._eventPoster.post({type:Fn.SubmitRequested,payload:{fields:e,data:t}},{successType:Bn.SubmitSucceeded,errorType:Bn.SubmitFailed}),[4,this._detachmentObserver.ensurePresence([this._iframe],n)];case 1:return[2,i.sent()];case 2:if(r=i.sent(),this._isSubmitErrorEvent(r)){if("hosted_form_error"===r.payload.error.code)throw new zn(r.payload.error.message);if(r.payload.response)throw Mn(r.payload.response);throw new Error(r.payload.error.message)}throw r;case 3:return[2]}}))}))},e.prototype.validateForm=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){var e,t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return e=this._eventPoster.post({type:Fn.ValidateRequested},{successType:Bn.Validated}),[4,this._detachmentObserver.ensurePresence([this._iframe],e)];case 1:if(!(t=n.sent().payload).isValid)throw new Ln(t.errors);return[2]}}))}))},e.prototype._getFontUrls=function(){var e=this,t="fonts.googleapis.com",n=document.querySelectorAll("link[href*='"+t+"'][rel='stylesheet']");return Array.prototype.slice.call(n).filter((function(e){return hn(e.href).hostname===t})).filter((function(t){return(0,Z.values)(e._styles).map((function(e){return e&&e.fontFamily})).filter((function(e){return"string"==typeof e})).some((function(e){return e.split(/,\s/).some((function(e){return-1!==t.href.indexOf(e.replace(" ","+"))}))}))})).map((function(e){return e.href}))},e.prototype._isSubmitErrorEvent=function(e){return e.type===Bn.SubmitFailed},e}();const xn=Un;var qn=function(){function e(e,t,n,r,i){var o=this;this._fields=e,this._eventListener=t,this._payloadTransformer=n,this._eventCallbacks=r,this._paymentHumanVerificationHandler=i,this._handleEnter=function(e){var t=e.payload;return(0,s.__awaiter)(o,void 0,void 0,(function(){var e,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,this.validate()];case 1:return r.sent(),[3,3];case 2:if("InvalidHostedFormValueError"!==(e=r.sent()).name)throw e;return[3,3];case 3:return(void 0===(n=this._eventCallbacks.onEnter)?Z.noop:n)(t),[2]}}))}))};var a=this._eventCallbacks,c=a.onBlur,u=void 0===c?Z.noop:c,d=a.onCardTypeChange,l=void 0===d?Z.noop:d,p=a.onFocus,h=void 0===p?Z.noop:p,m=a.onValidate,_=void 0===m?Z.noop:m;this._eventListener.addListener(Bn.Blurred,(function(e){var t=e.payload;return u(t)})),this._eventListener.addListener(Bn.CardTypeChanged,(function(e){var t=e.payload;return l(t)})),this._eventListener.addListener(Bn.Focused,(function(e){var t=e.payload;return h(t)})),this._eventListener.addListener(Bn.Validated,(function(e){var t=e.payload;return _(t)})),this._eventListener.addListener(Bn.Entered,this._handleEnter),this._eventListener.addListener(Bn.CardTypeChanged,(function(e){var t=e.payload;return o._cardType=t.cardType})),this._eventListener.addListener(Bn.BinChanged,(function(e){var t=e.payload;return o._bin=t.bin}))}return e.prototype.getBin=function(){return this._bin},e.prototype.getCardType=function(){return this._cardType},e.prototype.attach=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){var e,t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return this._eventListener.listen(),e=this._getFirstField(),t=(0,Z.without)(this._fields,e),[4,e.attach()];case 1:return n.sent(),[4,Promise.all(t.map((function(e){return e.attach()})))];case 2:return n.sent(),[2]}}))}))},e.prototype.detach=function(){this._eventListener.stopListen(),this._fields.forEach((function(e){e.detach()}))},e.prototype.submit=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,5]),[4,this._getFirstField().submitForm(this._fields.map((function(e){return e.getType()})),this._payloadTransformer.transform(e,t))];case 1:case 4:return[2,i.sent()];case 2:return n=i.sent(),[4,this._paymentHumanVerificationHandler.handle(n)];case 3:return r=i.sent(),[4,this._getFirstField().submitForm(this._fields.map((function(e){return e.getType()})),this._payloadTransformer.transform(e,r))];case 5:return[2]}}))}))},e.prototype.validate=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){return[2,this._getFirstField().validateForm()]}))}))},e.prototype._getFirstField=function(){var e=this._fields[0];if(!e)throw new Rn("Unable to proceed because the payment form has no field defined.");return e},e}();const Vn=qn;function Gn(e){return Boolean(e.instrumentId)}const Hn=function(){function e(e){this._store=e}return e.prototype.transform=function(e,t){var n=this._store.getState(),r=n.checkout.getCheckout(),i=n.config.getConfig(),o=n.instruments.getInstrumentsMeta(),a=n.order.getOrder(),s=n.order.getOrderMeta(),c=(0,Z.omit)(e.paymentData,"ccExpiry","ccName","ccNumber","ccCvv"),u=n.paymentMethods.getPaymentMethod(e.methodId,e.gatewayId),d=n.paymentMethods.getPaymentMethodsMeta(),l=o&&c&&Gn(c)?n.payment.getPaymentToken()+", "+o.vaultAccessToken:n.payment.getPaymentToken();if(!l)throw new m(h.MissingPaymentToken);return{additionalAction:t,authToken:l,checkout:r,config:i,order:a,orderMeta:s,payment:c,paymentMethod:u,paymentMethodMeta:d}},e}(),Yn=function(){function e(e){this._store=e}return e.prototype.create=function(e,t){var n=this,r=Object.keys(t.fields).reduce((function(r,i){var o=t.fields[i];return o?(0,s.__spreadArrays)(r,[new xn(i,o.containerId,o.placeholder||"",o.accessibilityLabel||"",t.styles||{},new _n(e),new gn(e),new ln(new pn),"instrumentId"in o?n._getCardInstrument(o.instrumentId):void 0)]):r}),[]);return new Vn(r,new gn(e),new Hn(this._store),(0,Z.pick)(t,"onBlur","onEnter","onFocus","onCardTypeChange","onValidate"),new In(Tn((0,a.createScriptLoader)())))},e.prototype._getCardInstrument=function(e){var t=(0,this._store.getState().instruments.getCardInstrument)(e);if(!t)throw new m(h.MissingPaymentInstrument);return t},e}(),jn=function(e){function t(){var t=e.call(this,"You haven't complete our spam check. Please try again.")||this;return t.name="SpamProtectionNotCompletedError",t.type="spam_protection_not_completed",t}return(0,s.__extends)(t,e),t}(p);var Wn;!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"}(Wn||(Wn={}));const Kn=function(){function e(e,t){this._orderRequestSender=e,this._checkoutValidator=t}return e.prototype.loadOrder=function(e,t){var n=this;return new u.Observable((function(r){r.next((0,c.createAction)(Wn.LoadOrderRequested)),n._orderRequestSender.loadOrder(e,t).then((function(e){r.next((0,c.createAction)(Wn.LoadOrderSucceeded,e.body)),r.complete()})).catch((function(e){r.error((0,c.createErrorAction)(Wn.LoadOrderFailed,e))}))}))},e.prototype.loadOrderPayments=function(e,t){var n=this;return new u.Observable((function(r){r.next((0,c.createAction)(Wn.LoadOrderPaymentsRequested)),n._orderRequestSender.loadOrder(e,t).then((function(e){r.next((0,c.createAction)(Wn.LoadOrderPaymentsSucceeded,e.body)),r.complete()})).catch((function(e){r.error((0,c.createErrorAction)(Wn.LoadOrderPaymentsFailed,e))}))}))},e.prototype.loadCurrentOrder=function(e){var t=this;return function(n){return(0,u.defer)((function(){var r=t._getCurrentOrderId(n.getState());if(!r)throw new m(h.MissingOrderId);return t.loadOrder(r,e)}))}},e.prototype.submitOrder=function(e,t){var n=this;return function(r){return(0,u.concat)((0,u.of)((0,c.createAction)(Wn.SubmitOrderRequested)),(0,u.defer)((function(){var i=r.getState(),o=i.config.getExternalSource(),a=i.config.getVariantIdentificationToken(),l=i.checkout.getCheckout();if(!l)throw new m(h.MissingCheckout);if(l.shouldExecuteSpamCheck)throw new jn;return(0,u.from)(n._checkoutValidator.validate(l,t).then((function(){return n._orderRequestSender.submitOrder(n._mapToOrderRequestBody(null!=e?e:{},l.id,l.customerMessage,o),(0,s.__assign)((0,s.__assign)({},t),{headers:{checkoutVariant:a}}))}))).pipe((0,d.switchMap)((function(e){return(0,u.concat)(n.loadOrder(e.body.data.order.orderId,t),(0,u.of)((0,c.createAction)(Wn.SubmitOrderSucceeded,e.body.data,(0,s.__assign)((0,s.__assign)({},e.body.meta),{token:e.headers.token}))))})))})).pipe((0,d.catchError)((function(e){return l(Wn.SubmitOrderFailed,e)}))))}},e.prototype.finalizeOrder=function(e,t){var n=this;return(0,u.concat)((0,u.of)((0,c.createAction)(Wn.FinalizeOrderRequested)),(0,u.from)(this._orderRequestSender.finalizeOrder(e,t)).pipe((0,d.switchMap)((function(r){return(0,u.concat)(n.loadOrder(e,t),(0,u.of)((0,c.createAction)(Wn.FinalizeOrderSucceeded,r.body.data)))})))).pipe((0,d.catchError)((function(e){return l(Wn.FinalizeOrderFailed,e)})))},e.prototype._getCurrentOrderId=function(e){var t=e.order.getOrder(),n=e.checkout.getCheckout();return t&&t.orderId||n&&n.orderId},e.prototype._mapToOrderRequestBody=function(e,t,n,r){var i=e.payment,o=(0,s.__rest)(e,["payment"]);return i?(0,s.__assign)((0,s.__assign)({},o),{cartId:t,customerMessage:n,externalSource:r,payment:{paymentData:i.paymentData,name:i.methodId,gateway:i.gatewayId}}):(0,s.__assign)((0,s.__assign)({},o),{cartId:t,customerMessage:n,externalSource:r})},e}(),Jn=function(e){function t(t){var n=e.call(this,t||"Your checkout could not be processed because some details have changed. Please review your order and try again.")||this;return n.name="CartConsistencyError",n.type="cart_consistency",n}return(0,s.__extends)(t,e),t}(p),Zn=function(e){function t(t){var n=e.call(this,t||"The tax provider is unavailable.")||this;return n.name="OrderTaxProviderUnavailableError",n.type="tax_provider_unavailable",n}return(0,s.__extends)(t,e),t}(p);var Qn=function(){function e(e){this._requestSender=e}return e.prototype.loadOrder=function(e,t){var n=(void 0===t?{}:t).timeout,r="/api/storefront/orders/"+e,i=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.get(r,{params:{include:Q(["payments","lineItems.physicalItems.socialMedia","lineItems.physicalItems.options","lineItems.physicalItems.categories","lineItems.digitalItems.socialMedia","lineItems.digitalItems.options","lineItems.digitalItems.categories"])},headers:i,timeout:n})},e.prototype.submitOrder=function(e,t){var n=void 0===t?{}:t,r=n.headers,i=n.timeout;return this._requestSender.post("/internalapi/v1/checkout/order",{body:e,headers:(0,Z.omitBy)((0,s.__assign)({"X-Checkout-Variant":r&&r.checkoutVariant},C),Z.isNil),timeout:i}).catch((function(e){if("tax_provider_unavailable"===e.body.type)throw new Zn;if("cart_has_changed"===e.body.type)throw new Jn;throw e}))},e.prototype.finalizeOrder=function(e,t){var n=(void 0===t?{}:t).timeout,r="/internalapi/v1/checkout/order/"+e;return this._requestSender.post(r,{timeout:n,headers:C})},e}();const Xn=Qn;var $n;!function(e){e.SubmitPaymentRequested="SUBMIT_PAYMENT_REQUESTED",e.SubmitPaymentSucceeded="SUBMIT_PAYMENT_SUCCEEDED",e.SubmitPaymentFailed="SUBMIT_PAYMENT_FAILED",e.InitializeOffsitePaymentRequested="INITIALIZE_OFFSITE_PAYMENT_REQUESTED",e.InitializeOffsitePaymentSucceeded="INITIALIZE_OFFSITE_PAYMENT_SUCCEEDED",e.InitializeOffsitePaymentFailed="INITIALIZE_OFFSITE_PAYMENT_FAILED"}($n||($n={}));var er=function(){function e(e,t,n,r){var i=this;this._paymentRequestSender=e,this._orderActionCreator=t,this._paymentRequestTransformer=n,this._paymentHumanVerificationHandler=r,this.initializeOffsitePayment=function(e){var t=e.methodId,n=e.gatewayId,r=e.instrumentId,o=e.target,a=e.promise,s=e.shouldSaveInstrument,p=e.shouldSetAsDefaultInstrument;return function(e){var h;r?h={formattedPayload:{bigpay_token:r}}:s&&(h={formattedPayload:{vault_payment_instrument:s,set_as_default_stored_instrument:p||null}});var m=i._paymentRequestTransformer.transform({gatewayId:n,methodId:t,paymentData:h},e.getState());return(0,u.concat)((0,u.of)((0,c.createAction)($n.InitializeOffsitePaymentRequested)),Promise.race([i._paymentRequestSender.initializeOffsitePayment(m,o),a].filter(Boolean)).then((function(){return(0,c.createAction)($n.InitializeOffsitePaymentSucceeded)}))).pipe((0,d.catchError)((function(e){return l($n.InitializeOffsitePaymentFailed,e)})))}}}return e.prototype.submitPayment=function(e){var t=this;return function(n){return(0,u.concat)((0,u.of)((0,c.createAction)($n.SubmitPaymentRequested)),(0,u.defer)((function(){return(0,s.__awaiter)(t,void 0,void 0,(function(){var t,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,5]),[4,this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform(e,n.getState()))];case 1:case 4:return[2,i.sent()];case 2:return t=i.sent(),[4,this._paymentHumanVerificationHandler.handle(t)];case 3:return r=i.sent(),[4,this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform((0,s.__assign)((0,s.__assign)({},e),{additionalAction:r}),n.getState()))];case 5:return[2]}}))}))})).pipe((0,d.switchMap)((function(e){var r=e.body;return(0,u.concat)(t._orderActionCreator.loadCurrentOrder()(n),(0,u.of)((0,c.createAction)($n.SubmitPaymentSucceeded,r)))})))).pipe((0,d.catchError)((function(e){return l($n.SubmitPaymentFailed,e)})))}},e}();const tr=er,nr=function(){function e(e){this._client=e}return e.prototype.submitPayment=function(e){var t=this;return new Promise((function(n,r){t._client.submitPayment(e,(function(e,i){e?r(t._transformResponse(e)):n(t._transformResponse(i))}))}))},e.prototype.initializeOffsitePayment=function(e,t){var n=this;return new Promise((function(){n._client.initializeOffsitePayment(e,null,t)}))},e.prototype._transformResponse=function(e){return{headers:e.headers,body:e.data,status:e.status,statusText:e.statusText}},e}(),rr=require("@bigcommerce/bigpay-client");function ir(e){var t=(0,rr.createClient)();return e.subscribe((function(e){var n=e.config.getStoreConfig();n&&t.setHost(n.paymentSettings.bigpayBaseUrl)}),(function(e){return e.config.getStoreConfig()})),t}function or(e){return void 0!==e.id}function ar(e,t){var n;return or(e)?n=e.id:t&&t.length&&(n=t[0].id),{id:n,firstName:e.firstName,lastName:e.lastName,company:e.company,addressLine1:e.address1,addressLine2:e.address2,city:e.city,province:e.stateOrProvince,provinceCode:e.stateOrProvinceCode,postCode:e.postalCode,country:e.country,countryCode:e.countryCode,phone:e.phone,customFields:e.customFields}}const sr=function(){function e(e){this._decimalPlaces=e}return e.prototype.toInteger=function(e){return Math.round(e*Math.pow(10,this._decimalPlaces))},e}();var cr,ur=["per_item_discount","percentage_discount","per_total_discount","shipping_discount","free_shipping"];function dr(e){return{code:e.code,discount:e.displayName,discountType:ur.indexOf(e.couponType)}}function lr(e){return{code:e.code,discountedAmount:e.used,remainingBalance:e.remaining,giftCertificate:{balance:e.balance,code:e.code,purchaseDate:e.purchaseDate}}}function pr(e,t,n){return void 0===n&&(n="id"),Object.keys(e).reduce((function(r,i){return(0,s.__spreadArrays)(r,e[i].map((function(e){return"giftCertificates"===i?function(e,t){var n=new sr(t);return{id:e.id,imageUrl:"",name:e.name,amount:e.amount,amountAfterDiscount:e.amount,discount:0,integerAmount:n.toInteger(e.amount),integerAmountAfterDiscount:n.toInteger(e.amount),integerUnitPrice:n.toInteger(e.amount),integerUnitPriceAfterDiscount:n.toInteger(e.amount),integerDiscount:0,quantity:1,sender:e.sender,recipient:e.recipient,type:"ItemGiftCertificateEntity",attributes:[],variantId:null}}(e,t):function(e,t,n,r){void 0===r&&(r="id");var i=new sr(n);return{id:e[r],imageUrl:e.imageUrl,amount:e.extendedListPrice,amountAfterDiscount:e.extendedSalePrice,discount:e.discountAmount,integerAmount:i.toInteger(e.extendedListPrice),integerAmountAfterDiscount:i.toInteger(e.extendedSalePrice),integerDiscount:i.toInteger(e.discountAmount),integerUnitPrice:i.toInteger(e.listPrice),integerUnitPriceAfterDiscount:i.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((function(e){return{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""}}(i),t,n)})))}),[])}function hr(e){var t,n,r=e.cart.currency.decimalPlaces,i=new sr(r);return{id:e.cart.id,items:pr(e.cart.lineItems,r),currency:e.cart.currency.code,coupon:{discountedAmount:(0,Z.reduce)(e.cart.coupons,(function(e,t){return e+t.discountedAmount}),0),coupons:e.cart.coupons.map(dr)},discount:{amount:e.cart.discountAmount,integerAmount:i.toInteger(e.cart.discountAmount)},discountNotifications:(t=e.promotions,n=[],(t||[]).forEach((function(e){(e.banners||[]).forEach((function(e){n.push({placeholders:[],discountType:null,message:"",messageHtml:e.text})}))})),n),giftCertificate:{totalDiscountedAmount:(0,Z.reduce)(e.giftCertificates,(function(e,t){return e+t.used}),0),appliedGiftCertificates:(0,Z.keyBy)(e.giftCertificates.map(lr),"code")},shipping:{amount:e.shippingCostTotal,integerAmount:i.toInteger(e.shippingCostTotal),amountBeforeDiscount:e.shippingCostBeforeDiscount,integerAmountBeforeDiscount:i.toInteger(e.shippingCostBeforeDiscount),required:(0,Z.some)(e.cart.lineItems.physicalItems,(function(e){return 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)}}}!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.MASTERPASS="masterpass",e.PAYPALEXPRESS="paypalexpress"}(cr||(cr={}));const mr=cr;function _r(e,t){var n=e.firstName||t.firstName||"",r=e.lastName||t.lastName||"";return{addresses:(e.addresses||[]).map((function(e){return ar(e)})),customerId:e.id,isGuest:e.isGuest,storeCredit:e.storeCredit,email:e.email||t.email||"",firstName:n,lastName:r,name:e.fullName||[n,r].join(" "),customerGroupName:e.customerGroup&&e.customerGroup.name}}var yr=function(){function e(){}return e.prototype.format=function(e){var t=e.split(new RegExp("\\s*/\\s*")),n=t[0],r=void 0===n?"":n,i=t[1],o=void 0===i?"":i,a=r.slice(0,2),s=4===o.length?o.slice(-2):o?o.slice(0,2):r.slice(2);return e.length<2?r:e.length>3&&!s?a:a+" / "+s},e.prototype.toObject=function(e){var t=e.split(new RegExp("\\s*/\\s*")),n=t[0],r=void 0===n?"":n,i=t[1],o=void 0===i?"":i;return/^\d+$/.test(r)&&/^\d+$/.test(o)?{month:1===r.length?"0"+r:r.slice(0,2),year:2===o.length?"20"+o:o.slice(0,4)}:{month:"",year:""}},e}();const fr=yr,gr=require("card-validator"),vr=function(){function e(){}return e.prototype.format=function(e){var t=(0,gr.number)(e).card;if(!t)return e;var n=(0,Z.max)((0,gr.creditCardType)(e).map((function(e){return(0,Z.max)(e.lengths)}))),r=this.unformat(e).slice(0,n);return t.gaps.filter((function(e){return r.length>e})).reduce((function(e,t,n){return[e.slice(0,t+n),e.slice(t+n)].join(" ")}),r)},e.prototype.unformat=function(e){return(0,gr.number)(e).card?e.replace(new RegExp(" ","g"),""):e},e}();function wr(e,t){void 0===t&&(t={});var n,r,i=e.currency.decimalPlaces,o=new sr(i);return{id:e.orderId,items:pr(e.lineItems,e.currency.decimalPlaces,"productId"),orderId:e.orderId,currency:e.currency.code,customerCanBeCreated:e.customerCanBeCreated,payment:Sr(e.payments,t.payment),subtotal:{amount:e.baseAmount,integerAmount:o.toInteger(e.baseAmount)},coupon:{discountedAmount:(0,Z.reduce)(e.coupons,(function(e,t){return e+t.discountedAmount}),0),coupons:e.coupons.map(dr)},discount:{amount:e.discountAmount,integerAmount:o.toInteger(e.discountAmount)},token:t.orderToken,callbackUrl:t.callbackUrl,discountNotifications:[],giftCertificate:(n=e.payments,r=(0,Z.filter)(n,{providerId:"giftcertificate"}),{totalDiscountedAmount:(0,Z.reduce)(r,(function(e,t){return t.amount+e}),0),appliedGiftCertificates:(0,Z.keyBy)(r.map((function(e){return{code:e.detail.code,discountedAmount:e.amount,remainingBalance:e.detail.remaining,giftCertificate:{balance:e.amount+e.detail.remaining,code:e.detail.code,purchaseDate:""}}})),"code")}),socialData:br(e),status:e.status,hasDigitalItems:e.hasDigitalItems,isDownloadable:e.isDownloadable,isComplete:e.isComplete,shipping:{amount:e.shippingCostTotal,integerAmount:o.toInteger(e.shippingCostTotal),amountBeforeDiscount:e.shippingCostBeforeDiscount,integerAmountBeforeDiscount:o.toInteger(e.shippingCostBeforeDiscount)},storeCredit:{amount:Cr(e.payments)},taxes:e.taxes,taxTotal:{amount:e.taxTotal,integerAmount:o.toInteger(e.taxTotal)},handling:{amount:e.handlingCostTotal,integerAmount:o.toInteger(e.handlingCostTotal)},grandTotal:{amount:e.orderAmount,integerAmount:e.orderAmountAsInteger}}}function Cr(e){var t=(0,Z.find)(e,{providerId:"storecredit"});return t?t.amount:0}function Sr(e,t){void 0===t&&(t={});var n,r=(0,Z.find)(e,Ir);return r?{id:r.providerId,status:(n=r.detail.step,"PAYMENT_STATUS_"+n),helpText:r.detail.instructions,returnUrl:t.returnUrl}:{}}function Ir(e){return"giftcertificate"!==e.providerId&&"storecredit"!==e.providerId}function br(e){var t={};return(0,s.__spreadArrays)(e.lineItems.physicalItems,e.lineItems.digitalItems).forEach((function(e){var n;t[e.id]=(n=e,["fb","tw","gp"].reduce((function(e,t){var r=n.socialMedia&&(0,Z.find)(n.socialMedia,(function(e){return e.code===t}));return r?(e[t]={name:n.name,description:n.name,image:n.imageUrl,url:r.link,shareText:r.text,sharingLink:r.link,channelName:r.channel,channelCode:r.code},e):e}),{}))})),t}function Pr(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}}var Er=function(){function e(){this._cardExpiryFormatter=new fr,this._cardNumberFormatter=new vr}return e.prototype.transform=function(e,t){var n,r=t.billingAddress.getBillingAddress(),i=t.checkout.getCheckout(),o=t.customer.getCustomer(),a=t.order.getOrder(),c=t.paymentMethods.getPaymentMethod(e.methodId,e.gatewayId),u=this._mapShippingAddress(t,c),d=t.consignments.getConsignments(),l=t.consignments.getShippingOption(),p=t.config.getStoreConfig(),_=t.config.getContextConfig(),y=t.instruments.getInstrumentsMeta(),f=t.paymentMethods.getPaymentMethodsMeta(),g=t.order.getOrderMeta(),v=o&&r&&_r(o,r),w=y&&e.paymentData&&(Gn(e.paymentData)||(n=e.paymentData.formattedPayload)&&("string"==typeof n.bigpay_token||Boolean(n.bigpay_token&&n.bigpay_token.token)))?t.payment.getPaymentToken()+", "+y.vaultAccessToken:t.payment.getPaymentToken();if(!w)throw new m(h.MissingPaymentToken);return{additionalAction:e.additionalAction,authToken:w,customer:v,billingAddress:r&&ar(r),shippingAddress:u&&ar(u,d),shippingOption:l&&Pr(l,!0),cart:i&&hr(i),order:a&&wr(a,g),orderMeta:g,payment:e.paymentData,paymentMethod:c&&this._transformPaymentMethod(c),quoteMeta:{request:(0,s.__assign)((0,s.__assign)({},f),{geoCountryCode:_&&_.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:(0,Z.pick)(p&&p.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}},e.prototype.transformWithHostedFormData=function(e,t,n){var r=t.additionalAction,i=t.authToken,o=t.checkout,a=t.config,c=t.order,u=t.orderMeta,d=t.payment,l=void 0===d?{}:d,p=t.paymentMethod,h=t.paymentMethodMeta,m=o&&o.consignments[0],_=m&&m.shippingAddress,y=m&&m.selectedShippingOption;return{additionalAction:r,authToken:i,paymentMethod:p&&this._transformPaymentMethod(p),customer:c&&c.billingAddress&&o&&_r(o.customer,c.billingAddress),billingAddress:c&&c.billingAddress&&ar(c.billingAddress),shippingAddress:_&&o&&ar(_,o.consignments),shippingOption:y&&Pr(y,!0),cart:o&&hr(o),order:c&&wr(c,u),orderMeta:u,payment:this._transformHostedInputValues(e,l,n),quoteMeta:{request:(0,s.__assign)((0,s.__assign)({},h),{geoCountryCode:a&&a.context.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:a&&(0,Z.pick)(a.storeConfig.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}},e.prototype._transformPaymentMethod=function(e){return"multi-option"!==e.method||e.gateway?e.initializationData&&e.initializationData.gateway?(0,s.__assign)((0,s.__assign)({},e),{id:e.initializationData.gateway}):e.id===mr.BRAINTREE_VENMO?(0,s.__assign)((0,s.__assign)({},e),{id:mr.BRAINTREE_PAYPAL}):e:(0,s.__assign)((0,s.__assign)({},e),{gateway:e.id})},e.prototype._transformHostedInputValues=function(e,t,n){return"instrumentId"in t?(0,s.__assign)((0,s.__assign)({},t),{ccCvv:e.cardCodeVerification,ccNumber:e.cardNumberVerification&&this._cardNumberFormatter.unformat(e.cardNumberVerification),hostedFormNonce:n}):(0,s.__assign)((0,s.__assign)({},t),{ccCvv:e.cardCode,ccExpiry:this._cardExpiryFormatter.toObject(e.cardExpiry||""),ccName:e.cardName||"",ccNumber:this._cardNumberFormatter.unformat(e.cardNumber||""),hostedFormNonce:n})},e.prototype._mapShippingAddress=function(e,t){var n,r,i,o;if(t){var a=null===(r=null===(n=t.initializationData)||void 0===n?void 0:n.bopis)||void 0===r?void 0:r.enabled,s=null===(o=null===(i=t.initializationData)||void 0===i?void 0:i.bopis)||void 0===o?void 0:o.requiredAddress,c=e.consignments.getConsignments(),u=null==c?void 0:c.every((function(e){return e.selectedPickupOption}));if(a&&u&&"none"===s)return}return e.shippingAddress.getShippingAddress()},e}();const Ar=Er;var Or;!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"}(Or||(Or={}));var kr=function(){function e(e,t){this._consignmentRequestSender=e,this._checkoutRequestSender=t}return e.prototype.unassignItemsByAddress=function(e,t){var n=this;return function(r){var i=r.getState();if(!i.checkout.getCheckout())throw new m(h.MissingCheckout);var o=n._consignmentHasAddress(e)?e.address:e.shippingAddress,a=i.consignments.getConsignmentByAddress(o);if(!a)throw new ae("No consignment found for the specified address");var s=n._removeLineItems(e.lineItems,a,i.cart.getCart());return s.length?n.updateConsignment({id:a.id,address:o,lineItems:s},t)(r):n.deleteConsignment(a.id,t)(r)}},e.prototype.assignItemsByAddress=function(e,t){var n=this;return function(r){var i=r.getState(),o=n._consignmentHasAddress(e)?e.address:e.shippingAddress,a=i.consignments.getConsignmentByAddress(o);return n._createOrUpdateConsignment({id:a&&a.id,address:o,lineItems:n._addLineItems(e.lineItems,a,i.cart.getCart())},t)(r)}},e.prototype.selectShippingOption=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o=r.getState(),a=o.checkout.getCheckout(),s=o.consignments.getConsignments();if(!a)throw new m(h.MissingCheckout);if(!s||!s.length)throw new m(h.MissingConsignments);var u={id:s[0].id,shippingOptionId:e},d={id:s[0].id};i.next((0,c.createAction)(Or.UpdateShippingOptionRequested,void 0,d)),n._consignmentRequestSender.updateConsignment(a.id,u,t).then((function(e){var t=e.body;i.next((0,c.createAction)(Or.UpdateShippingOptionSucceeded,t,d)),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(Or.UpdateShippingOptionFailed,e,d))}))}))}},e.prototype.loadShippingOptions=function(e){var t=this;return function(n){return u.Observable.create((function(r){var i=n.getState().checkout.getCheckout();if(!i)throw new m(h.MissingCheckout);r.next((0,c.createAction)(Or.LoadShippingOptionsRequested)),t._checkoutRequestSender.loadCheckout(i.id,(0,s.__assign)((0,s.__assign)({},e),{params:{include:[J.AvailableShippingOptions]}})).then((function(e){var t=e.body;r.next((0,c.createAction)(Or.LoadShippingOptionsSucceeded,t)),r.complete()})).catch((function(e){r.error((0,c.createErrorAction)(Or.LoadShippingOptionsFailed,e))}))}))}},e.prototype.updateAddress=function(e,t){var n=this;return function(r){var i=n._getUpdateAddressRequestBody(e,r),o=r.getState().consignments.getConsignments();return o&&o.length&&(i.id=o[0].id),n._createOrUpdateConsignment(i,t)(r)}},e.prototype.createConsignments=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o=r.getState().checkout.getCheckout();if(!o||!o.id)throw new m(h.MissingCheckout);i.next((0,c.createAction)(Or.CreateConsignmentsRequested)),n._consignmentRequestSender.createConsignments(o.id,e,t).then((function(e){var t=e.body;i.next((0,c.createAction)(Or.CreateConsignmentsSucceeded,t)),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(Or.CreateConsignmentsFailed,e))}))}))}},e.prototype.updateConsignment=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o=r.getState().checkout.getCheckout();if(!o||!o.id)throw new m(h.MissingCheckout);var a={id:e.id};i.next((0,c.createAction)(Or.UpdateConsignmentRequested,void 0,a)),n._consignmentRequestSender.updateConsignment(o.id,e,t).then((function(e){var t=e.body;i.next((0,c.createAction)(Or.UpdateConsignmentSucceeded,t,a)),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(Or.UpdateConsignmentFailed,e,a))}))}))}},e.prototype.deleteConsignment=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o=r.getState().checkout.getCheckout(),a={id:e};if(!o||!o.id)throw new m(h.MissingCheckout);i.next((0,c.createAction)(Or.DeleteConsignmentRequested,void 0,a)),n._consignmentRequestSender.deleteConsignment(o.id,e,t).then((function(e){var t=e.body;i.next((0,c.createAction)(Or.DeleteConsignmentSucceeded,t,a)),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(Or.DeleteConsignmentFailed,e,a))}))}))}},e.prototype.updateShippingOption=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o=r.getState().checkout.getCheckout();if(!o||!o.id)throw new m(h.MissingCheckout);var a={id:e.id};i.next((0,c.createAction)(Or.UpdateShippingOptionRequested,void 0,a)),n._consignmentRequestSender.updateConsignment(o.id,e,t).then((function(e){var t=e.body;i.next((0,c.createAction)(Or.UpdateShippingOptionSucceeded,t,a)),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(Or.UpdateShippingOptionFailed,e,a))}))}))}},e.prototype._createOrUpdateConsignment=function(e,t){var n=this;return function(r){var i=r.getState().checkout.getCheckout();if(!i||!i.id)throw new m(h.MissingCheckout);return n._isUpdateConsignmentRequest(e)?n.updateConsignment(e,t)(r):n.createConsignments([e],t)(r)}},e.prototype._getUpdateAddressRequestBody=function(e,t){var n=t.getState().cart.getCart();if(!n)throw new m(h.MissingCart);var r=n.lineItems,i=r.physicalItems,o=r.customItems,a=void 0===o?[]:o;return{address:e,lineItems:(0,s.__spreadArrays)(i,a).map((function(e){return{itemId:e.id,quantity:e.quantity}}))}},e.prototype._removeLineItems=function(e,t,n){if(!n)throw new m(h.MissingCart);return this._hydrateLineItems(t.lineItemIds,n).map((function(t){var n=(0,Z.find)(e,(function(e){return e.itemId===t.itemId}));return(0,s.__assign)((0,s.__assign)({},t),{quantity:n?t.quantity-n.quantity:t.quantity})})).filter((function(e){return e.quantity>0}))},e.prototype._addLineItems=function(e,t,n){if(!t)return e;if(!n)throw new m(h.MissingCart);return e.concat(this._hydrateLineItems(t.lineItemIds,n)).filter((function(e){return e.quantity>0}))},e.prototype._hydrateLineItems=function(e,t){return e.map((function(e){var n=(0,Z.find)(t.lineItems.physicalItems,(function(t){return t.id===e}));return{itemId:e,quantity:n?n.quantity:0}}))},e.prototype._isUpdateConsignmentRequest=function(e){return!!e.id},e.prototype._consignmentHasAddress=function(e){return"object"==typeof e&&"address"in e},e}();const Tr=kr;var Mr=["consignments.availableShippingOptions","cart.lineItems.physicalItems.options","cart.lineItems.digitalItems.options","customer","promotions.banners"],Dr=function(){function e(e){this._requestSender=e}return e.prototype.createConsignments=function(e,t,n){var r=void 0===n?{}:n,i=r.timeout,o=r.params,a=(void 0===o?{}:o).include,c="/api/storefront/checkouts/"+e+"/consignments",u=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.post(c,{body:t,params:{include:xt(Mr,a)},headers:u,timeout:i})},e.prototype.updateConsignment=function(e,t,n){var r=void 0===n?{}:n,i=r.timeout,o=r.params,a=(void 0===o?{}:o).include,c=t.id,u=(0,s.__rest)(t,["id"]),d="/api/storefront/checkouts/"+e+"/consignments/"+c,l=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.put(d,{body:u,params:{include:xt(Mr,a)},headers:l,timeout:i})},e.prototype.deleteConsignment=function(e,t,n){var r=(void 0===n?{}:n).timeout,i="/api/storefront/checkouts/"+e+"/consignments/"+t,o=(0,s.__assign)({Accept:w.JsonV1},C),a=Q(Mr);return this._requestSender.delete(i,{params:{include:a},headers:o,timeout:r})},e}();const Rr=Dr;var zr;!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"}(zr||(zr={}));var Nr=function(){function e(e,t){this._googleRecaptcha=e,this._requestSender=t}return e.prototype.initialize=function(e){var t=this;return function(n){return(0,u.concat)((0,u.of)((0,c.createAction)(zr.InitializeRequested,void 0)),(0,u.defer)((function(){return(0,s.__awaiter)(t,void 0,void 0,(function(){var t,r,i,o,a;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return t=e?e.containerId:"spamProtectionContainer",e||document.getElementById(t)||((r=document.createElement("div")).setAttribute("id",t),document.body.appendChild(r)),i=n.getState(),o=i.config.getStoreConfigOrThrow(),a=o.checkoutSettings.googleRecaptchaSitekey,[4,this._googleRecaptcha.load(t,a)];case 1:return s.sent(),[2,(0,c.createAction)(zr.InitializeSucceeded)]}}))}))}))).pipe((0,d.catchError)((function(e){return l(zr.InitializeFailed,e)})))}},e.prototype.verifyCheckoutSpamProtection=function(){var e=this;return function(t){return(0,u.defer)((function(){var n=t.getState().checkout.getCheckout();if(!n)throw new m(h.MissingCheckout);return(0,u.concat)((0,u.of)((0,c.createAction)(zr.VerifyCheckoutRequested)),(0,u.from)(e.execute()(t)).pipe((0,d.switchMap)((function(t){return Dt(t)&&t.payload?(0,u.from)(e._requestSender.validate(n.id,t.payload.token)).pipe((0,d.switchMap)((function(e){var n=e.body;return(0,u.concat)((0,u.of)(t),(0,u.of)((0,c.createAction)(zr.VerifyCheckoutSucceeded,n)))}))):(0,u.of)(t)})))).pipe((0,d.catchError)((function(e){return l(zr.VerifyCheckoutFailed,e)})))}))}},e.prototype.execute=function(){var e=this;return function(t){return(0,u.concat)((0,u.of)((0,c.createAction)(zr.ExecuteRequested)),e.initialize()(t),e._googleRecaptcha.execute().pipe((0,d.take)(1)).pipe((0,d.switchMap)((function(t){var n=t.error,r=t.token;return(0,s.__awaiter)(e,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){if(n instanceof vn)throw n;if(n||!r)throw new En;return[2,(0,c.createAction)(zr.ExecuteSucceeded,{token:r})]}))}))})))).pipe((0,d.catchError)((function(e){return l(zr.ExecuteFailed,e)})))}},e}();const Lr=Nr;var Fr=function(){function e(e){this._requestSender=e}return e.prototype.validate=function(e,t,n){var r=(void 0===n?{}:n).timeout,i="/api/storefront/checkouts/"+e+"/spam-protection",o=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.post(i,{body:{token:t},headers:o,timeout:r})},e}();const Br=Fr;var Ur;!function(e){e.ApplyStoreCreditRequested="APPLY_STORE_CREDIT_REQUESTED",e.ApplyStoreCreditSucceeded="APPLY_STORE_CREDIT_SUCCEEDED",e.ApplyStoreCreditFailed="APPLY_STORE_CREDIT_FAILED"}(Ur||(Ur={}));var xr=function(){function e(e){this._storeCreditRequestSender=e}return e.prototype.applyStoreCredit=function(e,t){var n=this;return function(r){return(0,u.concat)((0,u.of)((0,c.createAction)(Ur.ApplyStoreCreditRequested)),(0,u.defer)((function(){return(0,s.__awaiter)(n,void 0,void 0,(function(){var n,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:if(n=r.getState(),!(i=n.checkout.getCheckout()))throw new m(h.MissingCheckout);return[4,e?this._storeCreditRequestSender.applyStoreCredit(i.id,t):this._storeCreditRequestSender.removeStoreCredit(i.id,t)];case 1:return o=a.sent().body,[2,(0,c.createAction)(Ur.ApplyStoreCreditSucceeded,o)]}}))}))}))).pipe((0,d.catchError)((function(e){return l(Ur.ApplyStoreCreditFailed,e)})))}},e}();const qr=xr;var Vr=function(){function e(e){this._requestSender=e}return e.prototype.applyStoreCredit=function(e,t){var n=(void 0===t?{}:t).timeout,r="/api/storefront/checkouts/"+e+"/store-credit",i=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.post(r,{headers:i,timeout:n,params:{include:Q(K)}})},e.prototype.removeStoreCredit=function(e,t){var n=(void 0===t?{}:t).timeout,r="/api/storefront/checkouts/"+e+"/store-credit",i=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.delete(r,{headers:i,timeout:n,params:{include:Q(K)}})},e}();const Gr=Vr;var Hr;!function(e){e.UpdateSubscriptionsRequested="UPDATE_SUBSCRIPTIONS_REQUESTED",e.UpdateSubscriptionsSucceeded="UPDATE_SUBSCRIPTIONS_SUCCEEDED",e.UpdateSubscriptionsFailed="UPDATE_SUBSCRIPTIONS_FAILED"}(Hr||(Hr={}));const Yr=function(e){function t(t){var n=e.call(this,t)||this;return n.name="UpdateSubscriptionsError",n.type="update_subscriptions",n}return(0,s.__extends)(t,e),t}(x);var jr=function(){function e(e){this._subscriptionsRequestSender=e}return e.prototype.updateSubscriptions=function(e,t){var n=this;return(0,u.concat)((0,u.of)((0,c.createAction)(Hr.UpdateSubscriptionsRequested)),(0,u.defer)((function(){return(0,s.__awaiter)(n,void 0,void 0,(function(){var n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._subscriptionsRequestSender.updateSubscriptions(e,t)];case 1:return n=r.sent().body,[2,(0,c.createAction)(Hr.UpdateSubscriptionsSucceeded,n)]}}))}))}))).pipe((0,d.catchError)((function(e){return l(Hr.UpdateSubscriptionsFailed,new Yr(e))})))},e}();const Wr=jr;var Kr=function(){function e(e){this._requestSender=e}return e.prototype.updateSubscriptions=function(e,t){var n=(void 0===t?{}:t).timeout,r=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.post("/api/storefront/subscriptions",{body:e,headers:r,timeout:n})},e}();const Jr=Kr;function Zr(e){return(0,Z.isPlainObject)(e)}var Qr=(0,Z.memoize)((function(e){return Array.isArray(e)?e.map((function(e){return Xr(e)})):Zr(e)?Object.keys(e).reduce((function(t,n){var r;return(0,s.__assign)((0,s.__assign)({},t),((r={})[n]=Xr(e[n]),r))}),{}):e}));Qr.cache=new WeakMap;var Xr=function(e){return"object"==typeof e&&null!==e?Qr(e):e};function $r(e){return function(){for(var t=[],n=0;n\n Tell Me More',e.appendChild(n),n},e}();const Oo=Ao;function ko(e){var t=e.billingAddress,n=e.email,r=e.firstName,i=e.lastName,o=e.phone,a=e.shippingAddress,s=t||a;return{email:n,first_name:r,last_name:i,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 To(e){var t=e.email,n=e.phone,r=e.shippingAddress,i=((null==r?void 0:r.recipientName)||"").split(" ");return{email:t,first_name:i[0]||"",last_name:i[1]||"",phone_number:n,address_line_1:null==r?void 0:r.line1,address_line_2:null==r?void 0:r.line2,city:null==r?void 0:r.city,state:null==r?void 0:r.state,country_code:null==r?void 0:r.countryCode,postal_code:null==r?void 0:r.postalCode}}function Mo(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 Do,Ro,zo,No,Lo;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(Do||(Do={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(Ro||(Ro={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black"}(zo||(zo={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(No||(No={})),function(e){e.PILL="pill",e.RECT="rect"}(Lo||(Lo={}));var Fo=function(){function e(e,t,n,r,i,o,a){this._store=e,this._checkoutActionCreator=t,this._customerActionCreator=n,this._paymentMethodActionCreator=r,this._braintreeSDKCreator=i,this._formPoster=o,this._window=a}return e.prototype.initialize=function(e){var t,n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d,l,p,_,y,f,g=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(r=e.braintreepaypalcredit,i=e.methodId,a=(o=r||{}).container,c=o.buttonHeight,u=void 0===c?40:c,!i)throw new ae('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new ae('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');if(!a)throw new ae('Unable to initialize payment because "braintreepaypalcredit.container" argument is not provided.');return[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(i))];case 1:if(d=s.sent(),!(l=d.paymentMethods.getPaymentMethodOrThrow(i)).clientToken)throw new m(h.MissingPaymentMethod);return p=d.cart.getCartOrThrow().currency.code,_={currency:p,intent:null===(t=l.initializationData)||void 0===t?void 0:t.intent,isCreditEnabled:null===(n=l.initializationData)||void 0===n?void 0:n.isCreditEnabled},y=function(e){return g._renderPayPalButton(e,r,i,Boolean(l.config.testMode),u)},f=function(e){return g._handleError(e,r)},this._braintreeSDKCreator.initialize(l.clientToken),[4,this._braintreeSDKCreator.getPaypalCheckout(_,y,f)];case 2:return s.sent(),[2,this._store.getState()]}}))}))},e.prototype.deinitialize=function(){return this._braintreeSDKCreator.teardown(),Promise.resolve(this._store.getState())},e.prototype.signIn=function(e,t){return this._store.dispatch(this._customerActionCreator.signInCustomer(e,t))},e.prototype.signOut=function(e){return this._store.dispatch(this._customerActionCreator.signOutCustomer(e))},e.prototype.executePaymentMethodCheckout=function(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve(this._store.getState())},e.prototype._renderPayPalButton=function(e,t,n,r,i){var o=this,a=t.container,c=this._window.paypal,u=!1;if(c){var d=[c.FUNDING.PAYLATER,c.FUNDING.CREDIT],l={height:i,color:zo.GOLD};d.forEach((function(i){var d=i===c.FUNDING.CREDIT?(0,s.__assign)({label:No.CREDIT},l):l;if(!u){var p=c.Buttons({env:r?"sandbox":"production",commit:!1,fundingSource:i,style:d,createOrder:function(){return o._setupPayment(e,t,n)},onApprove:function(r){return o._tokenizePayment(r,e,t,n)}});p.isEligible()&&(p.render("#"+a),u=!0)}}))}c&&u||this._removeElement(a)},e.prototype._setupPayment=function(e,t,n){var r;return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u,d,l,p;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return s.trys.push([0,3,,4]),[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 1:return i=s.sent(),o=i.customer.getCustomer(),a=i.checkout.getCheckoutOrThrow().outstandingBalance,c=i.cart.getCartOrThrow().currency.code,u=i.paymentMethods.getPaymentMethodOrThrow(n),d=null==o?void 0:o.addresses[0],l=d?Mo(d):void 0,[4,e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:l,amount:a,currency:c,offerCredit:!0,intent:null===(r=u.initializationData)||void 0===r?void 0:r.intent})];case 2:return[2,s.sent()];case 3:return p=s.sent(),this._handleError(p,t),[3,4];case 4:return[2]}}))}))},e.prototype._tokenizePayment=function(e,t,n,r){return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return s.trys.push([0,3,,4]),[4,this._braintreeSDKCreator.getDataCollector({paypal:!0})];case 1:return i=s.sent().deviceData,[4,t.tokenizePayment(e)];case 2:return o=s.sent(),a=o.details,c=o.nonce,this._formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:r,action:"set_external_checkout",nonce:c,device_data:i,billing_address:JSON.stringify(ko(a)),shipping_address:JSON.stringify(To(a))}),[2,o];case 3:return u=s.sent(),this._handleError(u,n),[3,4];case 4:return[2]}}))}))},e.prototype._handleError=function(e,t){var n=t.container,r=t.onError;if(this._removeElement(n),!r)throw e;r(e)},e.prototype._removeElement=function(e){var t=e&&document.getElementById(e);t&&t.remove()},e}();const Bo=Fo;var Uo=function(){function e(e,t,n,r,i,o){this._store=e,this._paymentMethodActionCreator=t,this._remoteCheckoutActionCreator=n,this._chasePayScriptLoader=r,this._requestSender=i,this._formPoster=o}return e.prototype.initialize=function(e){var t=this,n=e.chasepay,r=e.methodId;if(!n||!r)throw new ae('Unable to proceed because "options.chasepay" argument is not provided.');return this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(r)).then((function(e){t._paymentMethod=e.paymentMethods.getPaymentMethod(r);var i=e.cart.getCart(),o=e.config.getStoreConfig();if(!i)throw new m(h.MissingCart);if(!o)throw new m(h.MissingCheckoutConfig);if(!t._paymentMethod||!t._paymentMethod.initializationData.digitalSessionId)throw new Pn(bn.PaymentNotInitialized);var a=n.container;return t._chasePayScriptLoader.load(t._paymentMethod.config.testMode).then((function(e){var n=e.ChasePay;n.configure({language:o.storeProfile.storeLanguage}),n.isChasePayUp&&n.insertButtons({containers:[a]}),n.on(n.EventType.START_CHECKOUT,(function(){t._store.dispatch(t._paymentMethodActionCreator.loadPaymentMethod(r)).then((function(){var e=t._store.getState().paymentMethods.getPaymentMethod(r),i=e&&e.initializationData&&e.initializationData.digitalSessionId;i&&n.startCheckout(i)}))})),n.on(n.EventType.COMPLETE_CHECKOUT,(function(e){var n=t._store.getState().paymentMethods.getPaymentMethod(r),i=n&&n.initializationData&&n.initializationData.merchantRequestId;i&&t._setExternalCheckoutData(e,i).then((function(){t._reloadPage()}))}))}))})).then((function(){return t._store.getState()}))},e.prototype.deinitialize=function(){return Promise.resolve(this._store.getState())},e.prototype.signIn=function(){throw new bo('In order to sign in via Chase Pay®, the shopper must click on "Chase Pay®" button.')},e.prototype.signOut=function(e){var t=this._store.getState().payment.getPaymentId();return t?this._store.dispatch(this._remoteCheckoutActionCreator.signOut(t.providerId,e)):Promise.resolve(this._store.getState())},e.prototype.executePaymentMethodCheckout=function(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve(this._store.getState())},e.prototype._setExternalCheckoutData=function(e,t){var n={headers:(0,s.__assign)({Accept:"text/html","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},C),body:{sessionToken:e.sessionToken,merchantRequestId:t},method:"post"};return this._requestSender.sendRequest("checkout.php?provider=chasepay&action=set_external_checkout",n)},e.prototype._reloadPage=function(){this._formPoster.postForm("/checkout.php",{headers:(0,s.__assign)({Accept:"text/html","Content-Type":"application/x-www-form-urlencoded"},C),params:{fromChasePay:!0}})},e}();const xo=Uo;var qo=function(){function e(e,t){this._store=e,this._customerActionCreator=t}return e.prototype.signIn=function(e,t){return this._store.dispatch(this._customerActionCreator.signInCustomer(e,t))},e.prototype.signOut=function(e){return this._store.dispatch(this._customerActionCreator.signOutCustomer(e))},e.prototype.executePaymentMethodCheckout=function(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve(this._store.getState())},e.prototype.initialize=function(){return Promise.resolve(this._store.getState())},e.prototype.deinitialize=function(){return Promise.resolve(this._store.getState())},e}();const Vo=qo;var Go;!function(e){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"}(Go||(Go={}));const Ho=Go;var Yo=function(){function e(e,t,n,r){this._store=e,this._remoteCheckoutActionCreator=t,this._googlePayPaymentProcessor=n,this._formPoster=r}return e.prototype.initialize=function(e){var t=this,n=e.methodId,r=this._getGooglePayOptions(e);if(!n)throw new m(h.MissingPaymentMethod);return this._googlePayPaymentProcessor.initialize(n).then((function(){t._walletButton=t._createSignInButton(r.container,r)})).then((function(){return t._store.getState()}))},e.prototype.deinitialize=function(){var e=this;return this._walletButton&&this._walletButton.parentNode&&(this._walletButton.parentNode.removeChild(this._walletButton),this._walletButton=void 0),this._googlePayPaymentProcessor.deinitialize().then((function(){return e._store.getState()}))},e.prototype.signIn=function(){throw new bo('In order to sign in via Google Pay, the shopper must click on "Google Pay" button.')},e.prototype.signOut=function(e){var t=this._store.getState().payment.getPaymentId();return t?this._store.dispatch(this._remoteCheckoutActionCreator.forgetCheckout(t.providerId,e)):Promise.resolve(this._store.getState())},e.prototype.executePaymentMethodCheckout=function(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve(this._store.getState())},e.prototype._createSignInButton=function(e,t){var n=document.querySelector("#"+e),r=t.buttonType,i=t.buttonColor;if(!n)throw new ae("Unable to create sign-in button without valid container ID.");var o=this._googlePayPaymentProcessor.createButton(this._handleWalletButtonClick,r,i);return n.appendChild(o),o},e.prototype._getGooglePayOptions=function(e){if(e.methodId===Ho.GOOGLEPAY_ADYENV2&&e.googlepayadyenv2)return e.googlepayadyenv2;if(e.methodId===Ho.GOOGLEPAY_ADYENV3&&e.googlepayadyenv3)return e.googlepayadyenv3;if(e.methodId===Ho.GOOGLEPAY_AUTHORIZENET&&e.googlepayauthorizenet)return e.googlepayauthorizenet;if(e.methodId===Ho.GOOGLEPAY_BNZ&&e.googlepaybnz)return e.googlepaybnz;if(e.methodId===Ho.GOOGLEPAY_BRAINTREE&&e.googlepaybraintree)return e.googlepaybraintree;if(e.methodId===Ho.GOOGLEPAY_CHECKOUTCOM&&e.googlepaycheckoutcom)return e.googlepaycheckoutcom;if(e.methodId===Ho.GOOGLEPAY_CYBERSOURCEV2&&e.googlepaycybersourcev2)return e.googlepaycybersourcev2;if(e.methodId===Ho.GOOGLEPAY_ORBITAL&&e.googlepayorbital)return e.googlepayorbital;if(e.methodId===Ho.GOOGLEPAY_STRIPE&&e.googlepaystripe)return e.googlepaystripe;if(e.methodId===Ho.GOOGLEPAY_STRIPEUPE&&e.googlepaystripeupe)return e.googlepaystripeupe;if(e.methodId===Ho.GOOGLEPAY_WORLDPAYACCESS&&e.googlepayworldpayaccess)return e.googlepayworldpayaccess;throw new ae},e.prototype._handleWalletButtonClick=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:e.preventDefault(),t=this._store.getState().cart.getCartOrThrow(),n=si(t)>0,r={transactionInfo:{currencyCode:t.currency.code,totalPrice:String(t.cartAmount)}},this._googlePayPaymentProcessor.updatePaymentDataRequest(r),a.label=1;case 1:return a.trys.push([1,7,,8]),[4,this._googlePayPaymentProcessor.displayWallet()];case 2:return i=a.sent(),[4,this._googlePayPaymentProcessor.handleSuccess(i)];case 3:return a.sent(),n&&i.shippingAddress?[4,this._googlePayPaymentProcessor.updateShippingAddress(i.shippingAddress)]:[3,5];case 4:a.sent(),a.label=5;case 5:return[4,this._onPaymentSelectComplete()];case 6:return a.sent(),[3,8];case 7:if((o=a.sent())&&"CANCELED"!==o.message)throw o;return[3,8];case 8:return[2]}}))}))},e.prototype._onPaymentSelectComplete=function(){var e=this._store.getState().config.getStoreConfigOrThrow().links.siteLink;this._formPoster.postForm("/embedded-checkout"===window.location.pathname?e+"/checkout":"/checkout.php",{headers:(0,s.__assign)({Accept:"text/html","Content-Type":"application/x-www-form-urlencoded"},C)})},(0,s.__decorate)([yn],e.prototype,"_handleWalletButtonClick",null),e}();const jo=Yo;function Wo(e){return window.location.origin+"/checkout.php?action=set_external_checkout&provider=masterpass&gateway=stripe&origin="+e}var Ko={es:["es_es","es_mx","es_pe","es_co","es_ar","es_cl"],en:["en_us","en_gb","en_ca","en_es","en_fr","en_ie","en_sg","en_au","en_nz","en_my","en_hk","en_th","en_ae","en_sa","en_qa","en_kw","en_za"],pt:["pt_br"],zu:["zu_za"],ar:["ar_sa","ar_ae","ar_qa","ar_kw"],zh:["zh_sg","zh_hk"],ms:["ms_my"],uk:["uk_ua"],sv:["sv_se"],hr:["hr_hr"],pl:["pl_pl"],nl:["nl_be"],it:["it_it"],de:["de_de"],fr:["fr_fr","fr_ca"]};function Jo(e){var t=e.replace("-","_").toLowerCase().split("_"),n=t[0],r=n+"_"+t[1],i=Ko[n];return i?i.indexOf(r)>-1?r:i[0]:"en_us"}var Zo=function(){function e(e,t,n,r,i){this._store=e,this._paymentMethodActionCreator=t,this._remoteCheckoutActionCreator=n,this._masterpassScriptLoader=r,this._locale=i}return e.prototype.initialize=function(e){var t=this,n=e.masterpass,r=e.methodId;if(!n||!r)throw new ae('Unable to proceed because "options.masterpass" argument is not provided.');return this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(r)).then((function(e){if(t._paymentMethod=e.paymentMethods.getPaymentMethod(r),!t._paymentMethod||!t._paymentMethod.initializationData.checkoutId)throw new m(h.MissingPaymentMethod);var i=e.cart.getCart();if(!i)throw new m(h.MissingCart);var o=n.container,a={checkoutId:t._paymentMethod.initializationData.checkoutId,allowedCardTypes:t._paymentMethod.initializationData.allowedCardTypes,amount:i.cartAmount.toString(),currency:i.currency.code,cartId:i.id,suppressShippingAddress:!1,callbackUrl:Wo("checkout")},s={useMasterpassSrc:t._paymentMethod.initializationData.isMasterpassSrcEnabled,language:Jo(t._locale),testMode:t._paymentMethod.config.testMode,checkoutId:t._paymentMethod.initializationData.checkoutId};return t._masterpassScriptLoader.load(s).then((function(e){t._signInButton=t._createSignInButton(o),t._signInButton.addEventListener("click",(function(){e.checkout(a)}))}))})).then((function(){return t._store.getState()}))},e.prototype.deinitialize=function(){return this._paymentMethod=void 0,this._signInButton&&this._signInButton.parentNode&&(this._signInButton.parentNode.removeChild(this._signInButton),this._signInButton=void 0),Promise.resolve(this._store.getState())},e.prototype.signIn=function(){throw new bo('In order to sign in via Masterpass, the shopper must click on "Masterpass" button.')},e.prototype.signOut=function(e){var t=this._store.getState().payment.getPaymentId();return t?this._store.dispatch(this._remoteCheckoutActionCreator.signOut(t.providerId,e)):Promise.resolve(this._store.getState())},e.prototype.executePaymentMethodCheckout=function(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve(this._store.getState())},e.prototype._createSignInButton=function(e){var t=document.querySelector("#"+e);if(!this._paymentMethod||!this._paymentMethod.initializationData.checkoutId)throw new m(h.MissingPaymentMethod);if(!t)throw new ae("Unable to create sign-in button without valid container ID.");var n=document.createElement("input");if(n.type="image",this._paymentMethod.initializationData.isMasterpassSrcEnabled){var r=this._paymentMethod.config.testMode?"sandbox.":"",i=this._paymentMethod.initializationData.checkoutId,o=["locale="+Jo(this._locale),"paymentmethod=master,visa,amex,discover","checkoutid="+i];n.src=["https://"+r+"src.mastercard.com/assets/img/btn/src_chk_btn_126x030px.svg",o.join("&")].join("?")}else n.src="https://static.masterpass.com/dyn/img/btn/global/mp_chk_btn_160x037px.svg";return t.appendChild(n),n},e}();const Qo=Zo;var Xo=function(){function e(e,t){this._store=e,this._remoteCheckoutActionCreator=t}return e.prototype.signIn=function(){throw new bo('In order to sign in via Masterpass, the shopper must click on "Masterpass" button.')},e.prototype.signOut=function(e){var t=this._store.getState().payment.getPaymentId();return t?this._store.dispatch(this._remoteCheckoutActionCreator.signOut(t.providerId,e)):Promise.resolve(this._store.getState())},e.prototype.initialize=function(){return Promise.resolve(this._store.getState())},e.prototype.deinitialize=function(){return Promise.resolve(this._store.getState())},e.prototype.executePaymentMethodCheckout=function(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve(this._store.getState())},e}();const $o=Xo;var ea,ta,na,ra,ia;!function(e){e.SHIPPING="shipping",e.BILLING="billing"}(ea||(ea={})),function(e){e.SPLIT="split",e.FULL="full",e.ORGANIZATION="organization"}(ta||(ta={})),function(e){e.CreditCard="card",e.SOFORT="sofort",e.EPS="eps",e.GRABPAY="grabpay",e.BANCONTACT="bancontact",e.IDEAL="ideal",e.GIROPAY="giropay",e.ALIPAY="alipay",e.KLARNA="klarna"}(na||(na={})),function(e){e.NEVER="never",e.AUTO="auto",e.ALWAYS="always",e.PAYMENT="payment",e.IF_REQUIRED="if_required"}(ra||(ra={})),function(e){e.PAYMENT="payment",e.AUTHENTICATION="linkAuthentication",e.SHIPPING="address"}(ia||(ia={}));var oa=function(){function e(e,t,n,r,i){this._store=e,this._stripeUPEScriptLoader=t,this._customerActionCreator=n,this._paymentMethodActionCreator=r,this._consignmentActionCreator=i}return e.prototype.initialize=function(e){var t;return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,u,d,l,p,_,y,f,g,v,w,C,S,I,b,P,E,A,O,k,T,M,D,R,z,N,L=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!e.stripeupe)throw new ae('Unable to proceed because "options" argument is not provided.');return r=e.stripeupe,i=r.container,o=r.gatewayId,a=r.methodId,u=r.onEmailChange,d=r.getStyles,l=r.isLoading,Object.entries(e.stripeupe).forEach((function(e){var t=e[0];if(!e[1])throw new ae('Unable to proceed because "'+t+'" argument is not provided.')})),[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(o,{params:{method:a}}))];case 1:if(p=s.sent(),_=p.paymentMethods.getPaymentMethodOrThrow,y=p.customer.getCustomerOrThrow,f=_(a,o),g=f.clientToken,v=f.initializationData,C=(w=void 0===v?{}:v).stripePublishableKey,S=w.stripeConnectedAccount,I=y(),b=I.email,P=I.isStripeLinkAuthenticated,b)return[3,3];if(!C||!g)throw new m(h.MissingPaymentToken);return E=void 0,A="function"==typeof d&&d(),E=A?{variables:{colorPrimary:A.fieldInnerShadow,colorBackground:A.fieldBackground,colorText:A.labelText,colorDanger:A.fieldErrorText,colorTextSecondary:A.labelText,colorTextPlaceholder:A.fieldPlaceholderText},rules:{".Input":{borderColor:A.fieldBorder,color:A.fieldText,boxShadow:A.fieldInnerShadow}}}:{},[4,this._stripeUPEScriptLoader.getStripeClient(C,S)];case 2:n=s.sent(),this._stripeElements=this._stripeUPEScriptLoader.getElements(n,{clientSecret:g,appearance:E}),O=this._store.getState(),k=O.billingAddress.getBillingAddress,T=O.consignments.getConsignments,M=T(),D=null===(t=null==M?void 0:M[0])||void 0===t?void 0:t.id,R=(k()||{}).email,z=R?{defaultValues:{mode:ea.SHIPPING,email:R}}:{},(N=this._stripeElements.getElement(ia.AUTHENTICATION)||this._stripeElements.create(ia.AUTHENTICATION,z)).on("change",(function(e){if(!("authenticated"in e))throw new m(h.MissingCustomer);L._store.dispatch((0,c.createAction)(Rt.StripeLinkAuthenticated,e.authenticated)),e.complete?u(e.authenticated,e.value.email):u(!1,""),l&&l(!1),void 0===P&&e.authenticated&&D&&L._store.dispatch(L._consignmentActionCreator.deleteConsignment(D))})),N.mount("#"+i),s.label=3;case 3:return[2,this._store.getState()]}}))}))},e.prototype.deinitialize=function(){var e,t;return null===(t=null===(e=this._stripeElements)||void 0===e?void 0:e.getElement(ia.AUTHENTICATION))||void 0===t||t.unmount(),Promise.resolve(this._store.getState())},e.prototype.signIn=function(e,t){return this._store.dispatch(this._customerActionCreator.signInCustomer(e,t))},e.prototype.signOut=function(e){return this._store.dispatch(this._customerActionCreator.signOutCustomer(e))},e.prototype.executePaymentMethodCheckout=function(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve(this._store.getState())},e}();const aa=oa;var sa,ca=function(e){function t(t){var n=e.call(this,t||"Unable to proceed due to no extension configured for this region.")||this;return n.name="ExtensionNotFoundError",n.type="extension_not_found",n}return(0,s.__extends)(t,e),t}(p);!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"}(sa||(sa={}));var ua=function(e){function t(t){var n=e.call(this,t||"Unable to proceed due to invalid configuration provided for the extension.")||this;return n.name="InvalidExtensionConfigError",n.type="invalid_extension_config",n}return(0,s.__extends)(t,e),t}(p),da=function(){function e(e,t,n){this._containerId=e,this._extension=t,this._cartId=n;var r=new URL(this._extension.url);r.searchParams.set("extensionId",this._extension.id),r.searchParams.set("cartId",this._cartId),this._iframe=document.createElement("iframe"),this._iframe.src=r.toString(),this._iframe.style.border="none",this._iframe.style.height="100%",this._iframe.style.overflow="hidden",this._iframe.style.width="100%"}return e.prototype.attach=function(){var e=document.getElementById(this._containerId);if(!e)throw new ua("Unable to proceed because the provided container ID is invalid.");e.appendChild(this._iframe)},e.prototype.detach=function(){this._iframe.parentElement&&this._iframe.parentElement.removeChild(this._iframe)},e}(),la=function(){function e(e){this._requestSender=e}return e.prototype.loadExtensions=function(e){var t=this;return function(){return u.Observable.create((function(n){n.next((0,c.createAction)(sa.LoadExtensionsRequested)),t._requestSender.loadExtensions(e).then((function(e){var t=e.body;n.next((0,c.createAction)(sa.LoadExtensionsSucceeded,t)),n.complete()})).catch((function(e){n.error((0,c.createErrorAction)(sa.LoadExtensionsFailed,e))}))}))}},e.prototype.renderExtension=function(e,t){return function(n){return u.Observable.create((function(r){var i=n.getState(),o=i.cart.getCartOrThrow().id,a=i.extensions.getExtensionByRegion(t);if(!a)throw new ca("Unable to proceed due to no extension configured for "+t+".");r.next((0,c.createAction)(sa.RenderExtensionRequested));try{new da(e,a,o).attach(),r.next((0,c.createAction)(sa.RenderExtensionSucceeded)),r.complete()}catch(e){r.error((0,c.createErrorAction)(sa.RenderExtensionFailed,e))}}))}},e}(),pa=function(){function e(e){this._requestSender=e}return e.prototype.loadExtensions=function(e){var t=void 0===e?{}:e,n=t.timeout,r=t.params;return this._requestSender.get("/api/storefront/checkout-extensions",{timeout:n,headers:(0,s.__assign)({Accept:w.JsonV1},C),params:r})},e}();const ha=function(e){function t(t){var n=this,r="Unable to submit payment for the order because the payload is invalid.";return t&&(r=r+" Make sure the following fields are provided correctly: "+t.join(", ")+"."),(n=e.call(this,r)||this).name="PaymentArgumentInvalidError",n}return(0,s.__extends)(t,e),t}(ye);function ma(e){return Boolean(e.instrumentId)}function _a(){var e,t=window.navigator;return e=t.language?t.language:t.userLanguage,{color_depth:window.screen.colorDepth||24,java_enabled:"function"==typeof t.javaEnabled&&t.javaEnabled(),language:e,screen_height:window.screen.height,screen_width:window.screen.width,time_zone_offset:(new Date).getTimezoneOffset().toString()}}const ya=function(e){function t(){var t=e.call(this,"The current order does not need to be finalized at this stage.")||this;return t.name="OrderFinalizationNotRequiredError",t.type="order_finalization_not_required",t}return(0,s.__extends)(t,e),t}(pe),fa=function(e){return"object"==typeof e&&null!==e&&"body"in e},ga=function(e){function t(t,n){var r=e.call(this,n||"Unable to proceed because the payment form contains invalid data.")||this;return r.details=t,r.name="PaymentInvalidFormError",r.type="payment_invalid_form",r}return(0,s.__extends)(t,e),t}(pe);var va,wa,Ca,Sa,Ia,ba;function Pa(e){return e&&"string"==typeof e.data.paymentMethod.encryptedSecurityCode||"string"==typeof e.data.paymentMethod.encryptedExpiryMonth}!function(e){e.ThreeDS2Fingerprint="threeDS2Fingerprint",e.ThreeDS2Challenge="threeDS2Challenge",e.Redirect="redirect",e.QRCode="qrCode",e.Voucher="voucher"}(va||(va={})),function(e){e.SecuredFields="securedfields"}(wa||(wa={})),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"}(Ca||(Ca={})),function(e){e.POST="POST"}(Sa||(Sa={})),function(e){e.ChallengeShopper="ChallengeShopper",e.Error="Error",e.IdentifyShopper="IdentifyShopper"}(Ia||(Ia={})),function(e){e.CardNumber="encryptedCardNumber",e.SecurityCode="encryptedSecurityCode",e.ExpiryDate="encryptedExpiryDate"}(ba||(ba={}));var Ea=function(){function e(e,t){this._paymentIntegrationService=e,this._scriptLoader=t}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d,l,p,h;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!(t=e.adyenv2))throw new ye('Unable to initialize payment because "options.adyenv2" argument is not provided.');return this._paymentInitializeOptions=t,n=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),r=n.initializationData||{},i=r.originKey,o=r.clientKey,a=r.environment,c=r.paymentMethodsResponse,u={key:"",value:""},i?(u.key="originKey",u.value=i):(u.key="clientKey",u.value=o||""),d=this,[4,this._scriptLoader.load((h={environment:a,locale:this._paymentIntegrationService.getState().getLocale()},h[u.key]=u.value,h.paymentMethodsResponse=c,h.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"}},h))];case 1:return d._adyenClient=s.sent(),l=this,[4,this._mountPaymentComponent(n)];case 2:return l._paymentComponent=s.sent(),n.method!==Ca.CreditCard&&n.method!==Ca.Bancontact?[3,4]:(p=this,[4,this._mountCardVerificationComponent()]);case 3:p._cardVerificationComponent=s.sent(),s.label=4;case 4:return[2,Promise.resolve()]}}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d,l,p,h,m,_,y;return(0,s.__generator)(this,(function(f){switch(f.label){case 0:return n=e.payment,r=(0,s.__rest)(e,["payment"]),i=n&&n.paymentData,o=i&&i.shouldSaveInstrument,a=i&&i.shouldSetAsDefaultInstrument,n?(this._validateCardData(),[4,this._paymentIntegrationService.submitOrder(r,t)]):[2,Promise.reject(new ha(["payment"]))];case 1:if(f.sent(),!(c=this._componentState))throw new Ee(Pe.PaymentNotInitialized);if(!i||!ma(i))return[3,6];if(u={},Pa(c)&&(d=c.data.paymentMethod,l=d.encryptedCardNumber,p=d.encryptedSecurityCode,h=d.encryptedExpiryMonth,m=d.encryptedExpiryYear,u={credit_card_number_confirmation:l,expiry_month:h,expiry_year:m,verification_value:p}),!Pa(c)&&-1===["ideal","sepadirectdebit","directEbanking","giropay"].indexOf(c.data.paymentMethod.type))return[3,6];f.label=2;case 2:return f.trys.push([2,4,,6]),[4,this._paymentIntegrationService.submitPayment((0,s.__assign)((0,s.__assign)({},n),{paymentData:{formattedPayload:{bigpay_token:(0,s.__assign)((0,s.__assign)({},u),{token:i.instrumentId}),origin:window.location.origin,browser_info:_a(),set_as_default_stored_instrument:a||null}}}))];case 3:return f.sent(),[2];case 4:return _=f.sent(),[4,this._processAdditionalAction(_,o,a)];case 5:return f.sent(),[2];case 6:return f.trys.push([6,8,,10]),[4,this._paymentIntegrationService.submitPayment({methodId:n.methodId,paymentData:{formattedPayload:{credit_card_token:{token:JSON.stringify((0,s.__assign)((0,s.__assign)({},c.data.paymentMethod),{origin:window.location.origin}))},browser_info:_a(),vault_payment_instrument:o||null,set_as_default_stored_instrument:a||null}}})];case 7:return f.sent(),[3,10];case 8:return y=f.sent(),[4,this._processAdditionalAction(y,o,a)];case 9:return f.sent(),[3,10];case 10:return[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.deinitialize=function(){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()},e.prototype._getAdyenClient=function(){if(!this._adyenClient)throw new Ee(Pe.PaymentNotInitialized);return this._adyenClient},e.prototype._getPaymentInitializeOptions=function(){if(!this._paymentInitializeOptions)throw new ye('"options.adyenv2" argument was not provided during initialization.');return this._paymentInitializeOptions},e.prototype._getThreeDS2ChallengeWidgetSize=function(){var e=this._getPaymentInitializeOptions(),t=e.additionalActionOptions,n=e.threeDS2Options;return t.widgetSize||(null==n?void 0:n.widgetSize)||"05"},e.prototype._handleAction=function(e){var t=this;return new Promise((function(n,r){var i=t._getPaymentInitializeOptions(),o=i.threeDS2ContainerId,a=i.additionalActionOptions,s=a.onBeforeLoad,c=a.containerId,u=a.onLoad,d=a.onComplete,l=JSON.parse(e.action),p=t._getAdyenClient().createFromAction(l,{onAdditionalDetails:function(e){var t={methodId:l.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};d&&d(),n(t)},size:t._getThreeDS2ChallengeWidgetSize(),onError:function(e){return r(e)}});s&&s(l.type===va.ThreeDS2Challenge||l.type===va.QRCode),p.mount("#"+(c||o)),u&&u((function(){r(new fe),p.unmount()}))}))},e.prototype._mapAdyenPlaceholderData=function(e,t){if(!e)return{};var n=e.firstName,r=e.lastName;return{holderName:t?n+" "+r:"",billingAddress:{street:e.address1,houseNumberOrName:e.address2,postalCode:e.postalCode,city:e.city,stateOrProvince:e.stateOrProvinceCode,country:e.countryCode}}},e.prototype._mountCardVerificationComponent=function(){var e,t=this,n=this._getPaymentInitializeOptions(),r=this._getAdyenClient();return new Promise((function(i,o){var a,c,u;if(n.cardVerificationContainerId){e=r.create(wa.SecuredFields,(0,s.__assign)((0,s.__assign)({},n.options),{styles:(0,s.__assign)((0,s.__assign)({},null===(a=n.options)||void 0===a?void 0:a.styles),{placeholder:(0,s.__assign)({color:"transparent",caretColor:"#000"},null===(u=null===(c=n.options)||void 0===c?void 0:c.styles)||void 0===u?void 0:u.placeholder)}),onChange:function(e){return t._updateComponentState(e)},onError:function(e){return n.validateCardFields(e)},onFieldValid:function(e){return n.validateCardFields(e)}}));try{e.mount("#"+n.cardVerificationContainerId)}catch(e){o(new Ee(Pe.PaymentNotInitialized))}}i(e)}))},e.prototype._mountPaymentComponent=function(e){var t,n=this,r=this._getPaymentInitializeOptions(),i=this._getAdyenClient();return new Promise((function(o,a){switch(e.method){case Ca.CreditCard:case Ca.ACH:case Ca.Bancontact:var c=n._paymentIntegrationService.getState().getBillingAddress(),u=e.initializationData.prefillCardHolderName;t=i.create(e.method,(0,s.__assign)((0,s.__assign)({},r.options),{onChange:function(e){return n._updateComponentState(e)},data:n._mapAdyenPlaceholderData(c,u)}));try{t.mount("#"+r.containerId)}catch(e){a(new Ee(Pe.PaymentNotInitialized))}break;case Ca.IDEAL:case Ca.SEPA:if(r.hasVaultedInstruments)n._updateComponentState({data:{paymentMethod:{type:e.method}}});else{t=i.create(e.method,(0,s.__assign)((0,s.__assign)({},r.options),{onChange:function(e){return n._updateComponentState(e)}}));try{t.mount("#"+r.containerId)}catch(e){a(new Ee(Pe.PaymentNotInitialized))}}break;case Ca.AliPay:case Ca.GiroPay:case Ca.Sofort:case Ca.Klarna:case Ca.KlarnaPayNow:case Ca.KlarnaAccount:case Ca.Vipps:case Ca.WeChatPayQR:n._updateComponentState({data:{paymentMethod:{type:e.method}}})}o(t)}))},e.prototype._processAdditionalAction=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(!fa(e)||!(0,Z.some)(e.body.errors,{code:"additional_action_required"}))throw e;return[4,this._handleAction(e.body.provider_data)];case 1:r=o.sent(),o.label=2;case 2:return o.trys.push([2,4,,5]),[4,this._paymentIntegrationService.submitPayment((0,s.__assign)((0,s.__assign)({},r),{paymentData:(0,s.__assign)((0,s.__assign)({},r.paymentData),{shouldSaveInstrument:t,shouldSetAsDefaultInstrument:n})}))];case 3:return o.sent(),[3,5];case 4:return i=o.sent(),[2,this._processAdditionalAction(i,t,n)];case 5:return[2]}}))}))},e.prototype._updateComponentState=function(e){this._componentState=e},e.prototype._validateCardData=function(){var e,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&&!t.state.issuer))throw new ga(this._mapCardErrors(t.state.errors))},e.prototype._mapCardErrors=function(e){void 0===e&&(e={});var t={};return Object.keys(e).forEach((function(n){t[n]=[{message:e[n],type:n}]})),t},e}();const Aa=Ea;var Oa=function(){function e(e,t,n){void 0===n&&(n=window),this._scriptLoader=e,this._stylesheetLoader=t,this._window=n}return e.prototype.load=function(e){var t,n;return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return[4,Promise.all([this._stylesheetLoader.loadStylesheet("https://checkoutshopper-"+(null!==(t=e.environment)&&void 0!==t?t:"")+".adyen.com/checkoutshopper/sdk/3.10.1/adyen.css"),this._scriptLoader.loadScript("https://checkoutshopper-"+(null!==(n=e.environment)&&void 0!==n?n:"")+".adyen.com/checkoutshopper/sdk/3.10.1/adyen.js")])];case 1:if(r.sent(),!this._window.AdyenCheckout)throw new Re;return[2,new this._window.AdyenCheckout(e)]}}))}))},e}();const ka=Oa,Ta=le((function(e){return new Aa(e,new ka((0,a.getScriptLoader)(),(0,a.getStylesheetLoader)()))}),[{gateway:"adyenv2"}]);function Ma(e){return!("object"!=typeof e||null===e||void 0!==e.shouldSaveInstrument&&"boolean"!=typeof e.shouldSaveInstrument||void 0!==e.shouldSetAsDefaultInstrument&&"boolean"!=typeof e.shouldSetAsDefaultInstrument)}var Da,Ra,za,Na,La,Fa;!function(e){e.ThreeDS2Fingerprint="threeDS2Fingerprint",e.ThreeDS2="threeDS2",e.Redirect="redirect",e.QRCode="qrCode",e.Voucher="voucher",e.Sdk="sdk"}(Da||(Da={})),function(e){e.SecuredFields="securedfields"}(Ra||(Ra={})),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"}(za||(za={})),function(e){e.POST="POST"}(Na||(Na={})),function(e){e.ChallengeShopper="ChallengeShopper",e.Error="Error",e.IdentifyShopper="IdentifyShopper"}(La||(La={})),function(e){e.CardNumber="encryptedCardNumber",e.SecurityCode="encryptedSecurityCode",e.ExpiryDate="encryptedExpiryDate"}(Fa||(Fa={}));var Ba=function(){function e(e,t){this._paymentIntegrationService=e,this._scriptLoader=t}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!(t=e.adyenv3))throw new ye('Unable to initialize payment because "options.adyenv3" argument is not provided.');return this._paymentInitializeOptions=t,n=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),r=n.initializationData||{},i=r.environment,o=r.clientKey,a=r.paymentMethodsResponse,c=this,[4,this._scriptLoader.load({paymentMethodsConfiguration:{klarna:{useKlarnaWidget:!0},klarna_account:{useKlarnaWidget:!0},klarna_paynow:{useKlarnaWidget:!0}},environment:i,locale:this._paymentIntegrationService.getState().getLocale(),clientKey:o,paymentMethodsResponse:a,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"}}})];case 1:return c._adyenClient=s.sent(),u=this,[4,this._mountPaymentComponent(n)];case 2:return u._paymentComponent=s.sent(),n.method!==za.CreditCard&&n.method!==za.Bancontact?[3,4]:(d=this,[4,this._mountCardVerificationComponent()]);case 3:d._cardVerificationComponent=s.sent(),s.label=4;case 4:return[2,Promise.resolve()]}}))}))},e.prototype.execute=function(e,t){var n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d,l,p,h,m,_,y,f,g;return(0,s.__generator)(this,(function(v){switch(v.label){case 0:if(r=e.payment,i=(0,s.__rest)(e,["payment"]),!r)throw new ha(["payment"]);return o=r.paymentData,a=Ma(o)?o:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1},c=a.shouldSaveInstrument,u=a.shouldSetAsDefaultInstrument,this._validateCardData(),d=this._componentState||{data:{paymentMethod:{type:r.methodId}}},"klarna"!==r.methodId&&"klarna_account"!==r.methodId&&"klarna_paynow"!==r.methodId||null===(n=this._paymentComponent)||void 0===n||n.submit(),[4,this._paymentIntegrationService.submitOrder(i,t)];case 1:if(v.sent(),!o||!ma(o))return[3,6];l={},("object"==typeof(w=d)&&w&&"string"==typeof w.data.paymentMethod.encryptedSecurityCode||"string"==typeof w.data.paymentMethod.encryptedExpiryMonth)&&(p=d.data.paymentMethod,h=p.encryptedCardNumber,m=p.encryptedSecurityCode,_=p.encryptedExpiryMonth,y=p.encryptedExpiryYear,l={credit_card_number_confirmation:h,expiry_month:_,expiry_year:y,verification_value:m}),v.label=2;case 2:return v.trys.push([2,4,,6]),[4,this._paymentIntegrationService.submitPayment((0,s.__assign)((0,s.__assign)({},r),{paymentData:{formattedPayload:{bigpay_token:(0,s.__assign)((0,s.__assign)({},l),{token:o.instrumentId}),origin:window.location.origin,browser_info:_a(),set_as_default_stored_instrument:u||null}}}))];case 3:return v.sent(),[2];case 4:return f=v.sent(),[4,this._processAdditionalAction(f,c,u)];case 5:return v.sent(),[2];case 6:return v.trys.push([6,8,,10]),[4,this._paymentIntegrationService.submitPayment({methodId:r.methodId,paymentData:{formattedPayload:{credit_card_token:{token:JSON.stringify((0,s.__assign)((0,s.__assign)({},d.data.paymentMethod),{type:r.methodId,origin:window.location.origin}))},browser_info:_a(),vault_payment_instrument:c||null,set_as_default_stored_instrument:u||null}}})];case 7:return v.sent(),[3,10];case 8:return g=v.sent(),[4,this._processAdditionalAction(g,c,u)];case 9:return v.sent(),[3,10];case 10:return[2]}var w}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.deinitialize=function(){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()},e.prototype._updateComponentState=function(e){this._componentState=e},e.prototype._getAdyenClient=function(){if(!this._adyenClient)throw new Ee(Pe.PaymentNotInitialized);return this._adyenClient},e.prototype._getPaymentInitializeOptions=function(){if(!this._paymentInitializeOptions)throw new ye('"options.adyenv3" argument was not provided during initialization.');return this._paymentInitializeOptions},e.prototype._handleAction=function(e){var t=this;return new Promise((function(n,r){var i=t._getPaymentInitializeOptions().additionalActionOptions,o=i.onBeforeLoad,a=i.containerId,s=i.onLoad,c=i.onComplete,u=i.widgetSize,d=JSON.parse(e.action),l=t._getAdyenClient().createFromAction(d,{onAdditionalDetails:function(e){var t={methodId:d.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};c&&c(),n(t)},challengeWindowSize:u||"05",onError:function(e){return r(e)}});o&&o(d.type===Da.ThreeDS2||d.type===Da.QRCode||d.type===Da.Sdk),l.mount("#"+a),s&&s((function(){r(new fe),l.unmount()}))}))},e.prototype._mapAdyenPlaceholderData=function(e,t){if(!e)return{};var n=e.firstName,r=e.lastName;return{holderName:t?n+" "+r:"",billingAddress:{street:e.address1,houseNumberOrName:e.address2,postalCode:e.postalCode,city:e.city,stateOrProvince:e.stateOrProvinceCode,country:e.countryCode}}},e.prototype._mountCardVerificationComponent=function(){var e,t=this,n=this._getPaymentInitializeOptions(),r=this._getAdyenClient();return new Promise((function(i,o){var a,c,u;if(n.cardVerificationContainerId){e=r.create(Ra.SecuredFields,(0,s.__assign)((0,s.__assign)({},n.options),{styles:(0,s.__assign)((0,s.__assign)({},null===(a=n.options)||void 0===a?void 0:a.styles),{placeholder:(0,s.__assign)({color:"transparent",caretColor:"#000"},null===(u=null===(c=n.options)||void 0===c?void 0:c.styles)||void 0===u?void 0:u.placeholder)}),onChange:function(e){return t._updateComponentState(e)},onError:function(e){return n.validateCardFields(e)},onFieldValid:function(e){return n.validateCardFields(e)}}));try{e.mount("#"+n.cardVerificationContainerId)}catch(e){o(new Ee(Pe.PaymentNotInitialized))}}i(e)}))},e.prototype._mountPaymentComponent=function(e){var t,n=this,r=this._getPaymentInitializeOptions(),i=this._getAdyenClient();return new Promise((function(o,a){var c=n._paymentIntegrationService.getState().getBillingAddress(),u=e.initializationData.prefillCardHolderName;t=i.create(e.method,(0,s.__assign)((0,s.__assign)((0,s.__assign)({},r.options),{showBrandsUnderCardNumber:!1,onChange:function(e){return n._updateComponentState(e)},onSubmit:function(e){return n._updateComponentState(e)}}),c?{data:n._mapAdyenPlaceholderData(c,u)}:{}));try{t.mount("#"+r.containerId)}catch(e){a(new Ee(Pe.PaymentNotInitialized))}o(t)}))},e.prototype._processAdditionalAction=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(!fa(e)||!(0,Z.some)(e.body.errors,{code:"additional_action_required"}))throw e;return[4,this._handleAction(e.body.provider_data)];case 1:r=o.sent(),o.label=2;case 2:return o.trys.push([2,4,,5]),[4,this._paymentIntegrationService.submitPayment((0,s.__assign)((0,s.__assign)({},r),{paymentData:(0,s.__assign)((0,s.__assign)({},r.paymentData),{shouldSaveInstrument:t,shouldSetAsDefaultInstrument:n})}))];case 3:return o.sent(),[3,5];case 4:return i=o.sent(),[2,this._processAdditionalAction(i,t,n)];case 5:return[2]}}))}))},e.prototype._validateCardData=function(){var e,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 ga(this._mapCardErrors(t.state.errors))},e.prototype._mapCardErrors=function(e){void 0===e&&(e={});var t={};return Object.keys(e).forEach((function(n){t[n]=[{message:e[n],type:n}]})),t},e}();const Ua=Ba;var xa=function(){function e(e,t,n){void 0===n&&(n=window),this._scriptLoader=e,this._stylesheetLoader=t,this._window=n}return e.prototype.load=function(e){var t,n;return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return[4,Promise.all([this._stylesheetLoader.loadStylesheet("https://checkoutshopper-"+(null!==(t=e.environment)&&void 0!==t?t:"")+".adyen.com/checkoutshopper/sdk/5.24.0/adyen.css"),this._scriptLoader.loadScript("https://checkoutshopper-"+(null!==(n=e.environment)&&void 0!==n?n:"")+".adyen.com/checkoutshopper/sdk/5.24.0/adyen.js")])];case 1:if(r.sent(),!this._window.AdyenCheckout)throw new Re;return[4,this._window.AdyenCheckout(e)];case 2:return[2,r.sent()]}}))}))},e}();const qa=xa,Va=le((function(e){return new Ua(e,new qa((0,a.getScriptLoader)(),(0,a.getStylesheetLoader)()))}),[{gateway:"adyenv3"}]);var Ga;!function(e){e.Shipping="Shipping",e.Subtotal="Subtotal"}(Ga||(Ga={}));var Ha=function(){function e(e,t,n){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=n,this._shippingLabel=Ga.Shipping,this._subTotalLabel=Ga.Subtotal}return e.prototype.initialize=function(e){var t,n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:if(!(null==e?void 0:e.methodId))throw new ye('Unable to submit payment because "options.methodId" argument is not provided.');return r=e.methodId,this._shippingLabel=(null===(t=e.applepay)||void 0===t?void 0:t.shippingLabel)||Ga.Shipping,this._subTotalLabel=(null===(n=e.applepay)||void 0===n?void 0:n.subtotalLabel)||Ga.Subtotal,[4,this._paymentIntegrationService.loadPaymentMethod(r)];case 1:return i.sent(),[2]}}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d,l,p=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(n=e.payment,r=this._paymentIntegrationService.getState(),i=r.getCheckoutOrThrow(),o=r.getCartOrThrow(),a=r.getStoreConfigOrThrow(),!n)throw new ha(["payment"]);return c=n.methodId,u=r.getPaymentMethodOrThrow(c),d=this._getBaseRequest(o,i,a,u),l=this._sessionFactory.create(d),[4,this._paymentIntegrationService.submitOrder({useStoreCredit:e.useStoreCredit},t)];case 1:return s.sent(),l.begin(),[2,new Promise((function(e,t){p._handleApplePayEvents(l,u,{resolve:e,reject:t})}))]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype._getBaseRequest=function(e,t,n,r){var i=n.storeProfile,o=i.storeCountryCode,a=i.storeName,s=e.currency.decimalPlaces,c=r.initializationData,u=c.merchantCapabilities,d=c.supportedNetworks,l=[{label:this._subTotalLabel,amount:""+t.subtotal.toFixed(s)}];return t.taxes.forEach((function(e){return l.push({label:e.name,amount:""+e.amount.toFixed()})})),l.push({label:this._shippingLabel,amount:""+t.shippingCostTotal.toFixed(s)}),{countryCode:o,currencyCode:e.currency.code,merchantCapabilities:u,supportedNetworks:d,lineItems:l,total:{label:a,amount:""+t.grandTotal.toFixed(e.currency.decimalPlaces),type:"final"}}},e.prototype._handleApplePayEvents=function(e,t,n){var r=this;e.onvalidatemerchant=function(n){return(0,s.__awaiter)(r,void 0,void 0,(function(){var r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this._onValidateMerchant(t,n)];case 1:return r=i.sent().body,e.completeMerchantValidation(r),[3,3];case 2:throw i.sent(),new Error("Merchant validation failed");case 3:return[2]}}))}))},e.oncancel=function(){return(0,s.__awaiter)(r,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){return[2,n.reject(new fe("Continue with applepay"))]}))}))},e.onpaymentauthorized=function(i){return r._onPaymentAuthorized(i,e,t,n)}},e.prototype._onValidateMerchant=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n;return(0,s.__generator)(this,(function(r){return n=["validationUrl="+t.validationURL,"merchantIdentifier="+e.initializationData.merchantId,"displayName="+e.initializationData.storeName,"domainName="+window.location.hostname].join("&"),[2,this._requestSender.post((i=e.initializationData.paymentsUrl,i+"/api/public/v1/payments/applepay/validate_merchant"),{credentials:!1,headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","X-XSRF-TOKEN":null},body:n})];var i}))}))},e.prototype._onPaymentAuthorized=function(e,t,n,r){return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:i=e.payment.token,o={methodId:n.id,paymentData:{formattedPayload:{apple_pay_token:{payment_data:i.paymentData,payment_method:i.paymentMethod,transaction_id:i.transactionIdentifier}}}},a.label=1;case 1:return a.trys.push([1,3,,4]),[4,this._paymentIntegrationService.submitPayment(o)];case 2:return a.sent(),t.completePayment(ApplePaySession.STATUS_SUCCESS),[2,r.resolve()];case 3:return a.sent(),t.completePayment(ApplePaySession.STATUS_FAILURE),[2,r.reject(new Ee(Pe.PaymentNotInitialized))];case 4:return[2]}}))}))},e}();const Ya=Ha,ja=le((function(e){var t=e.getState().getHost;return new Ya((0,o.createRequestSender)({host:t()}),e,new ve)}),[{id:"applepay"}]);function Wa(e,t){if(null==e)throw t?t():new Error("An unexpected error has occurred.");return e}var Ka;!function(e){e.CardCode="cardCode",e.CardCodeVerification="cardCodeVerification",e.CardExpiry="cardExpiry",e.CardName="cardName",e.CardNumber="cardNumber",e.CardNumberVerification="cardNumberVerification"}(Ka||(Ka={}));const Ja=Ka;function Za(e){return Ja.CardNumber in e}function Qa(e){return Ja.CardCodeVerification in e||Ja.CardNumberVerification in e}var Xa=function(){function e(e,t){this._paymentIntegrationService=e,this._blueSnapDirectHostedForm=t}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.methodId,n=e.gatewayId,r=e.creditCard,!n||!r)throw new ye;return[4,this._paymentIntegrationService.loadPaymentMethod(n,{params:{method:t}})];case 1:return i=s.sent(),o=i.getPaymentMethodOrThrow(t,n),a=o.config,c=a.testMode,u=a.is3dsEnabled,d=o.clientToken,this._paymentFieldsToken=d,this._shouldUseHostedFields=Za(r.form.fields)||Qa(r.form.fields)&&(!!r.form.fields.cardNumberVerification||!!r.form.fields.cardCodeVerification),this._shouldUseHostedFields?[4,this._blueSnapDirectHostedForm.initialize(c,r.form.fields)]:[3,4];case 2:return s.sent(),[4,this._blueSnapDirectHostedForm.attach(this._getPaymentFieldsToken(),r,u)];case 3:s.sent(),s.label=4;case 4:return[2]}}))}))},e.prototype.execute=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u;return(0,s.__generator)(this,(function(d){switch(d.label){case 0:if(!e.payment)throw new ha(["payment"]);return t=e.payment.paymentData,n=Ma(t)?t:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1},r=n.shouldSaveInstrument,i=n.shouldSetAsDefaultInstrument,o=this._getPaymentFieldsToken(),a=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.payment.methodId,e.payment.gatewayId).config.is3dsEnabled,this._shouldUseHostedFields?[4,this._blueSnapDirectHostedForm.validate().submit(a?this._getBlueSnapDirectThreeDSecureData():void 0,!(Ma(t)&&ma(t)))]:[3,2];case 1:return u=d.sent(),[3,3];case 2:u=void 0,d.label=3;case 3:return c=u,[4,this._paymentIntegrationService.submitOrder()];case 4:return d.sent(),Ma(t)&&ma(t)&&t.instrumentId?[4,this._paymentIntegrationService.submitPayment((0,s.__assign)((0,s.__assign)({},e.payment),{paymentData:(0,s.__assign)((0,s.__assign)({instrumentId:t.instrumentId},this._shouldUseHostedFields?{nonce:o}:{}),{shouldSetAsDefaultInstrument:!!i})}))]:[3,6];case 5:return d.sent(),[2];case 6:return[4,this._paymentIntegrationService.submitPayment((0,s.__assign)((0,s.__assign)({},e.payment),{paymentData:{formattedPayload:{credit_card_token:{token:JSON.stringify({pfToken:o,cardHolderName:c&&c.cardHolderName})},vault_payment_instrument:r,set_as_default_stored_instrument:i}}}))];case 7:return d.sent(),[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.deinitialize=function(){return this._shouldUseHostedFields&&this._blueSnapDirectHostedForm.detach(),Promise.resolve()},e.prototype._getBlueSnapDirectThreeDSecureData=function(){var e,t=this._paymentIntegrationService.getState(),n=t.getBillingAddress,r=t.getShippingAddress,i=t.getCustomer,o=t.getCheckoutOrThrow,a=t.getCartOrThrow,c=n(),u=r(),d=(null===(e=i())||void 0===e?void 0:e.email)||(null==c?void 0:c.email),l=(null==c?void 0:c.phone)||(null==u?void 0:u.phone);return(0,s.__assign)((0,s.__assign)((0,s.__assign)((0,s.__assign)({amount:o().outstandingBalance,currency:a().currency.code},d&&{email:d}),l&&{phone:l}),c&&{billingFirstName:c.firstName,billingLastName:c.lastName,billingCountry:c.countryCode,billingState:c.stateOrProvinceCode,billingCity:c.city,billingAddress:(c.address1+" "+c.address2).trim(),billingZip:c.postalCode}),u&&{shippingFirstName:u.firstName,shippingLastName:u.lastName,shippingCountry:u.countryCode,shippingState:u.stateOrProvinceCode,shippingCity:u.city,shippingAddress:(u.address1+" "+u.address2).trim(),shippingZip:u.postalCode})},e.prototype._getPaymentFieldsToken=function(){return Wa(this._paymentFieldsToken,(function(){return new me(he.MissingPaymentToken)}))},e}();const $a=Xa;var es,ts,ns,rs,is,os,as,ss;!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"}(es||(es={})),function(e){e.ON_BLUR="onBlur",e.ON_SUBMIT="onSubmit"}(ts||(ts={})),function(e){e.EMPTY="empty",e.INVALID="invalid",e.THREE_DS_NOT_ENABLED="3D Secure is not enabled"}(ns||(ns={})),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"}(rs||(rs={})),function(e){e.CardCode="cvv",e.CardExpiry="exp",e.CardName="noc",e.CardNumber="ccn"}(is||(is={}));var cs=((os={})[is.CardNumber]=Ja.CardNumber,os[is.CardExpiry]=Ja.CardExpiry,os[is.CardName]=Ja.CardName,os[is.CardCode]=Ja.CardCode,os),us={empty:(as={},as[Ja.CardNumber]={fieldType:"cardNumber",message:"Credit card number is required",type:"required"},as[Ja.CardNumberVerification]={fieldType:"cardNumber",message:"Credit card number is required",type:"required"},as[Ja.CardExpiry]={fieldType:"cardExpiry",message:"Expiration date is required",type:"required"},as[Ja.CardCode]={fieldType:"cardCode",message:"CVV is required",type:"required"},as[Ja.CardCodeVerification]={fieldType:"cardCode",message:"CVV is required",type:"required"},as[Ja.CardName]={fieldType:"cardName",message:"Full name is required",type:"required"},as),invalid:(ss={},ss[Ja.CardNumber]={fieldType:"cardNumber",message:"Credit card number must be valid",type:"invalid_card_number"},ss[Ja.CardNumberVerification]={fieldType:"cardNumber",message:"Credit card number must be valid",type:"invalid_card_number"},ss[Ja.CardExpiry]={fieldType:"cardExpiry",message:"Expiration date must be a valid future date in MM / YY format",type:"invalid_card_expiry"},ss[Ja.CardCode]={fieldType:"cardCode",message:"CVV must be valid",type:"invalid_card_code"},ss[Ja.CardCodeVerification]={fieldType:"cardCode",message:"CVV must be valid",type:"invalid_card_code"},ss[Ja.CardName]={fieldType:"cardName",message:"Full name is required",type:"required"},ss)},ds=function(){function e(e,t,n){this._scriptLoader=e,this._nameOnCardInput=t,this._hostedInputValidator=n}return e.prototype.initialize=function(e,t){return void 0===e&&(e=!1),(0,s.__awaiter)(this,void 0,void 0,(function(){var n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return n=this,[4,this._scriptLoader.load(e)];case 1:return n._blueSnapSdk=r.sent(),t?Za(t)?(this._hostedInputValidator.initialize(),[2]):Qa(t)&&t.cardNumberVerification&&t.cardCodeVerification?(this._hostedInputValidator.initializeValidationFields(),[2]):(Qa(t)&&t.cardCodeVerification&&this._hostedInputValidator.initializeValidationCVVFields(),[2]):[2]}}))}))},e.prototype.attach=function(e,t,n){void 0===n&&(n=!1);var r=t.form,i=r.fields,o=(0,s.__rest)(r,["fields"]);return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,r=this;return(0,s.__generator)(this,(function(a){if(t=this._getBlueSnapSdk(),!Za(i)&&!Qa(i))throw new ye("Field options must be of type HostedCardFieldOptionsMap");return this._onValidate=o.onValidate,Za(i)&&this._setCustomBlueSnapAttributes(i),Qa(i)&&this._setCustomStoredCardsBlueSnapAttributes(i),[2,new Promise((function(a){var s=r._getHostedPaymentFieldsOptions(e,i,o,a,n);t.hostedPaymentFieldsCreate(s),Za(i)&&r._nameOnCardInput.attach(s,i.cardName.accessibilityLabel,i.cardName.placeholder)}))]}))}))},e.prototype.validate=function(){var e,t=this._hostedInputValidator.validate();if(null===(e=this._onValidate)||void 0===e||e.call(this,t),!t.isValid){var n=Object.entries(t.errors).reduce((function(e,t){var n,r=t[0],i=t[1];return(0,s.__assign)((0,s.__assign)({},e),((n={})[r]=i.map((function(e){return{message:e.message,type:e.type}})),n))}),{});throw new ga(n)}return this},e.prototype.submit=function(e,t){var n=this;return void 0===t&&(t=!1),new Promise((function(r,i){return n._getBlueSnapSdk().hostedPaymentFieldsSubmitData((function(e){return n._isBlueSnapDirectCallbackError(e)?i(new be(e.statusCode===rs.THREE_DS_AUTH_FAILED?e.error[0].errorDescription:"Submission failed with status: "+e.statusCode+" and errors: "+JSON.stringify(e.error))):r((0,s.__assign)((0,s.__assign)({},e.cardData),t?{cardHolderName:n._nameOnCardInput.getValue()}:{}))}),e)}))},e.prototype.detach=function(){this._nameOnCardInput.detach()},e.prototype._isBlueSnapDirectCallbackError=function(e){return"error"in e},e.prototype._getHostedPaymentFieldsOptions=function(e,t,n,r,i){var o,a=this,c=n.onFocus,u=n.onBlur,d=n.onValidate,l=n.onCardTypeChange,p=n.onEnter,h=n.styles;return(0,s.__assign)((0,s.__assign)((0,s.__assign)({token:e,onFieldEventHandler:{setupComplete:function(){return r()},onFocus:this._usetUiEventCallback(c),onBlur:this._usetUiEventCallback(u),onError:this._handleError(d),onType:function(e,t){return null==l?void 0:l({cardType:es[t]})},onEnter:this._usetUiEventCallback(p),onValid:function(e){return null==d?void 0:d(a._hostedInputValidator.validate({tagId:e}))}}},Za(t)&&{ccnPlaceHolder:t.cardNumber.placeholder||"",cvvPlaceHolder:(null===(o=t.cardCode)||void 0===o?void 0:o.placeholder)||"",expPlaceHolder:t.cardExpiry.placeholder||"MM / YY"}),h&&{style:this._mapStyles(h)}),{"3DS":i})},e.prototype._mapStyles=function(e){var t=e.default,n=e.error,r=e.focus;return Object.entries((0,s.__assign)((0,s.__assign)((0,s.__assign)({},t&&{input:t}),n&&{".invalid":n}),r&&{":focus":r})).reduce((function(e,t){var n,r=t[0],i=t[1];return(0,s.__assign)((0,s.__assign)({},e),((n={})[r]=Object.entries(i).reduce((function(e,t){var n,r=t[0],i=t[1];return(0,s.__assign)((0,s.__assign)({},e),((n={})[(0,Z.kebabCase)(r)]=i,n))}),{}),n))}),{})},e.prototype._handleError=function(e){var t=this;return function(n,r,i,o){if(r===rs.INVALID_OR_EMPTY&&n&&function(e){return void 0!==e&&[ns.EMPTY,ns.INVALID].includes(e)}(i))return null==e?void 0:e(t._hostedInputValidator.validate({tagId:n,errorDescription:i}));throw new be("An unexpected error has occurred: "+JSON.stringify({tagId:n,errorCode:r,errorDescription:i,eventOrigin:o}))}},e.prototype._usetUiEventCallback=function(e){return function(t){e&&e({fieldType:cs[t]})}},e.prototype._getBlueSnapSdk=function(){return Wa(this._blueSnapSdk,(function(){return new Ee(Pe.PaymentNotInitialized)}))},e.prototype._setCustomBlueSnapAttributes=function(e){var t=e.cardNumber,n=e.cardExpiry,r=e.cardCode,i=e.cardName,o=document.getElementById(t.containerId),a=document.getElementById(n.containerId),s=r&&document.getElementById(r.containerId),c=document.getElementById(i.containerId);if(!(o&&a&&s&&c))throw new ye("Unable to create hosted payment fields to invalid HTML container elements.");o.dataset.bluesnap=is.CardNumber,a.dataset.bluesnap=is.CardExpiry,s.dataset.bluesnap=is.CardCode,c.dataset.bluesnap=is.CardName},e.prototype._setCustomStoredCardsBlueSnapAttributes=function(e){var t=e.cardNumberVerification,n=e.cardCodeVerification,r=t&&document.getElementById(t.containerId),i=n&&document.getElementById(n.containerId);(r||i)&&(r&&(r.dataset.bluesnap=is.CardNumber),i&&(i.dataset.bluesnap=is.CardCode))},e}();const ls=ds,ps=function(){function e(){this._errors={}}return e.prototype.initialize=function(){this._errors={cardNumber:[us.empty.cardNumber],cardExpiry:[us.empty.cardExpiry],cardCode:[us.empty.cardCode],cardName:[us.empty.cardName]}},e.prototype.initializeValidationFields=function(){this._errors={cardNumber:[us.empty.cardNumber],cardCode:[us.empty.cardCode]}},e.prototype.initializeValidationCVVFields=function(){this._errors={cardCode:[us.empty.cardCode]}},e.prototype.validate=function(e){return e&&this._updateErrors(e.tagId,e.errorDescription),{isValid:Object.values(this._errors).every((function(e){return 0===e.length})),errors:this._errors}},e.prototype._updateErrors=function(e,t){var n=cs[e];this._errors[n]=t?[us[t][n]]:[]},e}();var hs=function(){function e(){}return e.prototype.attach=function(e,t,n){var r,i=e.style,o=e.onFieldEventHandler,a=void 0===o?{}:o,s=a.onFocus,c=a.onBlur,u=a.onValid,d=a.onError,l=a.onEnter;this._style=i,this._create(),this._getInput().addEventListener("focus",this._handleFocus(s)),this._getInput().addEventListener("blur",this._handleBlur(c,u,d)),this._getInput().addEventListener("enter",this._handleEnter(l)),t&&this._getInput().setAttribute("aria-label",t),n&&(this._getInput().placeholder=n),null===(r=document.querySelector('[data-bluesnap="noc"]'))||void 0===r||r.appendChild(this._getInput())},e.prototype.getValue=function(){return this._getInput().value},e.prototype.detach=function(){this._input&&(this._input.remove(),this._input=void 0)},e.prototype._handleFocus=function(e){var t=this;return function(){var n;t._applyStyles(null===(n=t._style)||void 0===n?void 0:n[":focus"]),null==e||e(is.CardName)}},e.prototype._handleBlur=function(e,t,n){var r=this;return function(i){var o,a,s=i.target;null==e||e(is.CardName),s instanceof HTMLInputElement&&(/\w{1,200}/.test(s.value)?(r._applyStyles(null===(o=r._style)||void 0===o?void 0:o.input),null==t||t(is.CardName)):(r._applyStyles(null===(a=r._style)||void 0===a?void 0:a[".invalid"]),null==n||n(is.CardName,rs.INVALID_OR_EMPTY,ns.EMPTY,ts.ON_BLUR)))}},e.prototype._handleEnter=function(e){return function(){return null==e?void 0:e(is.CardName)}},e.prototype._applyStyles=function(e){var t=this;void 0===e&&(e={});var n={color:e.color,fontFamily:e["font-family"],fontSize:e["font-size"],fontWeight:e["font-weight"]},r=Object.keys(n);r.every((function(e){return["color","fontFamily","fontSize","fontWeight"].includes(e)}))&&r.forEach((function(e){n[e]&&(t._getInput().style[e]=n[e]||"")}))},e.prototype._configureInput=function(){this._getInput().autocomplete="cc-name",this._getInput().id=is.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"},e.prototype._getInput=function(){return Wa(this._input,(function(){return new Ee(Pe.PaymentNotInitialized)}))},e.prototype._create=function(){var e;this._input=document.createElement("input"),this._configureInput(),this._applyStyles(null===(e=this._style)||void 0===e?void 0:e.input)},e}();const ms=hs;var _s;!function(e){e.PRODUCTION="https://pay.bluesnap.com/web-sdk/5/bluesnap.js",e.SANDBOX="https://sandpay.bluesnap.com/web-sdk/5/bluesnap.js"}(_s||(_s={}));var ys=function(){function e(e,t){void 0===t&&(t=window),this._scriptLoader=e,this._window=t}return e.prototype.load=function(e){return void 0===e&&(e=!1),(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this._scriptLoader.loadScript(e?_s.SANDBOX:_s.PRODUCTION)];case 1:if(t.sent(),!this._window.bluesnap)throw new Re;return[2,this._window.bluesnap]}}))}))},e}();const fs=ys,gs=le((function(e){return new $a(e,new ls(new fs((0,a.getScriptLoader)()),new ms,new ps))}),[{id:"credit_card",gateway:"bluesnapdirect"}]);var vs=function(){function e(e){this._paymentIntegrationService=e}return e.prototype.initialize=function(){return Promise.resolve()},e.prototype.execute=function(e){var t=e.payment;return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){switch(e.label){case 0:return function(e){if(!function(e){return void 0!==e&&"accountNumber"in e&&"accountType"in e&&"shopperPermission"in e&&"routingNumber"in e}(e))throw new ha}(null==t?void 0:t.paymentData),[4,this._paymentIntegrationService.submitOrder()];case 1:return e.sent(),[4,this._paymentIntegrationService.submitPayment((0,s.__assign)((0,s.__assign)({},t),{paymentData:{formattedPayload:{ecp:{account_number:t.paymentData.accountNumber,account_type:t.paymentData.accountType,shopper_permission:t.paymentData.shopperPermission,routing_number:t.paymentData.routingNumber}}}}))];case 2:return e.sent(),[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.deinitialize=function(){return Promise.resolve()},e}();const ws=vs,Cs=le((function(e){return new ws(e)}),[{id:"ecp",gateway:"bluesnapdirect"}]);var Ss=function(){function e(e){this._paymentIntegrationService=e}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){if(!(t=e.bluesnapdirect))throw new ye('Unable to initialize payment because "options.bluesnapdirect" argument is not provided.');return this._initializeOptions=t,[2,Promise.resolve()]}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a;return(0,s.__generator)(this,(function(c){switch(c.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!n)throw new ha(["payment"]);if(!this._initializeOptions)throw new Ee(Pe.PaymentNotInitialized);return[4,this._paymentIntegrationService.submitOrder(r,t)];case 1:c.sent(),c.label=2;case 2:return c.trys.push([2,4,,7]),[4,this._paymentIntegrationService.submitPayment({methodId:n.methodId})];case 3:return c.sent(),[3,7];case 4:return i=c.sent(),this._isBlueSnapDirectRedirectResponse(i)&&function(e){if("object"!=typeof e||null===e)return!1;var t=e;return!!t.merchantid&&"string"==typeof t.merchantid}(o=JSON.parse(i.body.provider_data))?(a=new URLSearchParams(o).toString(),[4,this._mountAPMFrame(i.body.additional_action_required.data.redirect_url+"&"+a)]):[3,6];case 5:c.sent(),c.label=6;case 6:return[2,Promise.reject(i)];case 7:return[2]}}))}))},e.prototype.finalize=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){return[2,Promise.reject(new ya)]}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype._mountAPMFrame=function(e){var t=this;return new Promise((function(n,r){if(!t._initializeOptions)throw new Ee(Pe.PaymentNotInitialized);var i=t._initializeOptions,o=i.onLoad,a=i.style,s=function(e,t,n){var r=document.createElement("iframe");if(r.setAttribute("sandbox","allow-top-navigation allow-scripts allow-forms allow-same-origin"),r.src=t,r.name="bluesnap_direct_hosted_payment_page",n){var i=n.border,o=n.height,a=n.width;r.style.border=i||"",r.style.height=o||"",r.style.width=a||""}return r}(0,e,a);o(s,(function(){r(new fe)}))}))},e.prototype._isBlueSnapDirectRedirectResponse=function(e){var t;if("object"!=typeof e||null===e)return!1;var n=e;if(!n.body)return!1;var r=n.body;return"additional_action_required"===r.status&&!!(null===(t=r.additional_action_required)||void 0===t?void 0:t.data.redirect_url)&&"string"==typeof r.provider_data},e}();const Is=Ss,bs=le((function(e){return new Is(e)}),[{gateway:"bluesnapdirect"}]),Ps=require("local-storage-fallback");var Es=n.n(Ps);const As=function(){function e(e){this.storage=e}return e.prototype.saveExtraItemsData=function(e,t){var n=(0,s.__spreadArrays)(t.physicalItems,t.digitalItems).reduce((function(e,t){return e[t.productId]={brand:t.brand?t.brand:"",category:t.categoryNames?t.categoryNames.join(", "):""},e}),{});try{return this.storage.setItem(this.getStorageKey(e),JSON.stringify(n)),n}catch(e){return{}}},e.prototype.readExtraItemsData=function(e){try{var t=this.storage.getItem(this.getStorageKey(e));if(!t)return null;var n=JSON.parse(t);return function(e){if(!(0,Z.isObject)(e))return!1;var t=Object.values(e).some((function(e){return!(0,Z.isObject)(e)||!("brand"in e)||!("category"in e)}));return Boolean(!t)}(n)?n:null}catch(e){return null}},e.prototype.clearExtraItemData=function(e){try{this.storage.removeItem(this.getStorageKey(e))}catch(e){}},e.prototype.getStorageKey=function(e){return e?"ORDER_ITEMS_"+e:""},e}();function Os(e){return Boolean(e.hasOwnProperty("analytics"))}function ks(e){return"object"==typeof e&&null!==e&&"shouldCreateAccount"in e}const Ts=function(e){function t(n){var r=e.call(this)||this;return r.errorCode=n,r.name="BoltPaymentsFieldError",r.type="bolt_payments_field_error",r.body={errors:[t.getError(n)]},r}return(0,s.__extends)(t,e),t.getError=function(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"}}},t}(pe);var Ms=function(){function e(e,t,n){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.analyticsExtraItemsManager=n,this.useBoltClient=!1,this.useBoltEmbedded=!1}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d,l,p,h,m,_,y,f,g,v;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.bolt,n=e.methodId,i=(r=t||{}).containerId,o=r.onPaymentSelect,a=r.useBigCommerceCheckout,!n)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');return a?[3,2]:(c=this,[4,this.boltScriptLoader.loadBoltClient()]);case 1:return c.boltClient=s.sent(),[2];case 2:if(u=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),d=u.initializationData,l=u.config,h=(p=d||{}).publishableKey,m=p.developerConfig,_=p.embeddedOneClickEnabled,y=l.testMode,!h)throw new me(he.MissingPaymentMethod);return f=this,[4,this.boltScriptLoader.loadBoltClient(h,y,m)];case 3:if(f.boltClient=s.sent(),this.useBoltClient=!_,this.useBoltEmbedded=!!_,!this.useBoltEmbedded)return[3,6];if(!i)throw new ye('Unable to initialize payment because "options.bolt.containerId" argument is not provided.');if(!o)throw new ye('Unable to initialize payment because "options.bolt.onPaymentSelect" argument is not provided.');return g=this,[4,this.boltScriptLoader.loadBoltEmbedded(h,y,m)];case 4:return g.boltEmbedded=s.sent(),this.mountBoltEmbeddedField(i),v=o,[4,this.hasBoltAccount()];case 5:v.apply(void 0,[s.sent()]),s.label=6;case 6:return[2]}}))}))},e.prototype.deinitialize=function(){var e;return null===(e=this.embeddedField)||void 0===e||e.unmount(),this.boltClient=void 0,this.boltEmbedded=void 0,Promise.resolve()},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c;return(0,s.__generator)(this,(function(u){switch(u.label){case 0:if(this.setExtraItemsForAnalytics(),n=e.payment,r=(0,s.__rest)(e,["payment"]),o=(i=n||{}).methodId,a=i.paymentData,!e.payment)throw new ha(["payment"]);if(!o)throw new me(he.MissingPaymentMethod);if(!a||!function(e){return Boolean((0,Z.isObject)(e)&&("shouldSaveInstrument"in e||"nonce"in e||ks(e)))}(a))throw new me(he.MissingPayment);return[4,this.paymentIntegrationService.submitOrder(r,t)];case 1:return u.sent(),this.useBoltClient?[4,this.getBoltClientPaymentPayload(o,a,t)]:[3,3];case 2:return c=u.sent(),[3,7];case 3:return this.useBoltEmbedded?[4,this.getBoltEmbeddedPaymentPayload(o,a)]:[3,5];case 4:return c=u.sent(),[3,7];case 5:return[4,this.getBoltFullCheckoutPaymentPayload(o,a)];case 6:c=u.sent(),u.label=7;case 7:return[4,this.paymentIntegrationService.submitPayment(c)];case 8:return u.sent(),[2]}}))}))},e.prototype.getBoltClientPaymentPayload=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return[4,this.paymentIntegrationService.loadPaymentMethod(e,n)];case 1:return s.sent(),r=this.paymentIntegrationService.getState(),i=r.getPaymentMethodOrThrow(e),o=i.clientToken,a=r.getCheckoutOrThrow().isStoreCreditApplied,c=t.shouldSaveInstrument,u=this.getBoltClientOrThrow(),[4,this.paymentIntegrationService.applyStoreCredit(a)];case 2:if(s.sent(),!o)throw new me(he.MissingPaymentMethod);return[4,new Promise((function(e,t){var n={success:function(n,r){n.reference?e(n):t(new be("Unable to proceed because transaction reference is unavailable. Please try again later.")),r()},close:function(){t(new fe)}};u.configure({orderToken:o},{},n).open()}))];case 3:return d=s.sent(),[2,{methodId:e,paymentData:{nonce:d.reference,shouldSaveInstrument:c}}]}}))}))},e.prototype.getBoltEmbeddedPaymentPayload=function(e,t){var n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(!ks(t))throw new me(he.MissingPayment);return i=this.validateTokenizeResultOrThrow,[4,null===(n=this.embeddedField)||void 0===n?void 0:n.tokenize()];case 1:return r=i.apply(this,[o.sent()]),[2,{methodId:e,paymentData:{formattedPayload:{credit_card_token:{token:r.token,last_four_digits:r.last4,iin:r.bin,expiration_month:+r.expiration.split("-")[1],expiration_year:+r.expiration.split("-")[0]},provider_data:{create_account:!!t.shouldCreateAccount,embedded_checkout:!0}}}}]}}))}))},e.prototype.getBoltFullCheckoutPaymentPayload=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return[4,this.setBoltOrderId()];case 1:return r.sent(),[4,this.getBoltClientOrThrow().getTransactionReference()];case 2:if(!(n=r.sent()))throw new Te;return[2,{methodId:e,paymentData:(0,s.__assign)((0,s.__assign)({},t),{nonce:n})}]}}))}))},e.prototype.getBoltClientOrThrow=function(){if(!this.boltClient)throw new Ee(Pe.PaymentNotInitialized);return this.boltClient},e.prototype.getBoltEmbeddedOrThrow=function(){if(!this.boltEmbedded)throw new Ee(Pe.PaymentNotInitialized);return this.boltEmbedded},e.prototype.hasBoltAccount=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){var e,t,n,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:e=this.paymentIntegrationService.getState(),t=e.getCustomer(),n=e.getBillingAddress(),r=(null==t?void 0:t.email)||(null==n?void 0:n.email)||"",i=this.getBoltClientOrThrow(),o.label=1;case 1:return o.trys.push([1,3,,4]),[4,i.hasBoltAccount(r)];case 2:return[2,o.sent()];case 3:throw o.sent(),new Te;case 4:return[2]}}))}))},e.prototype.setBoltOrderId=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){var e,t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:e=this.paymentIntegrationService.getState().getOrderOrThrow(),t=this.getBoltClientOrThrow(),n.label=1;case 1:return n.trys.push([1,3,,4]),[4,t.setOrderId(e.orderId)];case 2:return n.sent(),[3,4];case 3:throw n.sent(),new Te;case 4:return[2]}}))}))},e.prototype.mountBoltEmbeddedField=function(e){var t=this.getBoltEmbeddedOrThrow().create("payment_field",{styles:{backgroundColor:"#fff"},renderSeparateFields:!0});t.mount("#"+e),this.embeddedField=t},e.prototype.validateTokenizeResultOrThrow=function(e){if(!e)throw new Te;if(e instanceof Error)throw new Ts(e.message);var t=e.token,n=e.last4,r=e.bin,i=e.expiration,o=+n,a=+r,s=+(""+i).split("-")[1],c=+(""+i).split("-")[0];if(!t||Number.isNaN(o)||Number.isNaN(a)||Number.isNaN(s)||Number.isNaN(c))throw new ha;return e},e.prototype.setExtraItemsForAnalytics=function(){var e=this.paymentIntegrationService.getState(),t=e.getStoreConfigOrThrow(),n=e.getCartOrThrow();if(t.checkoutSettings.isAnalyticsEnabled&&Os(window)){var r=n.id,i=n.lineItems;this.analyticsExtraItemsManager.saveExtraItemsData(r,i)}},e}();const Ds=Ms,Rs=le((function(e){return new Ds(e,new Be((0,a.getScriptLoader)()),new As(Es()))}),[{id:"bolt"}]);function zs(e){return!!e&&"accountNumber"in e&&"routingNumber"in e&&"ownershipType"in e&&"accountType"in e}var Ns=function(){function e(e,t){this.paymentIntegrationService=e,this.braintreeIntegrationService=t}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:if(t=(e.braintreeach||{}).getMandateText,!e.methodId)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');return this.getMandateText=t,[4,this.paymentIntegrationService.loadPaymentMethod(e.methodId)];case 1:if(a.sent(),n=this.paymentIntegrationService.getState(),!(r=n.getPaymentMethodOrThrow(e.methodId)).clientToken)throw new me(he.MissingPaymentMethod);a.label=2;case 2:return a.trys.push([2,4,,5]),this.braintreeIntegrationService.initialize(r.clientToken),i=this,[4,this.braintreeIntegrationService.getUsBankAccount()];case 3:return i.usBankAccount=a.sent(),[3,5];case 4:return o=a.sent(),this.handleError(o),[3,5];case 5:return[2]}}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u;return(0,s.__generator)(this,(function(d){switch(d.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!n)throw new ha(["payment"]);return(i=ma(n.paymentData||{}))?[4,this.tokenizePaymentForVaultedInstrument(n)]:[3,2];case 1:return a=d.sent(),[3,4];case 2:return[4,this.tokenizePayment(n)];case 3:a=d.sent(),d.label=4;case 4:return o=a,i?[4,this.preparePaymentDataForVaultedInstrument(o,n)]:[3,6];case 5:return u=d.sent(),[3,8];case 6:return[4,this.preparePaymentData(o,n)];case 7:u=d.sent(),d.label=8;case 8:return c=u,[4,this.paymentIntegrationService.submitOrder(r,t)];case 9:return d.sent(),[4,this.paymentIntegrationService.submitPayment(c)];case 10:return d.sent(),[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.deinitialize=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){return this.getMandateText=void 0,[2,Promise.resolve()]}))}))},e.prototype.preparePaymentData=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(n=t.paymentData,!zs(r=void 0===n?{}:n))throw new ha(["payment.paymentData"]);return[4,this.braintreeIntegrationService.getSessionId()];case 1:return i=s.sent(),o=r.shouldSaveInstrument,a=r.shouldSetAsDefaultInstrument,c=r.routingNumber,u=r.accountNumber,d={formattedPayload:{vault_payment_instrument:o||null,set_as_default_stored_instrument:a||null,device_info:i||null,tokenized_bank_account:{issuer:c,masked_account_number:u.substr(-4),token:e}}},[2,{methodId:t.methodId,paymentData:d}]}}))}))},e.prototype.preparePaymentDataForVaultedInstrument=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(n=t.paymentData,!ma(r=void 0===n?{}:n)||!Ma(r))throw new ha(["payment.paymentData"]);return[4,this.braintreeIntegrationService.getSessionId()];case 1:return i=o.sent(),[2,{methodId:t.methodId,paymentData:(0,s.__assign)({deviceSessionId:i,instrumentId:r.instrumentId,shouldSetAsDefaultInstrument:r.shouldSetAsDefaultInstrument},e&&{nonce:e})}]}}))}))},e.prototype.tokenizePayment=function(e){var t=e.paymentData;return(0,s.__awaiter)(this,void 0,void 0,(function(){var e,n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:if(e=this.getUsBankAccountOrThrow(),!zs(t))throw new ha(["payment.paymentData"]);if(!(n=ma(t)?"The data are used for stored instrument verification":"function"==typeof this.getMandateText&&this.getMandateText()))throw new ye("Unable to proceed because getMandateText is not provided or returned undefined value.");i.label=1;case 1:return i.trys.push([1,3,,4]),[4,e.tokenize({bankDetails:this.getBankDetails(t),mandateText:n})];case 2:return[2,i.sent().nonce];case 3:return r=i.sent(),this.handleError(r),[3,4];case 4:return[2]}}))}))},e.prototype.tokenizePaymentForVaultedInstrument=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r;return(0,s.__generator)(this,(function(i){if(t=e.methodId,n=e.paymentData,r=void 0===n?{}:n,!this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t).config.isVaultingEnabled)throw new ye("Vaulting is disabled but a vaulted instrument was being used for this transaction");return[2,zs(r)?this.tokenizePayment(e):null]}))}))},e.prototype.getBankDetails=function(e){var t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),n=e.ownershipType.toLowerCase(),r=e.accountType.toLowerCase();return(0,s.__assign)((0,s.__assign)({accountNumber:e.accountNumber,routingNumber:e.routingNumber,ownershipType:n},"personal"===n?{firstName:e.firstName,lastName:e.lastName}:{businessName:e.businessName}),{accountType:r,billingAddress:{streetAddress:t.address1,extendedAddress:t.address2,locality:t.city,region:t.stateOrProvinceCode,postalCode:t.postalCode}})},e.prototype.getUsBankAccountOrThrow=function(){if(!this.usBankAccount)throw new Ee(Pe.PaymentNotInitialized);return this.usBankAccount},e.prototype.handleError=function(e){if(!Ve(e))throw e;throw new be(e.message)},e}();const Ls=Ns,Fs=le((function(e){var t=window,n=new Ze(new $e((0,a.getScriptLoader)(),t),t);return new Ls(e,n)}),[{id:"braintreeach"}]);var Bs=function(){function e(e,t,n){this.paymentIntegrationService=e,this.braintreeIntegrationService=t,this.loadingIndicator=n}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.gatewayId,n=e.methodId,r=e.braintreelocalmethods,!n)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new ye('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!r)throw new ye('Unable to initialize payment because "options.braintreelocalmethods" argument is not provided.');return this.braintreeLocalMethods=r,this.loadingIndicatorContainer=r.container.split("#")[1],[4,this.paymentIntegrationService.loadPaymentMethod(t)];case 1:if(s.sent(),i=this.paymentIntegrationService.getState(),o=i.getPaymentMethodOrThrow(t),a=o.config.merchantId,!o.clientToken)throw new me(he.MissingPaymentMethod);s.label=2;case 2:return s.trys.push([2,4,,5]),this.braintreeIntegrationService.initialize(o.clientToken),[4,this.braintreeIntegrationService.loadBraintreeLocalMethods(this.getLocalPaymentInstance.bind(this),a||"")];case 3:return s.sent(),[3,5];case 4:return c=s.sent(),this.handleError(c),[3,5];case 5:return[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.deinitialize=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){return this.orderId=void 0,this.toggleLoadingIndicator(!1),[2,Promise.resolve()]}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d,l,p,h,m,_,y,f=this;return(0,s.__generator)(this,(function(g){switch(g.label){case 0:return n=e.payment,r=(0,s.__rest)(e,["payment"]),i=this.paymentIntegrationService.getState(),o=i.getCartOrThrow(),[4,this.braintreeIntegrationService.getSessionId()];case 1:if(a=g.sent(),c=i.getBillingAddressOrThrow(),u=c.firstName,d=c.lastName,l=c.countryCode,p=o.baseAmount,h=o.currency,m=o.email,_=o.lineItems,y=_.physicalItems.length>0,!n)throw new ha(["payment"]);if(this.toggleLoadingIndicator(!0),!this.localPaymentInstance)throw new Te;return[2,new Promise((function(e,i){var c;null===(c=f.localPaymentInstance)||void 0===c||c.startPayment({paymentType:n.methodId,amount:p,fallback:{url:"url-placeholder",buttonText:"button placeholder"},currencyCode:h.code,shippingAddressRequired:y,email:m,givenName:u,surname:d,address:{countryCode:l},onPaymentStart:function(e,t){f.orderId=e.paymentId,t()}},(function(c,u){return(0,s.__awaiter)(f,void 0,void 0,(function(){var d,l,p,h=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return c?("LOCAL_PAYMENT_WINDOW_CLOSED"!==c.code&&i((function(){return h.handleError(c)})),this.toggleLoadingIndicator(!1),i(),[3,6]):[3,1];case 1:if(!this.orderId)throw Te;d={formattedPayload:(p={device_info:a||null,method:n.methodId},p[n.methodId+"_account"]={email:o.email,token:u.nonce,order_id:this.orderId},p.vault_payment_instrument=null,p.set_as_default_stored_instrument=null,p)},s.label=2;case 2:return s.trys.push([2,5,,6]),[4,this.paymentIntegrationService.submitOrder(r,t)];case 3:return s.sent(),[4,this.paymentIntegrationService.submitPayment({methodId:n.methodId,paymentData:d})];case 4:return s.sent(),e(),[3,6];case 5:return l=s.sent(),i((function(){return h.handleError(l)})),[3,6];case 6:return[2]}}))}))}))}))]}}))}))},e.prototype.getLocalPaymentInstance=function(e){this.localPaymentInstance||(this.localPaymentInstance=e)},e.prototype.toggleLoadingIndicator=function(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()},e.prototype.handleError=function(e){var t=(this.braintreeLocalMethods||{}).onError;this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)},e}();const Us=Bs;var xs={size:70,color:"#d9d9d9",backgroundColor:"#ffffff"},qs="embedded-checkout-loading-indicator-rotation",Vs=function(){function e(e){this.styles=(0,s.__assign)((0,s.__assign)({},xs),e&&e.styles),this.defineAnimation(),this.container=this.buildContainer(),this.indicator=this.buildIndicator(),this.container.appendChild(this.indicator)}return e.prototype.show=function(e){if(e){var 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"},e.prototype.hide=function(){var e=this,t=function(){e.container.style.visibility="hidden",e.container.removeEventListener("transitionend",t)};this.container.addEventListener("transitionend",t),this.container.style.opacity="0"},e.prototype.buildContainer=function(){var 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",e},e.prototype.buildIndicator=function(){var 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=qs+" 500ms infinite cubic-bezier(0.69, 0.31, 0.56, 0.83)",e},e.prototype.defineAnimation=function(){var e;if(!document.getElementById(qs)){var t=document.createElement("style");t.id=qs,null===(e=document.head)||void 0===e||e.appendChild(t),t.sheet instanceof CSSStyleSheet&&t.sheet.insertRule("\n @keyframes "+qs+" {\n 0% { transform: translateY(-50%) rotate(0deg); }\n 100% { transform: translateY(-50%) rotate(360deg); }\n }\n ",0)}},e}();const Gs=Vs,Hs=le((function(e){var t=window,n=new Ze(new $e((0,a.getScriptLoader)(),t),t);return new Us(e,n,new Gs({styles:{backgroundColor:"black"}}))}),[{gateway:"braintreelocalmethods"}]);var Ys=function(){function e(e){this._paymentIntegrationService=e}return e.prototype.execute=function(e,t){var n,r;return this._isHostedPaymentFormEnabled(null===(n=e.payment)||void 0===n?void 0:n.methodId,null===(r=e.payment)||void 0===r?void 0:r.gatewayId)&&this._shouldRenderHostedForm?this._executeWithHostedForm(e,t):this._executeWithoutHostedForm(e,t)},e.prototype.initialize=function(e){var t=this;if(!this._isHostedPaymentFormEnabled(null==e?void 0:e.methodId,null==e?void 0:e.gatewayId)||!this._isHostedFieldAvailable(e))return this._shouldRenderHostedForm=!1,Promise.resolve();var n=e&&e.creditCard&&e.creditCard.form,r=this._paymentIntegrationService.getState().getStoreConfigOrThrow().paymentSettings,i=(void 0===r?{}:r).bigpayBaseUrl,o=void 0===i?"":i;if(!n)throw new ye;var a=this._paymentIntegrationService.createHostedForm(o,n);return a.attach().then((function(){return t._shouldRenderHostedForm=!0,t._hostedForm=a,Promise.resolve()}))},e.prototype.deinitialize=function(){return this._hostedForm&&this._hostedForm.detach(),Promise.resolve()},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype._executeWithoutHostedForm=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),i=n&&n.paymentData,!n||!i)throw new ha(["payment.paymentData"]);return[4,this._paymentIntegrationService.submitOrder(r,t)];case 1:return o.sent(),[4,this._paymentIntegrationService.submitPayment((0,s.__assign)((0,s.__assign)({},n),{paymentData:i}))];case 2:return o.sent(),[2]}}))}))},e.prototype._executeWithHostedForm=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!(i=this._hostedForm))throw new Ee(Pe.PaymentNotInitialized);if(!n||!n.methodId)throw new ha(["payment.methodId"]);return[4,this._paymentIntegrationService.submitOrder(r,t)];case 1:return o.sent(),[4,i.validate().then((function(){return i.submit(n)}))];case 2:return o.sent(),[2]}}))}))},e.prototype._isHostedPaymentFormEnabled=function(e,t){return!!e&&!0===this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e,t).config.isHostedFormEnabled},e.prototype._isHostedFieldAvailable=function(e){return!(0,Z.values)(e&&e.creditCard&&e.creditCard.form.fields).every(Z.isNil)},e}();const js=Ys,Ws=le((function(e){return new js(e)}),[{default:!0}]);var Ks=function(){function e(e,t){this._formPoster=e,this._paymentIntegrationService=t}return e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c=this;return(0,s.__generator)(this,(function(u){switch(u.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),i=n&&n.paymentData,!n||!i)throw new ha(["payment.paymentData"]);return[4,this._paymentIntegrationService.submitOrder(r,t)];case 1:u.sent(),u.label=2;case 2:return u.trys.push([2,4,,5]),[4,this._paymentIntegrationService.submitPayment((0,s.__assign)((0,s.__assign)({},n),{paymentData:i}))];case 3:return u.sent(),[3,5];case 4:return o=u.sent(),fa(o)&&"object"==typeof(d=o.body)&&null!==d&&"additional_action_required"in d&&this._isAdditionalActionRequired(o.body)?(a=o.body.additional_action_required.data.redirect_url,[2,new Promise((function(){return c.redirectUrl(a)}))]):[2,Promise.reject(o)];case 5:return[2]}var d}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.initialize=function(){return Promise.resolve()},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.redirectUrl=function(e){return this._formPoster.postForm(e,{})},e.prototype._isAdditionalActionRequired=function(e){var t=e.additional_action_required;return"additional_action_required"===e.status&&t&&"offsite_redirect"===t.type},e}();const Js=Ks,Zs=le((function(e){return new Js((0,xe.createFormPoster)(),e)}),[{id:"laybuy"}]);var Qs=function(){function e(e){this._paymentIntegrationService=e}return e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return[4,this._paymentIntegrationService.submitOrder(e,t)];case 1:return n.sent(),[2,Promise.resolve()]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.initialize=function(){return Promise.resolve()},e.prototype.deinitialize=function(){return Promise.resolve()},e}();const Xs=Qs,$s=le((function(e){return new Xs(e)}),[{id:"testgateway"}]);var ec=function(){function e(e){this._paymentIntegrationService=e}return e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return[4,this._paymentIntegrationService.submitOrder((0,Z.omit)(e,"payment"),t)];case 1:return n.sent(),[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.initialize=function(){return Promise.resolve()},e.prototype.deinitialize=function(){return Promise.resolve()},e}();const tc=ec,nc=le((function(e){return new tc(e)}),[{id:"nopaymentdatarequired"}]);var rc=function(){function e(e){this._paymentIntegrationService=e}return e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return[4,this._paymentIntegrationService.submitOrder((0,s.__assign)((0,s.__assign)({},e),{payment:e.payment?{methodId:e.payment.methodId}:void 0}),t)];case 1:return n.sent(),[2,Promise.resolve()]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.initialize=function(){return Promise.resolve()},e.prototype.deinitialize=function(){return Promise.resolve()},e}();const ic=rc,oc=le((function(e){return new ic(e)}),[{type:"PAYMENT_TYPE_OFFLINE"}]);var ac;!function(e){e.ACKNOWLEDGE="ACKNOWLEDGE",e.FINALIZE="FINALIZE",e.INITIALIZE="INITIALIZE"}(ac||(ac={}));const sc=ac;var cc=function(){function e(e){this._paymentIntegrationService=e}return e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d,l;return(0,s.__generator)(this,(function(p){switch(p.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),i=this._shouldSubmitFullPayload(n)?e:r,o=n&&n.paymentData,a=o&&ma(o)&&o.instrumentId||void 0,c=o&&Ma(o)&&o.shouldSaveInstrument||void 0,u=o&&Ma(o)&&o.shouldSetAsDefaultInstrument||void 0,!n)throw new ha(["payment"]);return d=n.methodId,l=n.gatewayId,[4,this._paymentIntegrationService.submitOrder(i,t)];case 1:return p.sent(),[4,this._paymentIntegrationService.initializeOffsitePayment({methodId:d,gatewayId:l,instrumentId:a,shouldSaveInstrument:c,shouldSetAsDefaultInstrument:u})];case 2:return p.sent(),[2]}}))}))},e.prototype.finalize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return t=this._paymentIntegrationService.getState(),n=t.getOrder(),r=t.getPaymentStatus(),!n||r!==sc.ACKNOWLEDGE&&r!==sc.FINALIZE?[3,2]:[4,this._paymentIntegrationService.finalizeOrder(e)];case 1:return i.sent(),[2];case 2:return[2,Promise.reject(new ya)]}}))}))},e.prototype.initialize=function(){return Promise.resolve()},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype._shouldSubmitFullPayload=function(e){return!!e&&("adyen"===e.gatewayId||"barclaycard"===e.gatewayId||"ccavenuemars"===e.methodId)},e}();const uc=cc,dc=le((function(e){return new uc(e)}),[{type:"PAYMENT_TYPE_HOSTED"}]);var lc=function(){function e(e,t,n){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.loadingIndicator=n}return e.prototype.initialize=function(e){var t,n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(i=(r=e||{}).methodId,o=r.paypalcommerce,!i)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(!o)throw new ye('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');return[4,this.paymentIntegrationService.loadPaymentMethod(i)];case 1:return s.sent(),a=this.paymentIntegrationService.getState(),c=a.getPaymentMethodOrThrow(i),(null===(t=c.initializationData)||void 0===t?void 0:t.orderId)?(this.orderId=null===(n=c.initializationData)||void 0===n?void 0:n.orderId,[2]):[4,this.paypalCommerceIntegrationService.loadPayPalSdk(i)];case 2:return s.sent(),this.loadingIndicatorContainer=o.container.split("#")[1],this.renderButton(i,o),[2]}}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!n)throw new ha(["payment"]);if(!this.orderId)throw new Te;return[4,this.paymentIntegrationService.submitOrder(r,t)];case 1:return i.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n.methodId,this.orderId)];case 2:return i.sent(),[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.deinitialize=function(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()},e.prototype.renderButton=function(e,t){var n=this,r=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),i=(this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData||{}).buttonStyle,o=t.container,a=t.onError,s=t.onRenderButton,c=t.onValidate,u=t.submitForm,d={fundingSource:r.FUNDING.PAYPAL,style:this.paypalCommerceIntegrationService.getValidButtonStyle(i),createOrder:function(){return n.paypalCommerceIntegrationService.createOrder("paypalcommercecheckout")},onClick:function(e,t){return n.handleClick(t,c)},onApprove:function(e){return n.handleApprove(e,u)},onCancel:function(){return n.toggleLoadingIndicator(!1)},onError:function(e){return n.handleError(e,a)}};this.paypalButton=r.Buttons(d),this.paypalButton.isEligible()&&(s&&"function"==typeof s&&s(),this.paypalButton.render(o))},e.prototype.handleClick=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i=this;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:return n=e.resolve,r=e.reject,[4,t((function(){return i.toggleLoadingIndicator(!0),n()}),r)];case 1:return o.sent(),[2]}}))}))},e.prototype.handleApprove=function(e,t){var n=e.orderID;this.orderId=n,t(),this.toggleLoadingIndicator(!1)},e.prototype.handleError=function(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)},e.prototype.toggleLoadingIndicator=function(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()},e}();const pc=lc,hc=le((function(e){return new pc(e,Ct(e),new Gs({styles:{backgroundColor:"black"}}))}),[{id:"paypalcommerce"}]);var mc=function(){function e(e,t,n){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.loadingIndicator=n}return e.prototype.initialize=function(e){var t,n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(i=(r=e||{}).methodId,o=r.paypalcommerce,a=r.paypalcommercecredit,c=a||o,!i)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(o&&console.warn('The "options.paypalcommerce" option is deprecated for this strategy, please use "options.paypalcommercevenmo" instead'),!c)throw new ye('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');return[4,this.paymentIntegrationService.loadPaymentMethod(i)];case 1:return s.sent(),u=this.paymentIntegrationService.getState(),d=u.getPaymentMethodOrThrow(i),(null===(t=d.initializationData)||void 0===t?void 0:t.orderId)?(this.orderId=null===(n=d.initializationData)||void 0===n?void 0:n.orderId,[2]):[4,this.paypalCommerceIntegrationService.loadPayPalSdk(i)];case 2:return s.sent(),this.loadingIndicatorContainer=c.container.split("#")[1],this.renderButton(i,c),[2]}}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!n)throw new ha(["payment"]);if(!this.orderId)throw new Te;return[4,this.paymentIntegrationService.submitOrder(r,t)];case 1:return i.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n.methodId,this.orderId)];case 2:return i.sent(),[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.deinitialize=function(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()},e.prototype.renderButton=function(e,t){var n=this,r=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),i=(this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData||{}).buttonStyle,o=t.container,a=t.onError,s=t.onRenderButton,c=t.onValidate,u=t.submitForm,d=[r.FUNDING.PAYLATER,r.FUNDING.CREDIT],l=!1;d.forEach((function(e){if(!l){var t={fundingSource:e,style:n.paypalCommerceIntegrationService.getValidButtonStyle(i),createOrder:function(){return n.paypalCommerceIntegrationService.createOrder("paypalcommercecreditcheckout")},onClick:function(e,t){return n.handleClick(t,c)},onApprove:function(e){return n.handleApprove(e,u)},onCancel:function(){return n.toggleLoadingIndicator(!1)},onError:function(e){return n.handleError(e,a)}};if(n.paypalButton=r.Buttons(t),n.paypalButton.isEligible()||e!==r.FUNDING.PAYLATER){if(!n.paypalButton.isEligible()&&e===r.FUNDING.CREDIT)throw new _e("PayPal "+e+" is not available for your region. Please use PayPal Checkout instead.");s&&"function"==typeof s&&s(),n.paypalButton.render(o),l=!0}}}))},e.prototype.handleClick=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i=this;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:return n=e.resolve,r=e.reject,[4,t((function(){return i.toggleLoadingIndicator(!0),n()}),r)];case 1:return o.sent(),[2]}}))}))},e.prototype.handleApprove=function(e,t){var n=e.orderID;this.orderId=n,t(),this.toggleLoadingIndicator(!1)},e.prototype.handleError=function(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)},e.prototype.toggleLoadingIndicator=function(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()},e}();const _c=mc,yc=le((function(e){return new _c(e,Ct(e),new Gs({styles:{backgroundColor:"black"}}))}),[{id:"paypalcommercecredit"}]);var fc=function(){function e(e,t,n){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.loadingIndicator=n}return e.prototype.initialize=function(e){var t,n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(i=(r=e||{}).methodId,o=r.paypalcommerce,a=r.paypalcommercevenmo,c=a||o,!i)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(o&&console.warn('The "options.paypalcommerce" option is deprecated for this strategy, please use "options.paypalcommercevenmo" instead'),!c)throw new ye('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');return[4,this.paymentIntegrationService.loadPaymentMethod(i)];case 1:return s.sent(),u=this.paymentIntegrationService.getState(),d=u.getPaymentMethodOrThrow(i),(null===(t=d.initializationData)||void 0===t?void 0:t.orderId)?(this.orderId=null===(n=d.initializationData)||void 0===n?void 0:n.orderId,[2]):[4,this.paypalCommerceIntegrationService.loadPayPalSdk(i)];case 2:return s.sent(),this.loadingIndicatorContainer=c.container.split("#")[1],this.renderButton(i,c),[2]}}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!n)throw new ha(["payment"]);if(!this.orderId)throw new Te;return[4,this.paymentIntegrationService.submitOrder(r,t)];case 1:return i.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n.methodId,this.orderId)];case 2:return i.sent(),[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.deinitialize=function(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()},e.prototype.renderButton=function(e,t){var n=this,r=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),i=(this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData||{}).buttonStyle,o=t.container,a=t.onError,s=t.onRenderButton,c=t.onValidate,u=t.submitForm,d={fundingSource:r.FUNDING.VENMO,style:this.paypalCommerceIntegrationService.getValidButtonStyle(i),createOrder:function(){return n.paypalCommerceIntegrationService.createOrder("paypalcommercevenmocheckout")},onClick:function(e,t){return n.handleClick(t,c)},onApprove:function(e){return n.handleApprove(e,u)},onCancel:function(){return n.toggleLoadingIndicator(!1)},onError:function(e){return n.handleError(e,a)}};if(this.paypalButton=r.Buttons(d),!this.paypalButton.isEligible())throw new _e("PayPal Venmo is not available for your region. Please use PayPal Checkout instead.");s&&"function"==typeof s&&s(),this.paypalButton.render(o)},e.prototype.handleClick=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i=this;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:return n=e.resolve,r=e.reject,[4,t((function(){return i.toggleLoadingIndicator(!0),n()}),r)];case 1:return o.sent(),[2]}}))}))},e.prototype.handleApprove=function(e,t){var n=e.orderID;this.orderId=n,t(),this.toggleLoadingIndicator(!1)},e.prototype.handleError=function(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)},e.prototype.toggleLoadingIndicator=function(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()},e}();const gc=fc,vc=le((function(e){return new gc(e,Ct(e),new Gs({styles:{backgroundColor:"black"}}))}),[{id:"paypalcommercevenmo"}]),wc=function(e){function t(t){var n=e.call(this,t,{message:"The request has timed out or aborted."})||this;return n.name="TimeoutError",n.type="timeout",n}return(0,s.__extends)(t,e),t}(ke);var Cc=function(){function e(e,t,n,r,i){void 0===r&&(r=3e3),void 0===i&&(i=6e5),this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.loadingIndicator=n,this.pollingInterval=r,this.maxPollingTime=i,this.pollingTimer=0,this.stopPolling=Z.noop}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d,l;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.gatewayId,n=e.methodId,r=e.paypalcommerce,i=e.paypalcommercealternativemethods,o=i||r,r&&console.warn('The "options.paypalcommerce" option is deprecated for this strategy, please use "options.paypalcommercealternativemethods" instead'),!n)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new ye('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!o)throw new ye('Unable to initialize payment because "options.paypalcommercealternativemethods" argument is not provided.');return a=this.paymentIntegrationService.getState(),c=a.getPaymentMethodOrThrow(n,t),u=c.initializationData||{},d=u.orderId,l=u.shouldRenderFields,d?(this.orderId=d,[2]):[4,this.paypalCommerceIntegrationService.loadPayPalSdk(n)];case 1:return s.sent(),this.loadingIndicatorContainer=o.container.split("#")[1],this.renderButton(n,t,o),l&&this.renderFields(n,o),[2]}}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!n)throw new ha(["payment"]);if(!this.orderId)throw new Te;return this.isNonInstantPaymentMethod(n.methodId)?[3,2]:[4,this.paymentIntegrationService.submitOrder(r,t)];case 1:i.sent(),i.label=2;case 2:return[4,this.paypalCommerceIntegrationService.submitPayment(n.methodId,this.orderId)];case 3:return i.sent(),[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.deinitialize=function(){var e;return this.deinitializePollingMechanism(),this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()},e.prototype.reinitializeStrategy=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this.deinitialize()];case 1:return t.sent(),[4,this.initialize(e)];case 2:return t.sent(),[2]}}))}))},e.prototype.renderButton=function(e,t,n){var r=this,i=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),o=(this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e,t).initializationData||{}).buttonStyle,a=n.container,s=n.onError,c=n.onRenderButton,u=n.submitForm,d={fundingSource:e,style:this.paypalCommerceIntegrationService.getValidButtonStyle(o),createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommercealternativemethodscheckout")},onClick:function(i,o){return r.handleClick(e,t,n,o)},onApprove:function(e){return r.handleApprove(e,u)},onCancel:function(){return r.resetPollingMechanism()},onError:function(e){return r.handleError(e,s)}};this.paypalButton=i.Buttons(d),this.paypalButton.isEligible()&&(c&&"function"==typeof c&&c(),this.paypalButton.render(a))},e.prototype.handleClick=function(e,t,n,r){return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return i=n.onValidate,o=r.resolve,a=r.reject,this.isNonInstantPaymentMethod(e)?[3,2]:[4,this.initializePollingMechanism(e,t,n)];case 1:s.sent(),s.label=2;case 2:return[4,i((function(){return c.toggleLoadingIndicator(!0),o()}),a)];case 3:return s.sent(),[2]}}))}))},e.prototype.handleApprove=function(e,t){var n=e.orderID;this.orderId=n,this.deinitializePollingMechanism(),t(),this.toggleLoadingIndicator(!1)},e.prototype.handleError=function(e,t){this.resetPollingMechanism(),t&&"function"==typeof t&&t(e)},e.prototype.renderFields=function(e,t){var n=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),r=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),i=r.firstName,o=r.lastName,a=r.email,s=t.apmFieldsContainer,c=t.apmFieldsStyles;if(!s)throw new ye('Unable to initialize payment because "options.paypalcommercealternativemethods" argument should contain "apmFieldsContainer".');var u=document.querySelector(s);u&&(u.innerHTML="");var d={fundingSource:e,style:c||{},fields:{name:{value:i+" "+o},email:{value:a}}};n.PaymentFields(d).render(s)},e.prototype.initializePollingMechanism=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return r=n.onError,i=n.submitForm,[4,new Promise((function(e,t){var n=setTimeout(e,d.pollingInterval);d.stopPolling=function(){clearTimeout(n),t()}}))];case 1:s.sent(),s.label=2;case 2:return s.trys.push([2,7,,8]),this.pollingTimer+=this.pollingInterval,[4,this.paypalCommerceIntegrationService.getOrderStatus()];case 3:return o=s.sent(),a=o===dt.Approved,c=o===dt.Created||o===dt.PayerActionRequired,a?(this.deinitializePollingMechanism(),[2,i()]):c&&this.pollingTimer0&&(n[o.code]={discount_amount:e.toInteger(o.discountedAmount),discount_display_name:o.displayName})}return t.discountAmount>0&&(n.DISCOUNTED_AMOUNT={discount_amount:e.toInteger(t.discountAmount),discount_display_name:"discount"}),n},e.prototype._getCategories=function(e){return e?e.map((function(e){return e.map((function(e){return e.name}))})):[[]]},e}();const lu=du,pu=function(){function e(e){void 0===e&&(e=window),this._window=e}return e.prototype.load=function(e,t){void 0===e&&(e="");var n=this._getScriptURI(t);if(function(e,t,n,r,i,o,a,s){var c=e[n]||{},u=document.createElement(o),d=document.getElementsByTagName(o)[0],l=function(e,t,n){return function(){e[t]._.push([n,arguments])}};c[r]=l(c,r,"set");var p=c[r];c[i]={},c[i]._=[],p._=[],c._=[],c[i][a]=l(c,i,a),c.jsReady=function(){c._.push([a,arguments])};for(var h=0,m="set add save post open empty reset on off trigger ready setProduct".split(" ");h0?o(new be(e.ErrorDescription)):e.Payment&&e.Payment.ExtendedData&&e.Payment.ExtendedData.SignatureVerification===ad.Yes?i({token:t}):o(new be("Transaction signature could not be validated."));case nd.Failure:return o(new be("User failed authentication or an error was encountered while processing the transaction."));case nd.Error:return o(new be(e.ErrorDescription))}}));var a={AcsUrl:e.acs_url,Payload:e.merchant_data},s=n._mapToPartialOrder(t,e.payer_auth_request);r.continue(od.CCA,a,s)}))}))},e.prototype._mapToPartialOrder=function(e,t){var n={BillingAddress:this._mapToCardinalAddress(e.billingAddress)};return e.paymentData&&(n.Account=this._mapToCardinalAccount(e.paymentData)),e.billingAddress.email&&(n.Email1=e.billingAddress.email),e.shippingAddress&&(n.ShippingAddress=this._mapToCardinalAddress(e.shippingAddress)),{Consumer:n,OrderDetails:{OrderNumber:e.id,Amount:e.amount,CurrencyCode:e.currencyCode,OrderChannel:"S",TransactionId:t}}},e.prototype._mapToCardinalAccount=function(e){return{AccountNumber:Number(e.ccNumber),ExpirationMonth:Number(e.ccExpiry.month),ExpirationYear:Number(e.ccExpiry.year),NameOnAccount:e.ccName,CardCode:Number(e.ccCvv)}},e.prototype._mapToCardinalAddress=function(e){var 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},e.prototype._getClientSDK=function(){if(!this._sdk)throw new Pn(bn.PaymentNotInitialized);return this._sdk},e}();const ud=function(){function e(e,t){void 0===t&&(t=window),this._scriptLoader=e,this._window=t}return e.prototype.load=function(e,t){var n=this,r=t?"https://songbirdstag.cardinalcommerce.com/edge/v1/songbird.js":"https://songbird.cardinalcommerce.com/edge/v1/songbird.js";return this._scriptLoader.loadScript(r+"?v="+e).then((function(){if(!n._window.Cardinal)throw new gi;return n._window.Cardinal}))},e}();var dd=function(){function e(e,t,n,r){this._store=e,this._paymentActionCreator=t,this._paymentMethodActionCreator=n,this._cardinalClient=r}return e.prototype.prepare=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._cardinalClient.load(e.id,e.config.testMode)];case 1:return r.sent(),n=(t=this._cardinalClient).configure,[4,this._getClientToken(e)];case 2:return[4,n.apply(t,[r.sent()])];case 3:return r.sent(),[2]}}))}))},e.prototype.start=function(e,t,n,r){return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u,d,l,p,h,m,_,y,f;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return i=this._store.getState(),o=i.instruments.getCardInstrument,a=i.paymentMethods.getPaymentMethodOrThrow,c=t.payment,d=(u=void 0===c?{}:c).methodId,l=void 0===d?"":d,p=u.paymentData,m=Gn(h=void 0===p?{}:p)&&o(h.instrumentId),(_=m?m.iin:r&&r.getBin())?[4,this._cardinalClient.runBinProcess(_)]:[3,2];case 1:s.sent(),s.label=2;case 2:return s.trys.push([2,4,,9]),[4,e((0,Z.merge)(t,{payment:{paymentData:{threeDSecure:{token:a(l).clientToken}}}}),n)];case 3:return[2,s.sent()];case 4:if(!((y=s.sent())instanceof x&&(0,Z.some)(y.body.errors,{code:"three_d_secure_required"})))throw y;return[4,this._cardinalClient.getThreeDSecureData(y.body.three_ds_result,this._getOrderData())];case 5:return f=s.sent(),r?[3,7]:[4,this._store.dispatch(this._paymentActionCreator.submitPayment((0,Z.merge)(t.payment,{paymentData:{threeDSecure:f}})))];case 6:return[2,s.sent()];case 7:return[4,r.submit((0,Z.merge)(t.payment,{paymentData:{threeDSecure:f}}))];case 8:return s.sent(),[2,this._store.getState()];case 9:return[2]}}))}))},e.prototype._getClientToken=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return e.clientToken?[2,e.clientToken]:[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e.id))];case 1:return[2,(0,t.sent().paymentMethods.getPaymentMethodOrThrow)(e.id).clientToken||""]}}))}))},e.prototype._getOrderData=function(){var e=this._store.getState(),t=e.billingAddress.getBillingAddressOrThrow(),n=e.shippingAddress.getShippingAddress(),r=e.checkout.getCheckoutOrThrow(),i=e.order.getOrderOrThrow();return{billingAddress:t,shippingAddress:n,currencyCode:r.cart.currency.code,id:i.orderId.toString(),amount:r.cart.cartAmount}},e}();const ld=dd,pd=function(e){function t(t){var n=e.call(this,t||"The selected payment method was declined. Please select another payment method.")||this;return n.name="PaymentMethodDeclinedError",n.type="payment_declined",n}return(0,s.__extends)(t,e),t}(p);var hd=function(e){function t(t,n,r,i,o,a,s){var c=e.call(this,t,n,r,i)||this;return c._paymentMethodActionCreator=o,c._CBAMGPSScriptLoader=a,c._locale=s,c._sessionId="",c}return(0,s.__extends)(t,e),t.prototype.initialize=function(t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d,l,p=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return[4,e.prototype.initialize.call(this,t)];case 1:return s.sent(),n=t.methodId,[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n))];case 2:return r=s.sent(),i=r.paymentMethods.getPaymentMethodOrThrow(n),o=i.clientToken,a=i.initializationData,c=a.isTestModeFlagEnabled,u=void 0!==c&&c,d=a.merchantId,i.config.is3dsEnabled?(l=this,[4,this._CBAMGPSScriptLoader.load(u)]):[3,5];case 3:if(l._threeDSjs=s.sent(),!this._threeDSjs)throw new Pn(bn.PaymentNotInitialized);if(!o||!d)throw new m(h.MissingPaymentMethod);return this._sessionId=o,[4,this._threeDSjs.configure({merchantId:d,sessionId:this._sessionId,callback:function(){var e;if(null===(e=p._threeDSjs)||void 0===e?void 0:e.isConfigured())return p._store.getState();throw new be("Failed to configure 3DS API.")},configuration:{userLanguage:this._locale,wsVersion:62}})];case 4:s.sent(),s.label=5;case 5:return[2,Promise.resolve(this._store.getState())]}}))}))},t.prototype.execute=function(t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d=this;return(0,s.__generator)(this,(function(l){if(r=t.payment,i=r&&r.paymentData,!r||!i)throw new cu(["payment.paymentData"]);return o=this._store.getState().paymentMethods.getPaymentMethodOrThrow,a=o(r.methodId),(c=a.config.is3dsEnabled)&&(u=(0,s.__assign)((0,s.__assign)({},i),{threeDSecure:{token:this._sessionId}}),t.payment&&(t.payment.paymentData=u)),[2,e.prototype.execute.call(this,t,n).catch((function(e){if(!(c&&e instanceof x&&(0,Z.some)(e.body.errors,{code:"three_d_secure_required"})))return Promise.reject(e);var t=d._store.getState(),n=t.order.getOrder(),r=t.config.getStoreConfigOrThrow().storeProfile.storeId;if(!n||!d._sessionId)throw new m(h.MissingCheckout);var i=r+"_"+n.orderId,o=e.body.three_ds_result.token;return o?d._initiateAuthentication(i,o):Promise.reject(e)}))]}))}))},t.prototype.finalize=function(e){var t=this._store.getState(),n=t.order.getOrder();return n&&t.payment.getPaymentStatus()===bu?this._store.dispatch(this._orderActionCreator.finalizeOrder(n.orderId,e)):Promise.reject(new Hc)},t.prototype.deinitialize=function(){return this._threeDSjs=void 0,this._sessionId="",e.prototype.deinitialize.call(this)},t.prototype._initiateAuthentication=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r=this;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return[4,new Promise((function(n,i){if(!r._threeDSjs)throw new Pn(bn.PaymentNotInitialized);r._threeDSjs.initiateAuthentication(e,t,(function(e){var t=e.error;return t?i(new pd(t.msg)):r._threeDSjs&&"PROCEED"===e.gatewayRecommendation?n(e.restApiResponse):i(new pd)}))}))];case 1:if((n=i.sent()).transaction&&"AUTHENTICATION_AVAILABLE"===n.transaction.authenticationStatus)return[2,this._authenticatePayer(e,t)];throw new pd}}))}))},t.prototype._authenticatePayer=function(e,t,n){return void 0===n&&(n=1),(0,s.__awaiter)(this,void 0,void 0,(function(){var r=this;return(0,s.__generator)(this,(function(i){return[2,new Promise((function(i,o){if(!r._threeDSjs)return o(new Pn(bn.PaymentNotInitialized));r._threeDSjs.authenticatePayer(e,t,(function(i){return(0,s.__awaiter)(r,void 0,void 0,(function(){var r;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:return(r=i.error)?r.cause&&"SERVER_BUSY"===r.cause&&n<5?[4,new Promise((function(e){return setTimeout(e,3e3)}))]:[3,2]:[3,3];case 1:return a.sent(),[2,this._authenticatePayer(e,t,++n)];case 2:return[2,o(new pd)];case 3:return[2,new Promise(Z.noop)]}}))}))}),{fullScreenRedirect:!0})}))]}))}))},t}(wu);const md=hd;var _d=function(){function e(e,t){void 0===t&&(t=window),this._scriptLoader=e,this._window=t}return e.prototype.load=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this._scriptLoader.loadScript("//"+(e?"test":"ap")+"-gateway.mastercard.com/static/threeDS/1.3.0/three-ds.min.js")];case 1:if(t.sent(),!this._window.ThreeDS)throw new gi;return[2,this._window.ThreeDS]}}))}))},e}();const yd=_d;var fd;!function(e){e.StartCheckout="startCheckout",e.CompleteCheckout="completeCheckout",e.CancelCheckout="cancelCheckout"}(fd||(fd={}));var gd=function(){function e(e,t,n,r,i,o,a,s,c){this._store=e,this._checkoutActionCreator=t,this._orderActionCreator=n,this._paymentActionCreator=r,this._paymentMethodActionCreator=i,this._paymentStrategyActionCreator=o,this._requestSender=a,this._chasePayScriptLoader=s,this._wepayRiskClient=c,this._walletEvent$=new u.Subject}return e.prototype.initialize=function(e){var t=this;if(this._methodId=e.methodId,!e.chasepay)throw new ae('Unable to initialize payment because "options.chasepay" argument is not provided.');var n=e.chasepay.walletButton&&document.getElementById(e.chasepay.walletButton);return n&&(this._walletButton=n,this._walletButton.addEventListener("click",this._handleWalletButtonClick)),this._configureWallet(e.chasepay).then((function(){return t._store.getState()}))},e.prototype.deinitialize=function(){return this._walletButton&&this._walletButton.removeEventListener("click",this._handleWalletButtonClick),this._walletButton=void 0,this._chasePayClient=void 0,Promise.resolve(this._store.getState())},e.prototype.execute=function(e,t){var n=this;return this._getPayment().catch((function(e){if(e.subtype===h.MissingPayment)return n._displayWallet().then((function(){return n._getPayment()}));throw e})).then((function(r){return n._createOrder(r,e.useStoreCredit,t)}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype._configureWallet=function(e){var t=this,n=this._store.getState(),r=n.paymentMethods.getPaymentMethod(this._methodId),i=n.config.getStoreConfig();if(!r)throw new m(h.MissingPaymentMethod);if(!i)throw new m(h.MissingCheckoutConfig);return this._chasePayScriptLoader.load(r.config.testMode).then((function(n){var r=n.ChasePay;t._chasePayClient=r,e.logoContainer&&document.getElementById(e.logoContainer)&&t._chasePayClient.insertBrandings({color:"white",containers:[e.logoContainer]}),t._chasePayClient.configure({language:i.storeProfile.storeLanguage}),t._chasePayClient.on(fd.CancelCheckout,(function(){t._walletEvent$.next({type:fd.CancelCheckout}),e.onCancel&&e.onCancel()})),t._chasePayClient.on(fd.CompleteCheckout,(function(n){t._setSessionToken(n.sessionToken).then((function(){t._walletEvent$.next({type:fd.CompleteCheckout}),e.onPaymentSelect&&e.onPaymentSelect()}))}))}))},e.prototype._displayWallet=function(){var e=this;return this._store.dispatch(this._paymentStrategyActionCreator.widgetInteraction((function(){return e._store.dispatch(e._paymentMethodActionCreator.loadPaymentMethod(e._methodId)).then((function(t){var n=t.paymentMethods.getPaymentMethod(e._methodId);if(!e._chasePayClient)throw new Pn(bn.PaymentNotInitialized);if(!n)throw new m(h.MissingPaymentMethod);e._chasePayClient.showLoadingAnimation(),e._chasePayClient.startCheckout(n.initializationData.digitalSessionId)})),new Promise((function(t,n){e._walletEvent$.pipe((0,d.take)(1)).subscribe((function(e){e.type===fd.CancelCheckout?n(new uu):e.type===fd.CompleteCheckout&&t()}))}))}),{methodId:this._methodId}),{queueId:"widgetInteraction"})},e.prototype._setSessionToken=function(e){var t=this,n=this._store.getState().paymentMethods.getPaymentMethod(this._methodId),r=n&&n.initializationData.merchantRequestId;return this._requestSender.post("checkout.php",{headers:(0,s.__assign)({Accept:"text/html","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},C),body:{action:"set_external_checkout",provider:this._methodId,sessionToken:e,merchantRequestId:r}}).then((function(){return Promise.all([t._store.dispatch(t._checkoutActionCreator.loadCurrentCheckout()),t._store.dispatch(t._paymentMethodActionCreator.loadPaymentMethod(t._methodId))])})).then((function(){return t._store.getState()}))},e.prototype._getPayment=function(){var e=this;return this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(this._methodId)).then((function(){return"wepay"===e._methodId?e._wepayRiskClient.initialize().then((function(e){return e.getRiskToken()})):""})).then((function(t){var n=e._store.getState().paymentMethods.getPaymentMethod(e._methodId);if(!n)throw new m(h.MissingPaymentMethod);if(!n.initializationData.paymentCryptogram)throw new m(h.MissingPayment);var r={method:e._methodId,cryptogramId:n.initializationData.paymentCryptogram,eci:n.initializationData.eci,transactionId:btoa(n.initializationData.reqTokenId),ccExpiry:{month:n.initializationData.expDate.toString().substr(0,2),year:n.initializationData.expDate.toString().substr(2,2)},ccNumber:n.initializationData.accountNum,accountMask:n.initializationData.accountMask,extraData:t?{riskToken:t}:void 0};return{methodId:e._methodId,paymentData:r}}))},e.prototype._createOrder=function(e,t,n){var r=this;return this._store.dispatch(this._orderActionCreator.submitOrder({useStoreCredit:t},n)).then((function(){return r._store.dispatch(r._paymentActionCreator.submitPayment(e))}))},e.prototype._handleWalletButtonClick=function(e){e.preventDefault(),this._displayWallet()},(0,s.__decorate)([yn],e.prototype,"_handleWalletButtonClick",null),e}();const vd=gd;var wd;!function(e){e.OffsiteRedirect="offsite_redirect"}(wd||(wd={}));var Cd=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return(0,s.__extends)(t,e),t.prototype.finalize=function(e){var t=this._store.getState(),n=t.order.getOrder();return n&&t.payment.getPaymentStatus()===bu?this._store.dispatch(this._orderActionCreator.finalizeOrder(n.orderId,e)):Promise.reject(new Hc)},t.prototype._executeWithHostedForm=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!(i=this._hostedForm))throw new Pn(bn.PaymentNotInitialized);if(!n||!n.methodId)throw new cu(["payment.methodId"]);a.label=1;case 1:return a.trys.push([1,5,,6]),[4,i.validate()];case 2:return a.sent(),[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 3:return a.sent(),[4,i.submit(n)];case 4:return a.sent(),[3,6];case 5:return o=a.sent(),[2,this._processResponse(o)];case 6:return[2,this._store.dispatch(this._orderActionCreator.loadCurrentOrder())]}}))}))},t.prototype._processResponse=function(e){if(!(e instanceof x))return Promise.reject(e);var t=e.body.additional_action_required;return t&&t.type===wd.OffsiteRedirect?this._performRedirect(t):Promise.reject(e)},t.prototype._performRedirect=function(e){return new Promise((function(){window.location.replace(e.data.redirect_url)}))},t}(wu);const Sd=Cd;var Id=["boleto","oxxo","qpay","ideal"],bd=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return(0,s.__extends)(t,e),t.prototype._executeWithoutHostedForm=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),i=null==n?void 0:n.paymentData,!n||!i)throw new cu(["payment.paymentData"]);return[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 1:a.sent(),a.label=2;case 2:return a.trys.push([2,4,,5]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment((0,s.__assign)((0,s.__assign)({},n),{paymentData:(0,s.__assign)((0,s.__assign)({},i),{formattedPayload:this._createFormattedPayload(n.methodId,i)})})))];case 3:return[2,a.sent()];case 4:return o=a.sent(),[2,this._processResponse(o)];case 5:return[2]}}))}))},t.prototype._createFormattedPayload=function(e,t){var n={ccDocument:""},r="ccDocument"in t?t.ccDocument:"";return-1!==Id.indexOf(e)&&r&&(n.ccDocument=r),n},t}(Sd);const Pd=bd;var Ed=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return(0,s.__extends)(t,e),t.prototype._executeWithoutHostedForm=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),i=n&&n.paymentData,!n||!i)throw new cu(["payment.paymentData"]);return[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 1:a.sent(),a.label=2;case 2:return a.trys.push([2,4,,5]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment((0,s.__assign)((0,s.__assign)({},n),{paymentData:(0,s.__assign)((0,s.__assign)({},i),{formattedPayload:this._createFormattedPayload(n.methodId,i)})})))];case 3:return[2,a.sent()];case 4:return o=a.sent(),[2,this._processResponse(o)];case 5:return[2]}}))}))},t.prototype._createFormattedPayload=function(e,t){if("fawry"===e&&"customerMobile"in t&&"customerEmail"in t)return{customerMobile:t.customerMobile,customerEmail:t.customerEmail}},t}(Sd);const Ad=Ed;var Od=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return(0,s.__extends)(t,e),t.prototype._executeWithoutHostedForm=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),i=null==n?void 0:n.paymentData,!n||!i)throw new cu(["payment.paymentData"]);return[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 1:a.sent(),a.label=2;case 2:return a.trys.push([2,4,,5]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment((0,s.__assign)((0,s.__assign)({},n),{paymentData:(0,s.__assign)((0,s.__assign)({},i),{formattedPayload:this._createFormattedPayload(n.methodId,i)})})))];case 3:return[2,a.sent()];case 4:return o=a.sent(),[2,this._processResponse(o)];case 5:return[2]}}))}))},t.prototype._createFormattedPayload=function(e,t){if("ideal"===e&&"bic"in t)return{bic:t.bic}},t}(Sd);const kd=Od;var Td=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return(0,s.__extends)(t,e),t.prototype._executeWithoutHostedForm=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),i=null==n?void 0:n.paymentData,!n||!i)throw new cu(["payment.paymentData"]);return[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 1:a.sent(),a.label=2;case 2:return a.trys.push([2,4,,5]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment((0,s.__assign)((0,s.__assign)({},n),{paymentData:(0,s.__assign)((0,s.__assign)({},i),{formattedPayload:this._createFormattedPayload(n.methodId,i)})})))];case 3:return[2,a.sent()];case 4:return o=a.sent(),[2,this._processResponse(o)];case 5:return[2]}}))}))},t.prototype._createFormattedPayload=function(e,t){var n={iban:"",bic:""},r="iban"in t?t:n,i=r.iban,o=r.bic;return"sepa"===e&&document&&(n.iban=i,n.bic=o),n},t}(Sd);const Md=Td;var Dd=function(){function e(e,t,n,r,i,o,a,s){this._store=e,this._checkoutValidator=t,this._orderActionCreator=n,this._paymentActionCreator=r,this._paymentMethodActionCreator=i,this._remoteCheckoutRequestSender=o,this._storeCreditActionCreator=a,this._clearpayScriptLoader=s}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return t=this._store.getState().paymentMethods.getPaymentMethodOrThrow,n=t(e.methodId,e.gatewayId),r=this,[4,this._clearpayScriptLoader.load(n)];case 1:return r._clearpaySdk=i.sent(),[2,this._store.getState()]}}))}))},e.prototype.deinitialize=function(){return this._clearpaySdk=void 0,Promise.resolve(this._store.getState())},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!e.payment)throw new cu(["payment.gatewayId","payment.methodId"]);if(n=e.payment,r=n.gatewayId,i=n.methodId,!r||!i)throw new cu(["payment.gatewayId","payment.methodId"]);return o=this._store.getState().checkout.getCheckoutOrThrow().isStoreCreditApplied,a=this._store.getState(),void 0===o?[3,2]:[4,this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(o))];case 1:a=s.sent(),s.label=2;case 2:return[4,this._checkoutValidator.validate(a.checkout.getCheckout(),t)];case 3:if(s.sent(),c=this._store.getState().billingAddress.getBillingAddressOrThrow().countryCode,!this._isCountrySupported(c))throw new ae("Unable to proceed because billing country is not supported.");return[4,this._loadPaymentMethod(r,i,t)];case 4:return a=s.sent(),[4,this._redirectToClearpay(c,a.paymentMethods.getPaymentMethod(i,r))];case 5:return s.sent(),[2,new Promise(Z.noop)]}}))}))},e.prototype.finalize=function(e){var t,n,r;return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(i=this._store.getState(),o=i.payment.getPaymentId(),a=i.config.getContextConfig(),!o)throw new m(h.MissingCheckout);if(!a||!a.payment.token)throw new m(h.MissingCheckoutConfig);return c={methodId:o.providerId,paymentData:{nonce:a.payment.token}},[4,this._store.dispatch(this._orderActionCreator.submitOrder({},e))];case 1:s.sent(),s.label=2;case 2:return s.trys.push([2,4,,7]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment(c))];case 3:return[2,s.sent()];case 4:return u=s.sent(),[4,this._remoteCheckoutRequestSender.forgetCheckout()];case 5:return s.sent(),[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethods())];case 6:throw s.sent(),new hu(null===(r=null===(n=null===(t=u.body)||void 0===t?void 0:t.errors)||void 0===n?void 0:n[0])||void 0===r?void 0:r.message);case 7:return[2]}}))}))},e.prototype._redirectToClearpay=function(e,t){if(!this._clearpaySdk||!t||!t.clientToken)throw new Pn(bn.PaymentNotInitialized);this._clearpaySdk.initialize({countryCode:e}),this._clearpaySdk.redirect({token:t.clientToken})},e.prototype._isCountrySupported=function(e){return"GB"===e},e.prototype._loadPaymentMethod=function(e,t,n){var r;return(0,s.__awaiter)(this,void 0,void 0,(function(){var i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e,(0,s.__assign)((0,s.__assign)({},n),{params:(0,s.__assign)((0,s.__assign)({},null==n?void 0:n.params),{method:t})})))];case 1:return[2,o.sent()];case 2:if((i=o.sent())instanceof x&&422===(null===(r=i.body)||void 0===r?void 0:r.status))throw new ae("Clearpay can't process your payment for this order, please try another payment method");throw i;case 3:return[2]}}))}))},e}();const Rd=Dd;var zd=function(){function e(e,t){void 0===t&&(t=window),this._scriptLoader=e,this._window=t}return e.prototype.load=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this._scriptLoader.loadScript(this._getScriptUrl(e.config.testMode))];case 1:if(t.sent(),!this._window.AfterPay)throw new gi;return[2,this._window.AfterPay]}}))}))},e.prototype._getScriptUrl=function(e){return e?"//portal.sandbox.clearpay.co.uk/afterpay-async.js":"//portal.clearpay.co.uk/afterpay-async.js"},e}();const Nd=zd,Ld=function(e){function t(t,n,r,i,o){var a=e.call(this,t,n,r,i)||this;return a._formPoster=o,a}return(0,s.__extends)(t,e),t.prototype.execute=function(t,n){var r=this;return e.prototype.execute.call(this,t,n).catch((function(e){return e instanceof x&&(0,Z.some)(e.body.errors,{code:"three_d_secure_required"})?new Promise((function(){r._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)}))},t.prototype.finalize=function(e){var t=this._store.getState(),n=t.order.getOrder();return n&&t.payment.getPaymentStatus()===bu?this._store.dispatch(this._orderActionCreator.finalizeOrder(n.orderId,e)):Promise.reject(new Hc)},t}(wu);var Fd=function(e){function t(t,n,r,i,o){var a=e.call(this,t,n,r,i)||this;return a._store=t,a._orderActionCreator=n,a._paymentActionCreator=r,a._hostedFormFactory=i,a._formPoster=o,a}return(0,s.__extends)(t,e),t.prototype.finalize=function(e){var t=this._store.getState(),n=t.order.getOrder();return n&&t.payment.getPaymentStatus()===bu?this._store.dispatch(this._orderActionCreator.finalizeOrder(n.orderId,e)):Promise.reject(new Hc)},t.prototype._executeWithoutHostedForm=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a=this;return(0,s.__generator)(this,(function(c){switch(c.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),i=n&&n.paymentData,!n||!i)throw new cu(["payment.paymentData"]);return[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 1:c.sent(),c.label=2;case 2:return c.trys.push([2,4,,5]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment((0,s.__assign)((0,s.__assign)({},n),{paymentData:i})))];case 3:return[2,c.sent()];case 4:return(o=c.sent())instanceof x&&(0,Z.some)(o.body.errors,{code:"three_d_secure_required"})?[2,new Promise((function(){return a._formPoster.postForm(o.body.three_ds_result.acs_url,{PaReq:o.body.three_ds_result.payer_auth_request||null,TermUrl:o.body.three_ds_result.callback_url||null,MD:o.body.three_ds_result.merchant_data||null})}))]:[2,Promise.reject(o)];case 5:return[2]}}))}))},t.prototype._executeWithHostedForm=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a=this;return(0,s.__generator)(this,(function(c){switch(c.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!(i=this._hostedForm))throw new Pn(bn.PaymentNotInitialized);if(!n||!n.methodId)throw new cu(["payment.methodId"]);c.label=1;case 1:return c.trys.push([1,5,,6]),[4,i.validate()];case 2:return c.sent(),[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 3:return c.sent(),[4,i.submit(n)];case 4:return c.sent(),[3,6];case 5:return(o=c.sent())instanceof x&&(0,Z.some)(o.body.errors,{code:"three_d_secure_required"})?[2,new Promise((function(){return a._formPoster.postForm(o.body.three_ds_result.acs_url,{PaReq:o.body.three_ds_result.payer_auth_request||null,TermUrl:o.body.three_ds_result.callback_url||null,MD:o.body.three_ds_result.merchant_data||null})}))]:[2,Promise.reject(o)];case 6:return[2,this._store.dispatch(this._orderActionCreator.loadCurrentOrder())]}}))}))},t}(wu);const Bd=Fd;var Ud=function(e){function t(t,n,r,i,o){var a=e.call(this,t,n,r,i)||this;return a._threeDSecureFlow=o,a}return(0,s.__extends)(t,e),t.prototype.initialize=function(t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return[4,e.prototype.initialize.call(this,t)];case 1:return i.sent(),n=this._store.getState().paymentMethods.getPaymentMethodOrThrow,(r=n(t.methodId)).config.is3dsEnabled?[4,this._threeDSecureFlow.prepare(r)]:[3,3];case 2:i.sent(),i.label=3;case 3:return[2,this._store.getState()]}}))}))},t.prototype.execute=function(t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o;return(0,s.__generator)(this,(function(a){return r=t.payment,i=(void 0===r?{}:r).methodId,o=void 0===i?"":i,(0,this._store.getState().paymentMethods.getPaymentMethodOrThrow)(o).config.is3dsEnabled?[2,this._threeDSecureFlow.start(e.prototype.execute.bind(this),t,n,this._hostedForm)]:[2,e.prototype.execute.call(this,t,n)]}))}))},t}(wu);const xd=Ud;var qd=function(e){function t(t,n,r,i,o){var a=e.call(this,t,n,r,i)||this;return a._threeDSecureFlow=o,a}return(0,s.__extends)(t,e),t.prototype.initialize=function(t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return[4,e.prototype.initialize.call(this,t)];case 1:return i.sent(),n=this._store.getState().paymentMethods.getPaymentMethodOrThrow,(r=n(t.methodId)).config.is3dsEnabled?[4,this._threeDSecureFlow.prepare(r)]:[3,3];case 2:i.sent(),i.label=3;case 3:return[2,this._store.getState()]}}))}))},t.prototype.execute=function(t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o;return(0,s.__generator)(this,(function(a){return r=t.payment,i=(void 0===r?{}:r).methodId,o=void 0===i?"":i,(0,this._store.getState().paymentMethods.getPaymentMethodOrThrow)(o).config.is3dsEnabled?[2,this._threeDSecureFlow.start(e.prototype.execute.bind(this),t,n,this._hostedForm)]:[2,e.prototype.execute.call(this,t,n)]}))}))},t}(wu);const Vd=qd;var Gd;!function(e){e.complete="complete",e.authentication_not_required="authentication_not_required",e.failed="failed"}(Gd||(Gd={}));const Hd=function(e){function t(t,n,r){var i=e.call(this,r||"There was an error while processing your payment. Please try again or contact us.")||this;return i.type=t,i.name=n,i}return(0,s.__extends)(t,e),t}(p);var Yd=function(){function e(e,t,n,r,i,o,a){this._store=e,this._paymentMethodActionCreator=t,this._orderActionCreator=n,this._paymentActionCreator=r,this._storeCreditActionCreator=i,this._digitalRiverScriptLoader=o,this._billingAddressActionCreator=a}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u=this;return(0,s.__generator)(this,(function(d){switch(d.label){case 0:return this._digitalRiverInitializeOptions=e.digitalriver,t=this._store.getState().paymentMethods.getPaymentMethodOrThrow(e.methodId),n=t.initializationData,r=n.publicKey,i=n.paymentLanguage,o=this._getDigitalRiverInitializeOptions().containerId,a=this,[4,this._digitalRiverScriptLoader.load(r,i)];case 1:return a._digitalRiverJS=d.sent(),c=this,[4,this._store.subscribe((function(t){return(0,s.__awaiter)(u,void 0,void 0,(function(){var n,a;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return t.paymentStrategies.isInitialized({methodId:e.methodId,gatewayId:e.gatewayId})?(n=document.getElementById(o))?(n.innerHTML="",a=this,[4,this._digitalRiverScriptLoader.load(r,i)]):[3,2]:[3,4];case 1:a._digitalRiverJS=s.sent(),s.label=2;case 2:return[4,this._loadWidget(e)];case 3:s.sent(),s.label=4;case 4:return[2]}}))}))}),(function(e){var t=e.checkout.getCheckout();return t&&t.outstandingBalance}),(function(e){var t=e.checkout.getCheckout();return t&&t.coupons}))];case 2:return c._unsubscribe=d.sent(),[2,this._loadWidget(e)]}}))}))},e.prototype.deinitialize=function(){this._unsubscribe&&this._unsubscribe();var e=this._getDigitalRiverInitializeOptions().containerId,t=document.getElementById(e);return t&&(t.innerHTML=""),Promise.resolve(this._store.getState())},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d,l,p;return(0,s.__generator)(this,(function(_){switch(_.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!n||!n.paymentData)throw new cu(["payment.paymentData"]);return i=n.paymentData,o=n.methodId,a=i.shouldSetAsDefaultInstrument,c=void 0!==a&&a,void 0===(u=this._store.getState().checkout.getCheckoutOrThrow().isStoreCreditApplied)?[3,2]:[4,this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(u))];case 1:_.sent(),_.label=2;case 2:return[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 3:if(_.sent(),!this._digitalRiverCheckoutData)throw new m(h.MissingPaymentMethod);if(!Gn(i))return[3,10];_.label=4;case 4:return _.trys.push([4,6,,9]),[4,this._submitVaultedInstrument(o,i.instrumentId,this._digitalRiverCheckoutData.checkoutData.checkoutId,c,!1)];case 5:return[2,_.sent()];case 6:if(d=_.sent(),!this._isAuthenticateSourceAction(d))throw d;return[4,this._authenticateSource(d.body.provider_data)];case 7:return l=_.sent(),[4,this._submitVaultedInstrument(o,i.instrumentId,this._digitalRiverCheckoutData.checkoutData.checkoutId,c,l)];case 8:return[2,_.sent()];case 9:return[3,11];case 10:if(!this._loadSuccessResponse)throw new cu(["this._loadSuccessResponse"]);return p={methodId:n.methodId,paymentData:{formattedPayload:{credit_card_token:{token:JSON.stringify({checkoutId:this._digitalRiverCheckoutData.checkoutData.checkoutId,source:this._loadSuccessResponse,sessionId:this._digitalRiverCheckoutData.sessionId})},vault_payment_instrument:this._loadSuccessResponse.readyForStorage,set_as_default_stored_instrument:!1}}},[2,this._store.dispatch(this._paymentActionCreator.submitPayment(p))];case 11:return[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype._getDigitalRiverJs=function(){if(!this._digitalRiverJS)throw new Pn(bn.PaymentNotInitialized);return this._digitalRiverJS},e.prototype._getErrorMessage=function(e){return e.errors.map((function(e){return"code: "+e.code+" message: "+e.message})).join("\n")},e.prototype._onSuccessResponse=function(e){var t,n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c;return(0,s.__generator)(this,(function(u){switch(u.label){case 0:return r=new ae("Unable to initialize payment because success argument is not provided."),e&&this._submitFormEvent?(i=e.source,o=i.browserInfo,a=i.owner,this._loadSuccessResponse=o?{source:(0,s.__assign)({id:e.source.id,reusable:e.source.reusable},o),readyForStorage:e.readyForStorage}:{source:{id:e.source.id,reusable:e.source.reusable},readyForStorage:e.readyForStorage},a?(c={firstName:a.firstName,lastName:a.lastName,city:a.address.city,company:"",address1:a.address.line1,address2:"",postalCode:a.address.postalCode,countryCode:a.address.country,phone:a.phoneNumber,stateOrProvince:a.address.state,stateOrProvinceCode:a.address.country,customFields:[],email:a.email||a.email},this._loadSuccessResponse.source.owner=e.source.owner,[4,this._store.dispatch(this._billingAddressActionCreator.updateAddress(c))]):[3,2]):[3,3];case 1:u.sent(),u.label=2;case 2:return[2,this._submitFormEvent()];case 3:return[2,null===(n=(t=this._getDigitalRiverInitializeOptions()).onError)||void 0===n?void 0:n.call(t,r)]}}))}))},e.prototype._onReadyResponse=function(e){var t,n;e&&(null===(n=(t=this._getDigitalRiverInitializeOptions()).onRenderButton)||void 0===n||n.call(t))},e.prototype._getDigitalRiverInitializeOptions=function(){if(!this._digitalRiverInitializeOptions)throw new Pn(bn.PaymentNotInitialized);return this._digitalRiverInitializeOptions},e.prototype._loadWidget=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d,l,p,_,y=this;return(0,s.__generator)(this,(function(f){switch(f.label){case 0:return f.trys.push([0,3,,4]),[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e.methodId))];case 1:if(t=f.sent(),n=t.billingAddress.getBillingAddressOrThrow(),r=t.customer.getCustomerOrThrow(),i=t.config.getStoreConfigOrThrow().checkoutSettings.features,o=this._getDigitalRiverInitializeOptions().configuration.paymentMethodConfiguration,a=this._getDigitalRiverInitializeOptions(),c=a.containerId,u=a.configuration,!(d=t.paymentMethods.getPaymentMethodOrThrow(e.methodId).clientToken))throw new m(h.MissingPaymentMethod);if(this._digitalRiverCheckoutData=JSON.parse(d),!this._digitalRiverCheckoutData)throw new m(h.MissingPaymentMethod);return this._mountComplianceSection(this._digitalRiverCheckoutData.checkoutData.sellingEntity),this._submitFormEvent=this._getDigitalRiverInitializeOptions().onSubmitForm,l=i["PROJECT-4802.digital_river_paypal_support"]?[]:["payPal"],p={sessionId:this._digitalRiverCheckoutData.sessionId,options:(0,s.__assign)((0,s.__assign)({},u),{showSavePaymentAgreement:Boolean(r.email)&&u.showSavePaymentAgreement}),billingAddress:{firstName:n.firstName,lastName:n.lastName,email:n.email||r.email,phoneNumber:n.phone,address:{line1:n.address1,line2:n.address2,city:n.city,state:n.stateOrProvinceCode,postalCode:n.postalCode,country:n.countryCode}},paymentMethodConfiguration:(0,s.__assign)((0,s.__assign)({},o),{disabledPaymentMethods:l}),onSuccess:function(e){y._onSuccessResponse(e)},onReady:function(e){y._onReadyResponse(e)},onError:function(e){var t,n,r=new Error(y._getErrorMessage(e));null===(n=(t=y._getDigitalRiverInitializeOptions()).onError)||void 0===n||n.call(t,r)}},_=this,[4,this._getDigitalRiverJs().createDropin(p)];case 2:return _._digitalRiverDropComponent=f.sent(),this._digitalRiverDropComponent.mount(c),[2,t];case 3:throw f.sent(),new Hd("payment.digitalriver_checkout_error","digitalRiverCheckoutError");case 4:return[2]}}))}))},e.prototype._isAuthenticateSourceAction=function(e){return!!(e instanceof x&&(0,Z.some)(e.body.errors,{code:"additional_action_required"}))},e.prototype._authenticateSource=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:if(!this._digitalRiverCheckoutData)throw new ae("Unable to proceed because payload payment argument is not provided.");return[4,this._getDigitalRiverJs().authenticateSource({sessionId:this._digitalRiverCheckoutData.sessionId,sourceId:e.source_id,sourceClientSecret:e.source_client_secret})];case 1:if((t=n.sent()).status===Gd.failed)throw new Error("Source authentication failed, please try again");return[2,t.status===Gd.complete||t.status===Gd.authentication_not_required]}}))}))},e.prototype._submitVaultedInstrument=function(e,t,n,r,i){return(0,s.__awaiter)(this,void 0,void 0,(function(){var o;return(0,s.__generator)(this,(function(a){return o={methodId:e,paymentData:{formattedPayload:{bigpay_token:{token:t},credit_card_token:{token:JSON.stringify({checkoutId:n})},confirm:i,set_as_default_stored_instrument:r||null}}},[2,this._store.dispatch(this._paymentActionCreator.submitPayment(o))]}))}))},e.prototype._mountComplianceSection=function(e){var t=document.getElementById("compliance"),n={classes:{base:"DRElement"},compliance:{entity:e}};if(t)t.innerHTML="",this._getDigitalRiverJs().createElement("compliance",n).mount("compliance");else{var r=document.createElement("div");r.setAttribute("id","compliance"),r.style.cssText="min-height: 45px;",r.classList.add("layout"),document.body.appendChild(r),this._getDigitalRiverJs().createElement("compliance",n).mount("compliance")}},e}();const jd=Yd;var Wd=function(){function e(e,t,n){void 0===n&&(n=window),this._scriptLoader=e,this._stylesheetLoader=t,this._window=n}return e.prototype.load=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return[4,Promise.all([this._stylesheetLoader.loadStylesheet("https://js.digitalriverws.com/v1/css/DigitalRiver.css"),this._scriptLoader.loadScript("https://js.digitalriverws.com/v1/DigitalRiver.js")])];case 1:if(n.sent(),!this._window.DigitalRiver)throw new gi;return[2,Promise.resolve(new this._window.DigitalRiver(e,{locale:t}))]}}))}))},e}();const Kd=Wd;function Jd(){return{color_depth:screen.colorDepth||24,java_enabled:"function"==typeof navigator.javaEnabled&&navigator.javaEnabled(),language:navigator.language||navigator.userLanguage,screen_height:screen.height,screen_width:screen.width,time_zone_offset:(new Date).getTimezoneOffset().toString()}}var Zd=function(){function e(e,t,n,r,i,o,a,s,c){this._store=e,this._checkoutActionCreator=t,this._paymentMethodActionCreator=n,this._paymentStrategyActionCreator=r,this._paymentActionCreator=i,this._orderActionCreator=o,this._googlePayPaymentProcessor=a,this._googlePayProviderProcessor=s,this._braintreeSDKCreator=c}return e.prototype.initialize=function(e){var t;return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:return n=e.methodId,[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n))];case 1:return r=o.sent(),this._paymentMethod=r.paymentMethods.getPaymentMethodOrThrow(n),this._is3dsEnabled=r.paymentMethods.getPaymentMethodOrThrow(n).initializationData.isThreeDSecureEnabled,this._googlePayOptions=this._getGooglePayOptions(e),this._buttonClickEventHandler=this._handleButtonClickedEvent(n),this._paymentMethod.clientToken&&(null===(t=this._braintreeSDKCreator)||void 0===t||t.initialize(this._paymentMethod.clientToken)),[4,this._googlePayPaymentProcessor.initialize(n)];case 2:if(o.sent(),!this._googlePayOptions.walletButton)throw new ae("walletButton argument is missing");if(!(i=document.getElementById(this._googlePayOptions.walletButton)))throw new ae("Unable to create wallet, walletButton ID could not be found");return this._walletButton=i,this._walletButton.addEventListener("click",this._buttonClickEventHandler),[2,Promise.resolve(this._store.getState())]}}))}))},e.prototype.deinitialize=function(){var e=this;return this._walletButton&&this._buttonClickEventHandler&&this._walletButton.removeEventListener("click",this._buttonClickEventHandler),this._buttonClickEventHandler=void 0,this._walletButton=void 0,this._googlePayPaymentProcessor.deinitialize().then((function(){return e._store.getState()}))},e.prototype.execute=function(e,t){var n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d,l,p,_;return(0,s.__generator)(this,(function(y){switch(y.label){case 0:if(!this._googlePayOptions)throw new ae('Unable to initialize payment because "options.googlepay" argument is not provided.');if(!e.payment)throw new cu(["payment"]);return r=e.payment.methodId,""!==(null===(n=this._paymentMethod)||void 0===n?void 0:n.initializationData.nonce)&&(u=this._store.getState(),this._paymentMethod=u.paymentMethods.getPaymentMethodOrThrow(r)),[4,this._getPayment(r)];case 1:return(i=y.sent()).paymentData.nonce&&i.paymentData.cardInformation?[3,4]:(o=this._googlePayOptions,a=o.onError,c=o.onPaymentSelect,[4,this._displayWallet(r,c,a)]);case 2:return y.sent(),[4,this._getPayment(r,!0)];case 3:i=y.sent(),y.label=4;case 4:if(!i.paymentData.nonce)throw new m(h.MissingPayment);y.label=5;case 5:return y.trys.push([5,10,,11]),[4,this._store.dispatch(this._orderActionCreator.submitOrder({useStoreCredit:e.useStoreCredit},t))];case 6:return u=y.sent(),d=void 0,this._is3dsEnabled?(l=u.order.getOrderOrThrow,[4,this._verifyCard(r,l().orderAmount,i)]):[3,8];case 7:d=y.sent(),y.label=8;case 8:return p=(0,s.__assign)((0,s.__assign)({},i),{paymentData:(0,s.__assign)((0,s.__assign)({},i.paymentData),{nonce:(null==d?void 0:d.nonce)||i.paymentData.nonce})}),[4,this._store.dispatch(this._paymentActionCreator.submitPayment(p))];case 9:return[2,y.sent()];case 10:return _=y.sent(),[2,this._processAdditionalAction(_)];case 11:return[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype._processAdditionalAction=function(e){return this._googlePayProviderProcessor?this._googlePayProviderProcessor.processAdditionalAction(e):Promise.reject(e)},e.prototype._verifyCard=function(e,t,n){var r;return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:return e!==Wc.BRAINTREE_GOOGLE_PAY?[3,2]:(i=n.paymentData.nonce,[4,null===(r=this._braintreeSDKCreator)||void 0===r?void 0:r.get3DS()]);case 1:if(o=a.sent(),!i||!o)throw new Pn(bn.PaymentNotInitialized);return[2,this._braintreePresent3DSChallenge(o,t,i)];case 2:return[2]}}))}))},e.prototype._braintreePresent3DSChallenge=function(e,t,n){return new cn(e.verifyCard({amount:t,nonce:n,onLookupComplete:function(e,t){t()}})).promise},e.prototype._getGooglePayOptions=function(e){if(e.methodId===Wc.ADYENV2_GOOGLEPAY&&e.googlepayadyenv2){if(!this._googlePayProviderProcessor)throw new Pn(bn.PaymentNotInitialized);return this._googlePayProviderProcessor.initialize(e),e.googlepayadyenv2}if(e.methodId===Wc.ADYENV3_GOOGLEPAY&&e.googlepayadyenv3){if(!this._googlePayProviderProcessor)throw new Pn(bn.PaymentNotInitialized);return this._googlePayProviderProcessor.initialize(e),e.googlepayadyenv3}if(e.methodId===Wc.AUTHORIZENET_GOOGLE_PAY&&e.googlepayauthorizenet)return e.googlepayauthorizenet;if(e.methodId===Wc.BNZ_GOOGLEPAY&&e.googlepaybnz)return e.googlepaybnz;if(e.methodId===Wc.CHECKOUTCOM_GOOGLE_PAY&&e.googlepaycheckoutcom)return e.googlepaycheckoutcom;if(e.methodId===Wc.CYBERSOURCEV2_GOOGLE_PAY&&e.googlepaycybersourcev2)return e.googlepaycybersourcev2;if(e.methodId===Wc.ORBITAL_GOOGLE_PAY&&e.googlepayorbital)return e.googlepayorbital;if(e.methodId===Wc.BRAINTREE_GOOGLE_PAY&&e.googlepaybraintree)return e.googlepaybraintree;if(e.methodId===Wc.STRIPE_GOOGLE_PAY&&e.googlepaystripe)return e.googlepaystripe;if(e.methodId===Wc.STRIPE_UPE_GOOGLE_PAY&&e.googlepaystripeupe)return e.googlepaystripeupe;if(e.methodId===Wc.WORLDPAYACCESS_GOOGLE_PAY&&e.googlepayworldpayaccess)return e.googlepayworldpayaccess;throw new ae('Unable to initialize payment because "options.googlepay" argument is not provided.')},e.prototype._getPayment=function(e,t){return void 0===t&&(t=!1),(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a;return(0,s.__generator)(this,(function(c){switch(c.label){case 0:if(!e||!this._paymentMethod)throw new Pn(bn.PaymentNotInitialized);return n=this._paymentMethod.initializationData.card_information,(r=this._paymentMethod.initializationData.nonce)&&(this._paymentMethod=(0,s.__assign)((0,s.__assign)({},this._paymentMethod),{initializationData:{nonce:""}})),t?[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e))]:[3,2];case 1:i=c.sent(),this._paymentMethod=i.paymentMethods.getPaymentMethodOrThrow(e),r=this._paymentMethod.initializationData.nonce,c.label=2;case 2:return o={methodId:e},a={method:e,cardInformation:n},[4,this._encodeNonce(e,r)];case 3:return[2,(o.paymentData=(a.nonce=c.sent(),a),o)]}}))}))},e.prototype._encodeNonce=function(e,t){var n,r;return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(i){return e===Wc.ADYENV2_GOOGLEPAY?[2,JSON.stringify({type:null===(n=this._paymentMethod)||void 0===n?void 0:n.method,googlePayToken:t,browser_info:Jd()})]:e===Wc.ADYENV3_GOOGLEPAY?[2,JSON.stringify({type:null===(r=this._paymentMethod)||void 0===r?void 0:r.method,googlePayToken:t,browser_info:Jd()})]:[2,t]}))}))},e.prototype._paymentInstrumentSelected=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:if(!t)throw new Pn(bn.PaymentNotInitialized);return[4,this._googlePayPaymentProcessor.handleSuccess(e)];case 1:return r.sent(),n=this._store.getState(),this._paymentMethod=n.paymentMethods.getPaymentMethodOrThrow(t),[2,Promise.all([this._store.dispatch(this._checkoutActionCreator.loadCurrentCheckout()),this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(t))])]}}))}))},e.prototype._handleButtonClickedEvent=function(e){var t=this;return function(n){null==n||n.preventDefault();var r=t._store.getState().cart.getCartOrThrow(),i={transactionInfo:{currencyCode:r.currency.code,totalPrice:String(r.cartAmount)}};if(t._googlePayPaymentProcessor.updatePaymentDataRequest(i),!e||!t._googlePayOptions)throw new Pn(bn.PaymentNotInitialized);var o=t._googlePayOptions,a=o.onError,c=o.onPaymentSelect;return t._store.dispatch(t._paymentStrategyActionCreator.widgetInteraction((function(){return(0,s.__awaiter)(t,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){return[2,this._displayWallet(e,c,a)]}))}))}),{methodId:e}),{queueId:"widgetInteraction"})}},e.prototype._displayWallet=function(e,t,n){return void 0===t&&(t=Z.noop),void 0===n&&(n=Z.noop),(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:return o.trys.push([0,3,,4]),[4,this._googlePayPaymentProcessor.displayWallet()];case 1:return r=o.sent(),[4,this._paymentInstrumentSelected(r,e)];case 2:return o.sent(),[2,t()];case 3:if("CANCELED"===(i=o.sent()).statusCode)throw new Error("CANCELED");return n(i),[3,4];case 4:return[2]}}))}))},e}();const Qd=Zd;var Xd=function(){function e(e,t,n){this._store=e,this._paymentActionCreator=t,this._scriptLoader=n}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=this._store.getState(),n=t.paymentMethods.getPaymentMethodOrThrow(e.methodId),!(r=t.config.getStoreConfig()))throw new m(h.MissingCheckoutConfig);return i={key:"",value:""},n.initializationData.originKey?(i.key="originKey",i.value=n.initializationData.originKey):(i.key="clientKey",i.value=n.initializationData.clientKey),o=this,[4,this._scriptLoader.load((a={environment:n.config.testMode?"test":"live",locale:r.storeProfile.storeLanguage},a[i.key]=i.value,a.paymentMethodsResponse=n.initializationData.paymentMethodsResponse,a))];case 1:return o._adyenClient=s.sent(),[2]}}))}))},e.prototype.processAdditionalAction=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return e instanceof x&&(0,Z.some)(e.body.errors,{code:"additional_action_required"})?[4,this._handleAction(e.body.provider_data)]:[2,Promise.reject(e)];case 1:t=r.sent(),r.label=2;case 2:return r.trys.push([2,4,,5]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment(t))];case 3:return[2,r.sent()];case 4:return n=r.sent(),[2,this.processAdditionalAction(n)];case 5:return[2]}}))}))},e.prototype._handleAction=function(e){var t=this;return new Promise((function(n,r){var i=JSON.parse(e.action);t._getAdyenClient().createFromAction(i,{onAdditionalDetails:function(e){var t={methodId:i.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};n(t)},size:"05",onError:function(e){return r(e)}}).mount("body"),r(new uu)}))},e.prototype._getAdyenClient=function(){if(!this._adyenClient)throw new Pn(bn.PaymentNotInitialized);return this._adyenClient},e}();const $d=Xd;var el=function(){function e(e,t,n){this._store=e,this._paymentActionCreator=t,this._scriptLoader=n}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(t=this._store.getState(),n=t.paymentMethods.getPaymentMethodOrThrow(e.methodId),!(r=t.config.getStoreConfig()))throw new m(h.MissingCheckoutConfig);return i=this,[4,this._scriptLoader.load({environment:n.config.testMode?"test":"live",locale:r.storeProfile.storeLanguage,clientKey:n.initializationData.clientKey,paymentMethodsResponse:n.initializationData.paymentMethodsResponse})];case 1:return i._adyenClient=o.sent(),[2]}}))}))},e.prototype.processAdditionalAction=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return e instanceof x&&(0,Z.some)(e.body.errors,{code:"additional_action_required"})?[4,this._handleAction(e.body.provider_data)]:[2,Promise.reject(e)];case 1:t=r.sent(),r.label=2;case 2:return r.trys.push([2,4,,5]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment(t))];case 3:return[2,r.sent()];case 4:return n=r.sent(),[2,this.processAdditionalAction(n)];case 5:return[2]}}))}))},e.prototype._handleAction=function(e){var t=this;return new Promise((function(n,r){var i=JSON.parse(e.action);t._getAdyenClient().createFromAction(i,{onAdditionalDetails:function(e){var t={methodId:i.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};n(t)},challengeWindowSize:"05",onError:function(e){return r(e)}}).mount("body"),r(new uu)}))},e.prototype._getAdyenClient=function(){if(!this._adyenClient)throw new Pn(bn.PaymentNotInitialized);return this._adyenClient},e}();const tl=el,nl=function(){function e(){}return e.prototype.initialize=function(e){return Promise.resolve()},e.prototype.processAdditionalAction=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){return e instanceof x&&(0,Z.some)(e.body.errors,{code:"three_d_secure_required"})?(t=e.body.three_ds_result.acs_url,[2,this._performRedirect(t)]):[2,Promise.reject(e)]}))}))},e.prototype._performRedirect=function(e){return new Promise((function(){window.location.assign(e)}))},e}();var rl=function(){function e(e,t,n,r,i){this._store=e,this._orderActionCreator=t,this._paymentActionCreator=n,this._formPoster=r,this._paymentMethodActionCreator=i}return e.prototype.execute=function(e,t){var n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c;return(0,s.__generator)(this,(function(u){switch(u.label){case 0:if(r=e.payment,i=(0,s.__rest)(e,["payment"]),!(null==r?void 0:r.methodId))throw new cu(["payment.methodId"]);return[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(r.methodId,t))];case 1:if(o=u.sent(),a=o.paymentMethods.getPaymentMethodOrThrow(r.methodId),!(null===(n=a.initializationData)||void 0===n?void 0:n.processable))throw new Tc("payment.humm_not_processable_error","hummNotProcessableError");return[4,this._store.dispatch(this._orderActionCreator.submitOrder(i,t))];case 2:u.sent(),u.label=3;case 3:return u.trys.push([3,5,,6]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment({methodId:r.methodId}))];case 4:return[2,u.sent()];case 5:return c=u.sent(),this._isOffsiteRedirectResponse(c)?[2,this._handleOffsiteRedirectResponse(c)]:[2,Promise.reject(c)];case 6:return[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype.initialize=function(){return Promise.resolve(this._store.getState())},e.prototype.deinitialize=function(){return Promise.resolve(this._store.getState())},e.prototype._handleOffsiteRedirectResponse=function(e){var t=this,n=e.body.additional_action_required.data.redirect_url,r=e.body.provider_data;return new Promise((function(){t._formPoster.postForm(n,JSON.parse(r))}))},e.prototype._isOffsiteRedirectResponse=function(e){if("object"!=typeof e||null===e)return!1;var t=e;if(!t.body)return!1;var n=t.body;return"additional_action_required"===n.status&&!!n.additional_action_required&&"offsite_redirect"===n.additional_action_required.type&&"string"==typeof n.provider_data},e}();const il=rl;var ol=["AT","BE","CA","CH","CZ","DE","DK","ES","FI","FR","GB","GR","IE","IT","NL","NO","NZ","PL","PT","SE"],al=["AU"],sl=function(){function e(e,t,n,r,i){this._store=e,this._orderActionCreator=t,this._paymentMethodActionCreator=n,this._remoteCheckoutActionCreator=r,this._klarnaScriptLoader=i}return e.prototype.initialize=function(e){var t=this;return this._klarnaScriptLoader.load().then((function(e){t._klarnaCredit=e})).then((function(){return t._unsubscribe=t._store.subscribe((function(n){n.paymentStrategies.isInitialized({methodId:e.methodId,gatewayId:e.gatewayId})&&t._loadWidget(e)}),(function(e){var t=e.checkout.getCheckout();return t&&t.outstandingBalance}),(function(e){var t=e.checkout.getCheckout();return t&&t.coupons})),t._loadWidget(e)})).then((function(){return t._store.getState()}))},e.prototype.deinitialize=function(){return this._unsubscribe&&this._unsubscribe(),Promise.resolve(this._store.getState())},e.prototype.execute=function(e,t){var n=this;if(!e.payment)throw new ae('Unable to proceed because "payload.payment" argument is not provided.');var r=e.payment,i=(r.paymentData,(0,s.__rest)(r,["paymentData"]));return this._authorize().then((function(e){var t=e.authorization_token;return n._store.dispatch(n._remoteCheckoutActionCreator.initializePayment(i.methodId,{authorizationToken:t}))})).then((function(){return n._store.dispatch(n._orderActionCreator.submitOrder((0,s.__assign)((0,s.__assign)({},e),{payment:i,useStoreCredit:e.useStoreCredit}),t))}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype._loadWidget=function(e){var t=this;if(!e.klarna)throw new ae('Unable to load widget because "options.klarna" argument is not provided.');var n=e.methodId,r=e.klarna,i=r.container,o=r.onLoad;return this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n)).then((function(e){return new Promise((function(r){var a=e.paymentMethods.getPaymentMethod(n);if(!a)throw new m(h.MissingPaymentMethod);if(!t._klarnaCredit||!a.clientToken)throw new Pn(bn.PaymentNotInitialized);t._klarnaCredit.init({client_token:a.clientToken}),t._klarnaCredit.load({container:i},(function(e){o&&o(e),r(e)}))}))}))},e.prototype._getUpdateSessionData=function(e,t){if(!(0,Z.includes)((0,s.__spreadArrays)(ol,al),e.countryCode))return{};var n={billing_address:this._mapToKlarnaAddress(e,e.email)};return t&&(n.shipping_address=this._mapToKlarnaAddress(t,e.email)),n},e.prototype._needsStateCode=function(e){return(0,Z.includes)(al,e)},e.prototype._mapToKlarnaAddress=function(e,t){var n={street_address:e.address1,city:e.city,country:e.countryCode,given_name:e.firstName,family_name:e.lastName,postal_code:e.postalCode,region:this._needsStateCode(e.countryCode)?e.stateOrProvinceCode:e.stateOrProvince,email:t};return e.address2&&(n.street_address2=e.address2),e.phone&&(n.phone=e.phone),n},e.prototype._authorize=function(){var e=this;return new Promise((function(t,n){var r=e._store.getState().billingAddress.getBillingAddress(),i=e._store.getState().shippingAddress.getShippingAddress();if(!r)throw new m(h.MissingBillingAddress);if(!e._klarnaCredit)throw new Pn(bn.PaymentNotInitialized);var o=e._getUpdateSessionData(r,i);e._klarnaCredit.authorize(o,(function(e){return e.approved?t(e):e.show_form?n(new uu):void n(new Te)}))}))},e}();const cl=sl,ul=function(){function e(e){this._scriptLoader=e}return e.prototype.load=function(){return this._scriptLoader.loadScript("//credit.klarnacdn.net/lib/v1/api.js").then((function(){return window.Klarna.Credit}))},e}();var dl=function(){function e(e,t,n,r,i){this._store=e,this._orderActionCreator=t,this._remoteCheckoutActionCreator=n,this._klarnav2ScriptLoader=r,this._klarnav2TokenUpdater=i}return e.prototype.initialize=function(e){var t=this;return this._klarnav2ScriptLoader.load().then((function(e){t._klarnaPayments=e})).then((function(){return t._unsubscribe=t._store.subscribe((function(n){n.paymentStrategies.isInitialized({methodId:e.methodId,gatewayId:e.gatewayId})&&t._loadPaymentsWidget(e)}),(function(e){var t=e.checkout.getCheckout();return t&&t.outstandingBalance}),(function(e){var t=e.checkout.getCheckout();return t&&t.coupons})),t._loadPaymentsWidget(e)})).then((function(){return t._store.getState()}))},e.prototype.deinitialize=function(){return this._unsubscribe&&this._unsubscribe(),Promise.resolve(this._store.getState())},e.prototype.execute=function(e,t){var n=this;if(!e.payment)throw new ae('Unable to proceed because "payload.payment" argument is not provided.');var r=e.payment,i=(r.paymentData,(0,s.__rest)(r,["paymentData"])),o=i.gatewayId;if(!o)throw new ae('Unable to proceed because "payload.payment.gatewayId" argument is not provided.');return this._authorize(i.methodId).then((function(e){var t=e.authorization_token;return n._store.dispatch(n._remoteCheckoutActionCreator.initializePayment(o,{authorizationToken:t}))})).then((function(){return n._store.dispatch(n._orderActionCreator.submitOrder((0,s.__assign)((0,s.__assign)({},e),{payment:i,useStoreCredit:e.useStoreCredit}),t))}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype._loadPaymentsWidget=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!e.klarnav2)throw new ae('Unable to load widget because "options.klarnav2" argument is not provided.');if(t=e.methodId,n=e.gatewayId,r=e.klarnav2,i=r.container,o=r.onLoad,!n)throw new ae('Unable to proceed because "payload.payment.gatewayId" argument is not provided.');return a=this._store.getState(),c=a.cart.getCartOrThrow().id,u={params:c},[4,this._klarnav2TokenUpdater.updateClientToken(n,{params:u}).catch((function(){throw new m(h.MissingPaymentMethod)}))];case 1:return s.sent(),[2,new Promise((function(e){var n=a.paymentMethods.getPaymentMethodOrThrow(t);if(!d._klarnaPayments||!n.clientToken)throw new Pn(bn.PaymentNotInitialized);d._klarnaPayments.init({client_token:n.clientToken}),d._klarnaPayments.load({container:i,payment_method_category:n.id},(function(t){o&&o(t),e(t)}))}))]}}))}))},e.prototype._getUpdateSessionData=function(e,t){if(!(0,Z.includes)((0,s.__spreadArrays)(ol,al),e.countryCode))return{};var n={billing_address:this._mapToKlarnaAddress(e,e.email)};return t&&(n.shipping_address=this._mapToKlarnaAddress(t,e.email)),n},e.prototype._needsStateCode=function(e){return(0,Z.includes)(al,e)},e.prototype._mapToKlarnaAddress=function(e,t){var n={street_address:e.address1,city:e.city,country:e.countryCode,given_name:e.firstName,family_name:e.lastName,postal_code:e.postalCode,region:this._needsStateCode(e.countryCode)?e.stateOrProvinceCode:e.stateOrProvince,email:t};return e.address2&&(n.street_address2=e.address2),e.phone&&(n.phone=e.phone),n},e.prototype._authorize=function(e){var t=this;return new Promise((function(n,r){var i=t._store.getState().billingAddress.getBillingAddress(),o=t._store.getState().shippingAddress.getShippingAddress();if(!i)throw new m(h.MissingBillingAddress);var a=t._getUpdateSessionData(i,o);if(!t._klarnaPayments)throw new Pn(bn.PaymentNotInitialized);t._klarnaPayments.authorize({payment_method_category:e},a,(function(e){return e.approved?n(e):e.show_form?r(new uu):void r(new Te)}))}))},e}();const ll=dl,pl=function(){function e(e){this._scriptLoader=e}return e.prototype.load=function(){return this._scriptLoader.loadScript("https://x.klarnacdn.net/kp/lib/v1/api.js").then((function(){return window.Klarna.Payments}))},e}();var hl=function(){function e(e){this._requestSender=e}return e.prototype.updateClientToken=function(e,t){var n=void 0===t?{}:t,r=n.timeout,i=n.params,o="/api/storefront/payments/"+e;return this._requestSender.get(o,{timeout:r,headers:(0,s.__assign)({Accept:w.JsonV1,"X-API-INTERNAL":V},C),params:i})},e}();const ml=hl,_l=function(){function e(e,t,n,r,i){this._store=e,this._orderActionCreator=t,this._paymentActionCreator=n,this._masterpassScriptLoader=r,this._locale=i}return e.prototype.initialize=function(e){var t=this,n=e.methodId;if(this._paymentMethod=this._store.getState().paymentMethods.getPaymentMethod(n),!this._paymentMethod)throw new m(h.MissingPaymentMethod);var r={useMasterpassSrc:this._paymentMethod.initializationData.isMasterpassSrcEnabled,language:Jo(this._locale),testMode:this._paymentMethod.config.testMode,checkoutId:this._paymentMethod.initializationData.checkoutId};return this._masterpassScriptLoader.load(r).then((function(n){if(t._masterpassClient=n,!e.masterpass)throw new ae('Unable to initialize payment because "options.masterpass" argument is not provided.');var r=e.masterpass.walletButton&&document.getElementById(e.masterpass.walletButton);return r&&(t._walletButton=r,t._walletButton.addEventListener("click",t._handleWalletButtonClick)),t._store.getState()}))},e.prototype.deinitialize=function(){return this._paymentMethod=void 0,this._walletButton&&this._walletButton.removeEventListener("click",this._handleWalletButtonClick),this._walletButton=void 0,this._masterpassClient=void 0,Promise.resolve(this._store.getState())},e.prototype.execute=function(e,t){var n=this,r=e.payment,i={useStoreCredit:e.useStoreCredit};if(!r)throw new ae('Unable to submit payment because "payload.payment" argument is not provided.');if(!this._paymentMethod||!this._paymentMethod.initializationData||!this._paymentMethod.initializationData.gateway)throw new m(h.MissingPaymentMethod);var o=this._paymentMethod.initializationData.paymentData;if(!o)throw new ae('Unable to proceed because "paymentMethod.initializationData.paymentData" argument is not provided.');return this._store.dispatch(this._orderActionCreator.submitOrder(i,t)).then((function(){return n._store.dispatch(n._paymentActionCreator.submitPayment((0,s.__assign)((0,s.__assign)({},r),{paymentData:o})))}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype._createMasterpassPayload=function(){var e=this._store.getState(),t=e.checkout.getCheckout(),n=e.config.getStoreConfig();if(!t)throw new m(h.MissingCheckout);if(!n)throw new m(h.MissingCheckoutConfig);if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new m(h.MissingPaymentMethod);return{checkoutId:this._paymentMethod.initializationData.checkoutId,allowedCardTypes:this._paymentMethod.initializationData.allowedCardTypes,amount:t.subtotal.toFixed(2),currency:n.currency.code,cartId:t.cart.id,callbackUrl:Wo("checkout")}},e.prototype._handleWalletButtonClick=function(e){if(e.preventDefault(),this._masterpassClient){var t=this._createMasterpassPayload();this._masterpassClient.checkout(t)}},(0,s.__decorate)([yn],e.prototype,"_handleWalletButtonClick",null),e}();var yl;!function(e){e.creditcard="credit_card"}(yl||(yl={}));var fl=["klarnapaylater","klarnasliceit"],gl=function(){function e(e,t,n,r,i){this._hostedFormFactory=e,this._store=t,this._mollieScriptLoader=n,this._orderActionCreator=r,this._paymentActionCreator=i}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d,l,p,_,y,f,g=this;return(0,s.__generator)(this,(function(v){switch(v.label){case 0:if(t=e.mollie,n=e.methodId,r=e.gatewayId,!t)throw new ae('Unable to initialize payment because "options.mollie" argument is not provided.');if(!n||!r)throw new ae('Unable to initialize payment because "methodId" and/or "gatewayId" argument is not provided.');if(i=document.querySelectorAll(".mollie-components-controller"),(0,Z.each)(i,(function(e){return e.remove()})),o=this._store.getState(),!(a=o.config.getStoreConfig()))throw new m(h.MissingCheckoutConfig);if(this._initializeOptions=t,c=o.paymentMethods,u=c.getPaymentMethodOrThrow(n,r),d=u.config,l=d.merchantId,p=d.testMode,_=u.initializationData.locale,this._locale=_,!l)throw new ae('Unable to initialize payment because "merchantId" argument is not provided.');return this.isCreditCard(n)&&t.form&&this.shouldShowTSVHostedForm(n,r)?(y=this,[4,this._mountCardVerificationfields(t.form)]):[3,2];case 1:return y._hostedForm=v.sent(),[3,4];case 2:return this.isCreditCard(n)?(f=this,[4,this._loadMollieJs(l,a.storeProfile.storeLanguage,p)]):[3,4];case 3:f._mollieClient=v.sent(),this._mountElements(),v.label=4;case 4:return this._unsubscribe=this._store.subscribe((function(i){return(0,s.__awaiter)(g,void 0,void 0,(function(){var o;return(0,s.__generator)(this,(function(a){return i.paymentStrategies.isInitialized({methodId:e.methodId,gatewayId:e.gatewayId})&&((o=document.getElementById(r+"-"+n+"-paragraph"))&&o.remove(),t.disableButton(!1),this._loadPaymentMethodsAllowed(t,n,r,i)),[2]}))}))}),(function(e){var t=e.checkout.getCheckout();return t&&t.outstandingBalance}),(function(e){var t=e.checkout.getCheckout();return t&&t.coupons})),this._loadPaymentMethodsAllowed(t,n,r,o),[2,Promise.resolve(this._store.getState())]}}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),i=null==n?void 0:n.paymentData,!n||!n.gatewayId||!i)throw new cu(["payment","gatewayId","paymentData"]);a.label=1;case 1:return a.trys.push([1,8,,9]),[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 2:return a.sent(),Gn(i)?[4,this.executeWithVaulted(n)]:[3,4];case 3:return[2,a.sent()];case 4:return this.isCreditCard(n.methodId)?[4,this.executeWithCC(n)]:[3,6];case 5:return[2,a.sent()];case 6:return[4,this.executeWithAPM(n)];case 7:return[2,a.sent()];case 8:return o=a.sent(),[2,this._processAdditionalAction(o)];case 9:return[2]}}))}))},e.prototype.finalize=function(){return Promise.resolve(this._store.getState())},e.prototype.deinitialize=function(e){if(this._unsubscribe&&this._unsubscribe(),this._hostedForm&&this._hostedForm.detach(),e&&e.methodId&&e.gatewayId&&!this._hostedForm){var 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(this._store.getState())},e.prototype.executeWithCC=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c;return(0,s.__generator)(this,(function(u){switch(u.label){case 0:return t=e.paymentData,n=t.shouldSaveInstrument,r=t.shouldSetAsDefaultInstrument,[4,this._getMollieClient().createToken()];case 1:return i=u.sent(),o=i.token,(a=i.error)?[2,Promise.reject(a)]:(c={credit_card_token:{token:o},vault_payment_instrument:n,set_as_default_stored_instrument:r,browser_info:Jd(),shopper_locale:this._getShopperLocale()},[2,this._store.dispatch(this._paymentActionCreator.submitPayment((0,s.__assign)((0,s.__assign)({},e),{paymentData:{formattedPayload:c}})))])}}))}))},e.prototype.executeWithVaulted=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:if(!this._isHostedPaymentFormEnabled(e.methodId,e.gatewayId))return[3,3];if(!(t=this._hostedForm))throw new Pn(bn.PaymentNotInitialized);return[4,t.validate()];case 1:return n.sent(),[4,t.submit(e)];case 2:return n.sent(),[2,this._store.dispatch(this._orderActionCreator.loadCurrentOrder())];case 3:return[2,this._store.dispatch(this._paymentActionCreator.submitPayment(e))]}}))}))},e.prototype.executeWithAPM=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){return t=e.paymentData,n=t&&"issuer"in t?t.issuer:"",[2,this._store.dispatch(this._paymentActionCreator.submitPayment((0,s.__assign)((0,s.__assign)({},e),{paymentData:(0,s.__assign)((0,s.__assign)({},t),{formattedPayload:{issuer:n,shopper_locale:this._getShopperLocale()}})})))]}))}))},e.prototype.isCreditCard=function(e){return e===yl.creditcard},e.prototype.shouldShowTSVHostedForm=function(e,t){return this._isHostedPaymentFormEnabled(e,t)&&this._isHostedFieldAvailable()},e.prototype._mountCardVerificationfields=function(e){var t=this;return new Promise((function(n,r){return(0,s.__awaiter)(t,void 0,void 0,(function(){var t,i,o,a,c;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(s.trys.push([0,2,,3]),t=this._store.getState().config,!(i=null===(c=t.getStoreConfig())||void 0===c?void 0:c.paymentSettings.bigpayBaseUrl))throw new m(h.MissingCheckoutConfig);return[4,(o=this._hostedFormFactory.create(i,e)).attach()];case 1:return s.sent(),n(o),[3,3];case 2:return a=s.sent(),r(a),[3,3];case 3:return[2]}}))}))}))},e.prototype._isHostedPaymentFormEnabled=function(e,t){return!0===(0,this._store.getState().paymentMethods.getPaymentMethodOrThrow)(e,t).config.isHostedFormEnabled},e.prototype._isHostedFieldAvailable=function(){var e;return!!(null===(e=this._getInitializeOptions().form)||void 0===e?void 0:e.fields)},e.prototype._processAdditionalAction=function(e){if(!(e instanceof x&&(0,Z.some)(e.body.errors,{code:"additional_action_required"})))return Promise.reject(e);var t=e.body.additional_action_required.data.redirect_url;return new Promise((function(){return window.location.replace(t)}))},e.prototype._getInitializeOptions=function(){if(!this._initializeOptions)throw new Pn(bn.PaymentNotInitialized);return this._initializeOptions},e.prototype._loadMollieJs=function(e,t,n){return void 0===n&&(n=!1),this._mollieClient?Promise.resolve(this._mollieClient):this._mollieScriptLoader.load(e,t,n)},e.prototype._getMollieClient=function(){if(!this._mollieClient)throw new Pn(bn.PaymentNotInitialized);return this._mollieClient},e.prototype._getShopperLocale=function(){if(!this._locale)throw new Pn(bn.PaymentNotInitialized);return this._locale},e.prototype._mountElements=function(){var e,t=this,n=this._getInitializeOptions(),r=n.containerId,i=n.cardNumberId,o=n.cardCvcId,a=n.cardExpiryId,s=n.cardHolderId,c=n.styles;r&&(e=document.getElementById(r)),setTimeout((function(){if(!r||"none"!==(null==e?void 0:e.style.display)){var n=t._getMollieClient();t._cardHolderElement=n.createComponent("cardHolder",{styles:c}),t._cardHolderElement.mount("#"+s),t._cardNumberElement=n.createComponent("cardNumber",{styles:c}),t._cardNumberElement.mount("#"+i),t._verificationCodeElement=n.createComponent("verificationCode",{styles:c}),t._verificationCodeElement.mount("#"+o),t._expiryDateElement=n.createComponent("expiryDate",{styles:c}),t._expiryDateElement.mount("#"+a)}}),0)},e.prototype._loadPaymentMethodsAllowed=function(e,t,n,r){if(fl.includes(t)){var i=r.cart.getCartOrThrow().lineItems.digitalItems;if(i&&i.length>0){var o=this._getInitializeOptions().containerId;if(o){var a=document.getElementById(o);if(a){var s=document.createElement("p");s.setAttribute("id",n+"-"+t+"-paragraph"),e.unsupportedMethodMessage&&(s.innerText=e.unsupportedMethodMessage,a.appendChild(s),e.disableButton(!0))}}}}},e}();const vl=gl;var wl=function(){function e(e,t){void 0===t&&(t=window),this._scriptLoader=e,this._window=t}return e.prototype._isMollieWindow=function(e){return!!e.Mollie},e.prototype.load=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._scriptLoader.loadScript("https://js.mollie.com/v1/mollie.js")];case 1:if(r.sent(),!this._isMollieWindow(this._window))throw new gi;return[2,this._window.Mollie(e,{locale:t,testmode:n})]}}))}))},e}();const Cl=wl;var Sl="moneris-payment-iframe",Il=function(){function e(e,t,n,r,i){this._hostedFormFactory=e,this._store=t,this._orderActionCreator=n,this._paymentActionCreator=r,this._storeCreditActionCreator=i}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=this._store.getState(),n=e.moneris,!(r=e.methodId))throw new ae('Unable to initialize payment because "methodId" argument is not provided.');if(!n)throw new ae('Unable to initialize payment because "options.moneris" argument is not provided.');if(this._initializeOptions=n,i=t.paymentMethods.getPaymentMethodOrThrow(r),o=i.config,!(null==(a=i.initializationData)?void 0:a.profileId))throw new m(h.MissingPaymentMethod);return n.form&&this._shouldShowTSVHostedForm(r)?(c=this,[4,this._mountCardVerificationfields(n.form)]):[3,2];case 1:c._hostedForm=s.sent(),s.label=2;case 2:return this._iframe||(this._iframe=this._createIframe(n.containerId,a,!!o.testMode)),[2,Promise.resolve(this._store.getState())]}}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!n)throw new cu(["payment"]);return void 0===(i=this._store.getState().checkout.getCheckoutOrThrow().isStoreCreditApplied)?[3,2]:[4,this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(i))];case 1:o.sent(),o.label=2;case 2:return[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 3:return o.sent(),n.paymentData&&Gn(n.paymentData)?[2,this._executeWithVaulted(n)]:[2,this._executeWithCC(n)]}}))}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype.deinitialize=function(){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(this._store.getState())},e.prototype._executeWithCC=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return t=this._store.getState().paymentMethods.getPaymentMethodOrThrow,n=t(e.methodId),r=n.config.testMode,i=e.paymentData||{},o=Vu(i)?i:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1},a=o.shouldSaveInstrument,c=o.shouldSetAsDefaultInstrument,[4,new Promise((function(e,t){if(!d._iframe)throw new Pn(bn.PaymentNotInitialized);var n=d._iframe.contentWindow;null==n||n.postMessage("tokenize",d._monerisURL(!!r)),d._windowEventListener=function(n){if("string"==typeof n.data)try{e(d._handleMonerisResponse(n))}catch(e){t(e)}},window.addEventListener("message",d._windowEventListener)}))];case 1:return void 0!==(u=s.sent())?[2,this._store.dispatch(this._paymentActionCreator.submitPayment({methodId:e.methodId,paymentData:{nonce:u,shouldSaveInstrument:a,shouldSetAsDefaultInstrument:c}}))]:[2,this._store.getState()]}}))}))},e.prototype._executeWithVaulted=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:if(!this._hostedForm)return[3,3];if(!(t=this._hostedForm))throw new Pn(bn.PaymentNotInitialized);return[4,t.validate()];case 1:return n.sent(),[4,t.submit(e)];case 2:return n.sent(),[2,this._store.dispatch(this._orderActionCreator.loadCurrentOrder())];case 3:return[2,this._store.dispatch(this._paymentActionCreator.submitPayment(e))]}}))}))},e.prototype._shouldShowTSVHostedForm=function(e){return this._isHostedPaymentFormEnabled(e)&&this._isHostedFieldAvailable()},e.prototype._isHostedPaymentFormEnabled=function(e){var t=(0,this._store.getState().paymentMethods.getPaymentMethodOrThrow)(e);return Boolean(t.config.isHostedFormEnabled)},e.prototype._isHostedFieldAvailable=function(){var e,t=this._getInitializeOptions(),n=(0,Z.omitBy)(null===(e=t.form)||void 0===e?void 0:e.fields,Z.isEmpty);return!(0,Z.isEmpty)(n)},e.prototype._getInitializeOptions=function(){if(!this._initializeOptions)throw new Pn(bn.PaymentNotInitialized);return this._initializeOptions},e.prototype._mountCardVerificationfields=function(e){var t;return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(n=this._store.getState().config,!(r=null===(t=n.getStoreConfig())||void 0===t?void 0:t.paymentSettings.bigpayBaseUrl))throw new m(h.MissingCheckoutConfig);return[4,(i=this._hostedFormFactory.create(r,e)).attach()];case 1:return o.sent(),[2,i]}}))}))},e.prototype._createIframe=function(e,t,n,r){var i=document.getElementById(e);if(!i)throw new ae("Unable to create iframe without valid container ID.");var o=document.createElement("iframe"),a={id:t.profileId,pmmsg:!0,display_labels:1,enable_exp:1,enable_cvd:1,css_body:(null==r?void 0:r.cssBody)||"font-family: Arial, Helvetica,sans-serif;background: transparent;",css_textbox:(null==r?void 0:r.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==r?void 0:r.cssTextboxCardNumber)||"width: 240px;",css_textbox_exp:(null==r?void 0:r.cssTextboxExpiryDate)||"margin-bottom: 0;width: calc(30% - 12px);",css_textbox_cvd:(null==r?void 0:r.cssTextboxCVV)||"margin-bottom: 0;width: calc(30% - 12px);",css_input_label:(null==r?void 0:r.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=(0,Z.map)(a,(function(e,t){return t+"="+e})).join("&");return o.width="100%",o.height="100%",o.name=Sl,o.id=Sl,o.style.border="none",o.src=this._monerisURL(n)+"?"+s,i.appendChild(o),o},e.prototype._handleMonerisResponse=function(e){var t=JSON.parse(e.data);if("001"!==t.responseCode[0])throw new Error(t.errorMessage);return t.dataKey},e.prototype._monerisURL=function(e){return"https://"+(e?"esqa":"www3")+".moneris.com/HPPtoken/index.php"},e}();const bl=Il;var Pl,El;function Al(e){var t;return!!(null===(t=e.initializationData)||void 0===t?void 0:t.widgetConfig)}!function(e){e.FORM_POST="FormPost",e.WAIT_FOR_CUSTOMER="WaitForCustomer"}(Pl||(Pl={})),function(e){e.InvalidCart="invalid_cart"}(El||(El={}));const Ol=function(e){function t(t,n){var r=e.call(this,function(e,t){return e===El.InvalidCart?"Cart price is different to "+t+" plan amount.":"There was an error while processing your payment. Please try again or contact us."}(t,n))||this;return r.name="OpyError",r.type="opy_error",r.subtype=t,r}return(0,s.__extends)(t,e),t}(p);var kl=function(){function e(e,t,n,r,i,o){this._store=e,this._orderActionCreator=t,this._paymentMethodActionCreator=n,this._storefrontPaymentRequestSender=r,this._paymentActionCreator=i,this._scriptLoader=o}return e.prototype.initialize=function(e){var t;return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:return(null===(t=null==e?void 0:e.opy)||void 0===t?void 0:t.containerId)?(n=e.methodId,r=e.opy.containerId,(i=this._store.getState().paymentMethods.getPaymentMethod(n))&&Al(i)?(o=i.initializationData.widgetConfig,[4,this._installWidget(r,o)]):[3,2]):[3,2];case 1:a.sent(),a.label=2;case 2:return[2,Promise.resolve(this._store.getState())]}}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d,l,p,_,y,f,g;return(0,s.__generator)(this,(function(v){switch(v.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!n)throw new cu(["payment"]);return i=n.methodId,[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(i,t))];case 1:if(o=v.sent().paymentMethods.getPaymentMethodOrThrow,!Al(a=o(i)))throw new m(h.MissingPaymentMethod);if(c=a.clientToken,!(u=a.initializationData.nextAction))throw d=a.config.displayName,l=void 0===d?"Openpay":d,new Ol(El.InvalidCart,l);if(!c)throw new m(h.MissingPaymentToken);return[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 2:return v.sent(),[4,this._storefrontPaymentRequestSender.saveExternalId(i,c)];case 3:v.sent(),v.label=4;case 4:return v.trys.push([4,6,,7]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment({methodId:i,paymentData:{nonce:c}}))];case 5:return[2,v.sent()];case 6:if((p=v.sent())instanceof x&&"additional_action_required"===p.body.status){if(u.type===Pl.FORM_POST)return _=u.formPost,y=_.formPostUrl,f=_.formFields,g=new URL(y.replace(/\/$/,"")),f.forEach((function(e){var t=e.fieldName,n=e.fieldValue;g.searchParams.append(t,n)})),[2,new Promise((function(){return window.location.assign(decodeURI(g.href))}))];throw new bo("Unsupported action type: "+u.type)}throw p;case 7:return[2]}}))}))},e.prototype.finalize=function(e){return Promise.reject(new Hc)},e.prototype.deinitialize=function(e){return Promise.resolve(this._store.getState())},e.prototype._installWidget=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:if(!(n=document.getElementById(e)))return[3,5];r.label=1;case 1:return r.trys.push([1,3,,4]),[4,this._scriptLoader.loadOpyWidget(t.region)];case 2:return r.sent().Config(t),[3,4];case 3:return r.sent(),[2];case 4:n.appendChild(document.createElement("opy-learn-more-button")),r.label=5;case 5:return[2]}}))}))},e}();const Tl=kl;var Ml;!function(e){e.AU="AU",e.UK="UK",e.US="US"}(Ml||(Ml={}));var Dl="https://widgets.openpay.com.au/lib/openpay-widgets.min.js",Rl={AU:Dl,UK:Dl,US:"https://widgets.opy.com/lib/openpay-widgets.min.js"},zl=function(){function e(e,t){void 0===t&&(t=window),this._scriptLoader=e,this._window=t}return e.prototype.loadOpyWidget=function(e){return void 0===e&&(e=Ml.AU),(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this._scriptLoader.loadScript(Rl[e])];case 1:if(t.sent(),!this._window.OpenpayWidgets)throw new gi;return[2,this._window.OpenpayWidgets]}}))}))},e}();const Nl=zl;var Ll=function(e){function t(t,n,r,i,o){var a=e.call(this,t,n,r,i)||this;return a._threeDSecureFlow=o,a}return(0,s.__extends)(t,e),t.prototype.initialize=function(t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return[4,e.prototype.initialize.call(this,t)];case 1:return i.sent(),n=this._store.getState().paymentMethods.getPaymentMethodOrThrow,(r=n(t.methodId)).config.is3dsEnabled?[4,this._threeDSecureFlow.prepare(r)]:[3,3];case 2:i.sent(),i.label=3;case 3:return[2,this._store.getState()]}}))}))},t.prototype.execute=function(t,n){var r=t.payment,i=(void 0===r?{}:r).methodId,o=void 0===i?"":i,a=this._store.getState(),c=a.payment.getPaymentStatus,u=a.paymentMethods.getPaymentMethodOrThrow;return c()===Iu?this._store.dispatch(this._orderActionCreator.submitOrder((0,s.__assign)((0,s.__assign)({},t),{payment:{methodId:o}}),n)):u(o).config.is3dsEnabled?this._threeDSecureFlow.start(e.prototype.execute.bind(this),t,n,this._hostedForm):e.prototype.execute.call(this,t,n)},t}(wu);const Fl=Ll,Bl=function(){function e(e,t,n,r){void 0===r&&(r=window),this._store=e,this._orderActionCreator=t,this._scriptLoader=n,this._window=r,this._useRedirectFlow=!1}return e.prototype.initialize=function(e){var t=this,n=this._store.getState();return this._paymentMethod=n.paymentMethods.getPaymentMethod(e.methodId),this._useRedirectFlow=!0===(e.paypalexpress&&e.paypalexpress.useRedirectFlow),this._isInContextEnabled()?this._scriptLoader.loadPaypal().then((function(e){if(t._paypalSdk=e,!t._paymentMethod||!t._paymentMethod.config.merchantId)throw new m(h.MissingPaymentMethod);t._paypalSdk.checkout.setup(t._paymentMethod.config.merchantId,{button:"paypal-button",environment:t._paymentMethod.config.testMode?"sandbox":"production"})})).then((function(){return t._store.getState()})):Promise.resolve(this._store.getState())},e.prototype.deinitialize=function(){return this._isInContextEnabled()&&this._paypalSdk&&(this._paypalSdk.checkout.closeFlow(),this._paypalSdk=void 0),Promise.resolve(this._store.getState())},e.prototype.execute=function(e,t){var n=this,r=this._paypalSdk;if(this._isAcknowledgedOrFinalized())return this._store.dispatch(this._orderActionCreator.submitOrder(e,t));if(!this._isInContextEnabled()||this._useRedirectFlow)return this._store.dispatch(this._orderActionCreator.submitOrder(e,t)).then((function(e){var t=e.payment.getPaymentRedirectUrl();return t&&(n._window.top.location.href=t),new Promise(Z.noop)}));if(!r)throw new Pn(bn.PaymentNotInitialized);return r.checkout.initXO(),this._store.dispatch(this._orderActionCreator.submitOrder(e,t)).then((function(e){var t=e.payment.getPaymentRedirectUrl();return t&&r.checkout.startFlow(t),new Promise(Z.noop)})).catch((function(e){return r.checkout.closeFlow(),Promise.reject(e)}))},e.prototype.finalize=function(e){var t=this._store.getState().order.getOrder();return t&&this._isAcknowledgedOrFinalized()?this._store.dispatch(this._orderActionCreator.finalizeOrder(t.orderId,e)):Promise.reject(new Hc)},e.prototype._isAcknowledgedOrFinalized=function(){var e=this._store.getState();return e.payment.getPaymentStatus()===Iu||e.payment.getPaymentStatus()===bu},e.prototype._isInContextEnabled=function(){return!(!this._paymentMethod||!this._paymentMethod.config.merchantId)},e}();var Ul=function(){function e(e){this._scriptLoader=e,this._window=window}return e.prototype.loadPaypal=function(e){return void 0===e&&(e=""),(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return t="//www.paypalobjects.com/api/checkout.min.js",n={async:!0,attributes:{"data-merchant-id":e}},e?[4,this._scriptLoader.loadScript(t,n)]:[3,2];case 1:return r.sent(),[3,4];case 2:return[4,this._scriptLoader.loadScript(t)];case 3:r.sent(),r.label=4;case 4:if(!this._window.paypal)throw new gi;return[2,this._window.paypal]}}))}))},e}();const xl=Ul,ql=require("query-string");var Vl,Gl="redirecting",Hl=function(){function e(){this._isRedirecting=this.currentUrlHasRedirectingParam()}return e.prototype.isRedirecting=function(){return this._isRedirecting},e.prototype.setRedirecting=function(e){e?this.setRedirectingParamOnUrl():this.removeRedirectingParamFromUrl(),this._isRedirecting=e},e.prototype.currentUrlHasRedirectingParam=function(){return Gl in this.getCurrentUrl().query},e.prototype.getCurrentUrl=function(){return(0,ql.parseUrl)(window.location.href)},e.prototype.replaceCurrentUrl=function(e){window.history.replaceState(null,"",e)},e.prototype.setRedirectingParamOnUrl=function(){var e;if(!this.currentUrlHasRedirectingParam()){var t=this.getCurrentUrl(),n=(0,s.__assign)((0,s.__assign)({},t),{query:(0,s.__assign)((0,s.__assign)({},t.query),(e={},e[Gl]="true",e))});this.replaceCurrentUrl((0,ql.stringifyUrl)(n))}},e.prototype.removeRedirectingParamFromUrl=function(){this.currentUrlHasRedirectingParam()&&this.replaceCurrentUrl((0,ql.exclude)(window.location.href,[Gl]))},e}(),Yl=(0,Z.overSome)([function(e){return"continue"===(0,Z.get)(e,"type")&&"redirect"===(0,Z.get)(e,"code")&&(t=(0,Z.get)(e,"parameters"),n=(0,Z.get)(t,"form_fields"),(0,Z.isString)((0,Z.get)(t,"url"))&&((0,Z.isUndefined)(n)||(0,Z.isObject)(n)));var t,n},function(e){return"continue"===(0,Z.get)(e,"type")&&"resubmit_with_human_verification"===(0,Z.get)(e,"code")&&(t=(0,Z.get)(e,"parameters"),n=(0,Z.get)(t,"available_methods"),(0,Z.isArray)(n));var t,n}]),jl=function(){function e(e,t){this._formPoster=e,this._humanVerificationHandler=t}return e.prototype.handle=function(e,t){switch(e.code){case"redirect":return function(e,t){var n=e.url,r=e.form_fields,i=new Hl;return i.isRedirecting()?(i.setRedirecting(!1),Promise.reject(new uu)):(i.setRedirecting(!0),r?t.postForm(n,r):window.location.assign(n),new Promise(Z.noop))}(e.parameters,this._formPoster);case"resubmit_with_human_verification":return function(e,t,n){var r=e.available_methods;return(0,s.__awaiter)(void 0,void 0,void 0,(function(){var e,i,o,a;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!n)throw new Error("PPSDK human verification callback function is missing.");if(!t)throw new Error("PPSDK human verification handler is missing.");if(0===r.length)throw Error("Human verification method is missing.");return e=r[0],i=e.id,o=e.parameters,[4,t.handle(i,o.key)];case 1:return a=s.sent(),[2,n(a)]}}))}))}(e.parameters,this._humanVerificationHandler,null==t?void 0:t.humanVerification)}},e}(),Wl=function(){function e(e){this._continueHandler=e}return e.prototype.handle=function(e,t){var n=e.body;return function(e){return"success"===(0,Z.get)(e,"type")}(n)?Promise.resolve():function(e){return Yl(e)}(n)?this._continueHandler.handle(n,null==t?void 0:t.continue):function(e){return"failure"===(0,Z.get)(e.body,"type")&&(0,Z.isString)((0,Z.get)(e.body,"code"))}(e)?function(e){return Promise.reject(new x((t=e,(0,s.__assign)((0,s.__assign)({},t),{body:{errors:[{code:t.body.code}]}}))));var t}(e):(function(e){(0,Z.get)(e.body,"type")}(e),function(e){return Promise.reject(new x(e))}(e))},e}(),Kl=function(e,t){return new Wl(new jl(e,t))},Jl="completed-payments",Zl=function(){function e(e){this._browserStorage=e}return e.prototype.isCompleted=function(e){return this.getCompletedPayments().indexOf(e)>=0},e.prototype.setCompleted=function(e){var t=this.getCompletedPayments();t.push(e),this.setCompletedPayments(t)},e.prototype.getCompletedPayments=function(){return this._browserStorage.getItem(Jl)||[]},e.prototype.setCompletedPayments=function(e){this._browserStorage.setItem(Jl,e)},e}(),Ql=function(){function e(e,t,n,r,i){this._store=e,this._orderActionCreator=t,this._subStrategyRegistry=n,this._paymentResumer=r,this._completedPayments=new Zl(i)}return e.prototype.execute=function(e,t){var n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u;return(0,s.__generator)(this,(function(d){switch(d.label){case 0:if(r=this._store.getState().config.getStoreConfigOrThrow().paymentSettings.bigpayBaseUrl,!(null==t?void 0:t.methodId))throw new ae('Unable to submit payment because "options.methodId" argument is not provided.');if(i=t.methodId,o=e.payment,a=(0,s.__rest)(e,["payment"]),!(c=this._subStrategy))throw new Pn(bn.PaymentNotInitialized);return[4,this._store.dispatch(this._orderActionCreator.submitOrder(a,t))];case 1:if(d.sent(),!(u=null===(n=this._store.getState().order.getOrderMeta())||void 0===n?void 0:n.token))throw new m(h.MissingOrder);return[4,c.execute({methodId:i,payment:o,bigpayBaseUrl:r,token:u})];case 2:return d.sent(),[2,this._store.getState()]}}))}))},e.prototype.finalize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o=this;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:if((t=this._store.getState().order.getOrderOrThrow()).isComplete)return[2,this._store.getState()];if(n=this._store.getState().config.getStoreConfigOrThrow().paymentSettings.bigpayBaseUrl,!(null==e?void 0:e.methodId))throw new ae('Unable to submit payment because "options.methodId" argument is not provided.');if(!(r=this._store.getState().order.getPaymentId(e.methodId))||!t||this._completedPayments.isCompleted(r))throw new Hc;return i=t.orderId,[4,this._paymentResumer.resume({paymentId:r,bigpayBaseUrl:n,orderId:i}).catch((function(e){throw o._completedPayments.setCompleted(r),e}))];case 1:return a.sent(),[2,this._store.getState()]}}))}))},e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:if(!(null==e?void 0:e.methodId))throw new ae('Unable to submit payment because "options.methodId" argument is not provided.');if(!(t=function(e,t){var n=e.getState().paymentMethods.getPaymentMethod(t);if(n&&Xc(n))return n}(this._store,e.methodId)))throw new Pn(bn.PaymentNotInitialized);if(this._subStrategy=this._subStrategyRegistry.getByMethod(t),!this._subStrategy)throw new Pn(bn.PaymentNotInitialized);return[4,this._subStrategy.initialize(e)];case 1:return n.sent(),[2,this._store.getState()]}}))}))},e.prototype.deinitialize=function(e){var t;return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){return null===(t=this._subStrategy)||void 0===t||t.deinitialize(),[2,this._store.getState()]}))}))},e}();!function(e){e.CARD="card_ui",e.NONE="none",e.UNSUPPORTED="unsupported"}(Vl||(Vl={}));var Xl=(0,Z.cond)([[function(e){return"card_ui"===e.type},(0,Z.constant)(Vl.CARD)],[function(e){return"none"===e.type},(0,Z.constant)(Vl.NONE)],[Z.stubTrue,(0,Z.constant)(Vl.UNSUPPORTED)]]),$l=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return(0,s.__extends)(t,e),t.prototype.getByMethod=function(e){var t=Xl(e.initializationStrategy);return this.get(t)},t}(ce),ep=function(){function e(e,t,n,r){this._store=e,this._orderActionCreator=t,this._hostedFormFactory=n,this._ppsdkStepHandler=r}return e.prototype.execute=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c=this;return(0,s.__generator)(this,(function(u){switch(u.label){case 0:if(!(t=this._hostedForm))throw new Pn(bn.PaymentNotInitialized);if(n=e.additionalAction,!(r=e.payment)||!r.methodId)throw new cu(["payment.methodId"]);return[4,t.validate()];case 1:return u.sent(),[4,t.submit(r,n)];case 2:return i=u.sent().payload,o=i.response,a=function(t){return(0,s.__awaiter)(c,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){return[2,this.execute((0,s.__assign)({additionalAction:t},e))]}))}))},[4,this._ppsdkStepHandler.handle(o,{continue:{humanVerification:a}})];case 3:return u.sent(),[4,this._store.dispatch(this._orderActionCreator.loadCurrentOrder())];case 4:return u.sent(),[2]}}))}))},e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e&&e.creditCard&&e.creditCard.form,n=this._store.getState().config,r=(n.getStoreConfig()||{}).paymentSettings,i=(void 0===r?{}:r).bigpayBaseUrl,o=void 0===i?"":i,!t)throw new ae;return[4,(a=t&&this._hostedFormFactory.create(o,t)).attach()];case 1:return s.sent(),this._hostedForm=a,[2]}}))}))},e.prototype.deinitialize=function(){this._hostedForm&&this._hostedForm.detach()},e}(),tp=function(){function e(e,t){this._requestSender=e,this._stepHandler=t}return e.prototype.execute=function(e){var t=this,n=e.methodId,r=e.bigpayBaseUrl,i={credentials:!1,body:{payment_method_id:n},headers:{authorization:e.token,"X-XSRF-TOKEN":null}};return this._requestSender.post(r+"/payments",i).then((function(e){return t._stepHandler.handle(e)}))},e.prototype.initialize=function(){return Promise.resolve()},e.prototype.deinitialize=function(){},e}(),np=function(e,t,n,r,i){var o=new $l;return o.register(Vl.CARD,(function(){return new ep(e,t,i,r)})),o.register(Vl.NONE,(function(){return new tp(n,r)})),o.register(Vl.UNSUPPORTED,(function(){})),o},rp=function(){function e(e,t){this._requestSender=e,this._stepHandler=t}return e.prototype.resume=function(e){var t=e.paymentId,n=e.bigpayBaseUrl,r=e.orderId;return(0,s.__awaiter)(this,void 0,void 0,(function(){var e,i,o=this;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:return[4,this._getToken(r).catch((function(){throw new Hc}))];case 1:return e=a.sent(),i={credentials:!1,headers:{authorization:e,"X-XSRF-TOKEN":null}},[2,this._requestSender.get(n+"/payments/"+t,i).then((function(e){return o._stepHandler.handle(e)}))]}}))}))},e.prototype._getToken=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){return t={params:{order_id:e}},[2,this._requestSender.get("/api/storefront/payments/auth-token",t).then((function(e){return e.body.auth_token}))]}))}))},e}(),ip=function(){function e(e,t,n,r,i,o,a){this._store=e,this._orderActionCreator=t,this._paymentActionCreator=n,this._paymentMethodActionCreator=r,this._storeCreditActionCreator=i,this._remoteCheckoutActionCreator=o,this._storefrontPaymentRequestSender=a}return e.prototype.initialize=function(){return Promise.resolve(this._store.getState())},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d,l,p,_,y;return(0,s.__generator)(this,(function(f){switch(f.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!n)throw new cu(["payment"]);return i=n.methodId,[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(i,t))];case 1:if(o=f.sent().paymentMethods.getPaymentMethodOrThrow,a=o(i),c=a.clientToken,u=a.initializationData,d=(void 0===u?{}:u).redirectUrl,!c||!d)throw new m(h.MissingPaymentMethod);if(!(l=JSON.parse(c).id))throw new m(h.MissingPaymentToken);return p={methodId:i,paymentData:{nonce:l}},_=this._store.getState().checkout.getCheckoutOrThrow().isStoreCreditApplied,[4,this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(_))];case 2:return f.sent(),[4,this._store.dispatch(this._remoteCheckoutActionCreator.initializePayment(i,{useStoreCredit:_}))];case 3:return f.sent(),[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 4:return f.sent(),[4,this._prepareForReferredRegistration(i,l)];case 5:f.sent(),f.label=6;case 6:return f.trys.push([6,8,,9]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment(p))];case 7:return[2,f.sent()];case 8:if((y=f.sent())instanceof x&&"additional_action_required"===y.body.status)return window.location.replace(d),[2,new Promise(Z.noop)];throw y;case 9:return[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype.deinitialize=function(){return Promise.resolve(this._store.getState())},e.prototype._prepareForReferredRegistration=function(e,t){return this._storefrontPaymentRequestSender.saveExternalId(e,t)},e}();const op=ip,ap=function(e){function t(t,n,r,i,o){var a=e.call(this,t,n,r,i)||this;return a._formPoster=o,a}return(0,s.__extends)(t,e),t.prototype.execute=function(t,n){var r=this,i=t.payment;if(!i)throw new Pn(bn.PaymentNotInitialized);var o=i.paymentData;if(!o)throw new m(h.MissingPayment);if(this._isThreeDSTwoExperimentOn()){var a=(0,s.__assign)((0,s.__assign)({},o),{browser_info:Jd()});t.payment&&(t.payment.paymentData=a)}return e.prototype.execute.call(this,t,n).catch((function(e){return e instanceof x&&(0,Z.some)(e.body.errors,{code:"three_d_secure_required"})?new Promise((function(){var t;t=r._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},r._formPoster.postForm(e.body.three_ds_result.acs_url,t,void 0,"_top")})):Promise.reject(e)}))},t.prototype.finalize=function(t){var n=this._store.getState(),r=n.order.getOrder();return r&&n.payment.getPaymentStatus()===bu?this._store.dispatch(this._orderActionCreator.finalizeOrder(r.orderId,t)):e.prototype.finalize.call(this,t)},t.prototype._isThreeDSTwoExperimentOn=function(){return!0===this._store.getState().config.getStoreConfigOrThrow().checkoutSettings.features["INT-4994.Opayo_3DS2"]},t}(wu);const sp=function(e){function t(t){var n=e.call(this,t,{message:"The request has timed out or aborted."})||this;return n.name="TimeoutError",n.type="timeout",n}return(0,s.__extends)(t,e),t}(x);var cp,up,dp;!function(e){e.CHARGE="CHARGE",e.STORE="STORE"}(cp||(cp={})),function(e){e.americanExpress="AMERICAN_EXPRESS",e.discover="DISCOVER",e.discoverDiners="DISCOVER_DINERS",e.JCB="JCB",e.masterCard="MASTERCARD",e.unionPay="CHINA_UNIONPAY",e.unknown="OTHER_BRAND",e.visa="VISA",e.squareGift="SQUARE_GIFT_CARD"}(up||(up={})),function(e){e.applePay="APPLEPAY",e.none="NONE"}(dp||(dp={}));var lp=function(){function e(e,t,n,r,i,o,a,s){this._store=e,this._checkoutActionCreator=t,this._orderActionCreator=n,this._paymentActionCreator=r,this._paymentMethodActionCreator=i,this._paymentStrategyActionCreator=o,this._requestSender=a,this._scriptLoader=s}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i=this;return(0,s.__generator)(this,(function(o){if(t=e.methodId,n=e.gatewayId,!(r=e.square))throw new ae('Unable to proceed because "options.square" argument is not provided.');return this._squareOptions=r,this._syncPaymentMethod(t),[2,new Promise((function(e,r){return(0,s.__awaiter)(i,void 0,void 0,(function(){var i,o,a;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:i=this._store.getState(),o=i.paymentMethods.getPaymentMethodOrThrow(t,n).config.testMode,s.label=1;case 1:return s.trys.push([1,3,,4]),[4,this._scriptLoader.load(o)];case 2:return a=s.sent(),this._paymentForm=a(this._getFormOptions({resolve:e,reject:r})),this._getPaymentForm().build(),[3,4];case 3:return s.sent(),r(new gi),[3,4];case 4:return[2]}}))}))})).then((function(){return i._store.getState()}))]}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:if(!(n=e.payment)||!n.methodId)throw new ae('Unable to submit payment because "payload.payment.methodId" argument is not provided.');return this._syncPaymentMethod(n.methodId),[4,this._getNonceInstrument(n.methodId)];case 1:return r=i.sent(),[4,this._store.dispatch(this._orderActionCreator.submitOrder((0,Z.omit)(e,"payment"),t))];case 2:return i.sent(),[4,this._store.dispatch(this._paymentActionCreator.submitPayment((0,s.__assign)((0,s.__assign)({},n),{paymentData:r})))];case 3:return i.sent(),[2,this._store.getState()]}}))}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype.deinitialize=function(){return Promise.resolve(this._store.getState())},e.prototype._syncPaymentMethod=function(e){var t=this._store.getState();if(this._paymentMethod=t.paymentMethods.getPaymentMethodOrThrow(e),!this._paymentMethod.initializationData)throw new m(h.MissingPaymentMethod)},e.prototype._getCountryCode=function(e){switch(e.toUpperCase()){case"NEW ZELAND":return"NZ";case"AUSTRALIA":return"AU";default:return"US"}},e.prototype._getNonceInstrument=function(e){var t=this,n=this._store.getState().paymentMethods.getPaymentMethod(e);if(n){var r=n.initializationData;if(r&&r.paymentData.nonce)return Promise.resolve({nonce:n.initializationData.paymentData.nonce})}return new Promise((function(e,n){t._deferredRequestNonce&&t._deferredRequestNonce.reject(new sp),t._deferredRequestNonce={resolve:e,reject:n},t._getPaymentForm().requestCardNonce()}))},e.prototype._getFormOptions=function(e){var t,n=this;return(0,s.__assign)((0,s.__assign)((0,s.__assign)({},this._getInitializeOptions()),null===(t=this._paymentMethod)||void 0===t?void 0:t.initializationData),{callbacks:{cardNonceResponseReceived:function(e,t,r,i,o){var a=n._getDeferredRequestNonce(),s=n._getInitializeOptions().onError,c=void 0===s?Z.noop:s;if(!t)return c(e),a.reject((0,Z.get)(e,"0",{}));r&&r.digital_wallet_type!==dp.none&&t?n._handleWalletNonceResponse(t,r,i,o):n._is3DSExperimentOn()?n._getPaymentForm().verifyBuyer(t,n._getVerificationDetails(),(function(e,n){if(!(0,Z.isEmpty)(e))return c(e),a.reject((0,Z.get)(e,"0",{}));a.resolve({nonce:JSON.stringify({nonce:t,token:n.token})})})):a.resolve({nonce:t})},createPaymentRequest:this._paymentRequestPayload.bind(this),paymentFormLoaded:function(){e.resolve(),n._setPostalCode()},unsupportedBrowserDetected:function(){return e.reject(new Si)}}})},e.prototype._getInitializeOptions=function(){if(!this._squareOptions)throw new Pn(bn.PaymentNotInitialized);return this._squareOptions},e.prototype._handleWalletNonceResponse=function(e,t,n,r){var i=this._getInitializeOptions(),o=i.onError,a=void 0===o?Z.noop:o,s=i.onPaymentSelect,c=void 0===s?Z.noop:s;e&&this._paymentMethod&&this._paymentInstrumentSelected(this._paymentMethod.id,e,t,n,r).then(c).catch(a)},e.prototype._paymentInstrumentSelected=function(e,t,n,r,i){var o=this;return this._store.dispatch(this._paymentStrategyActionCreator.widgetInteraction((function(){return o._setExternalCheckoutData(t,n,r,i).then((function(){return Promise.all([o._store.dispatch(o._checkoutActionCreator.loadCurrentCheckout()),o._store.dispatch(o._paymentMethodActionCreator.loadPaymentMethod(e))])}))}),{methodId:e}),{queueId:"widgetInteraction"})},e.prototype._paymentRequestPayload=function(){var e=this._store.getState(),t=e.checkout.getCheckout(),n=e.config.getStoreConfigOrThrow();if(!t)throw new m(h.MissingCheckout);return{requestShippingAddress:!0,requestBillingInfo:!0,currencyCode:n.currency.code,countryCode:this._getCountryCode(n.storeProfile.storeCountry),total:{label:n.storeProfile.storeName,amount:String(t.subtotal),pending:!1}}},e.prototype._setExternalCheckoutData=function(e,t,n,r){return this._requestSender.post("/checkout.php",{headers:(0,s.__assign)({Accept:"text/html","Content-Type":"application/x-www-form-urlencoded"},C),body:{nonce:e,provider:"squarev2",action:"set_external_checkout",cardData:JSON.stringify(t),billingContact:JSON.stringify(n),shippingContact:JSON.stringify(r)}})},e.prototype._setPostalCode=function(){var e=this._store.getState().billingAddress.getBillingAddress();e&&e.postalCode&&this._getPaymentForm().setPostalCode(e.postalCode)},e.prototype._getBillingContact=function(){var e=this._store.getState().billingAddress.getBillingAddressOrThrow();return{givenName:e.firstName,familyName:e.lastName,email:e.email||"",country:e.countryCode,countryName:e.country,region:"",city:e.city,postalCode:e.postalCode,addressLines:[e.address1,e.address2],phone:e.phone}},e.prototype._getAmountAndCurrencyCode=function(){var e=this._store.getState(),t=e.cart.getCartOrThrow(),n=e.checkout.getCheckoutOrThrow();return[String(n.grandTotal),t.currency.code]},e.prototype._getVerificationDetails=function(){var e=this._getBillingContact(),t=this._getAmountAndCurrencyCode(),n=t[0],r=t[1];return{intent:cp.CHARGE,currencyCode:r,amount:n,billingContact:e}},e.prototype._getDeferredRequestNonce=function(){if(!this._deferredRequestNonce)throw new Pn(bn.PaymentNotInitialized);return this._deferredRequestNonce},e.prototype._getPaymentForm=function(){if(!this._paymentForm)throw new Pn(bn.PaymentNotInitialized);return this._paymentForm},e.prototype._is3DSExperimentOn=function(){return!0===this._store.getState().config.getStoreConfigOrThrow().checkoutSettings.features["PROJECT-3828.add_3ds_support_on_squarev2"]},e}();const pp=lp;var hp=function(){function e(e,t){void 0===t&&(t=window),this._scriptLoader=e,this._window=t}return e.prototype._isSquareWindow=function(e){return!!e.SqPaymentForm},e.prototype.load=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t=this;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return[4,this._scriptLoader.loadScript(e?"//js.squareupsandbox.com/v2/paymentform":"//js.squareup.com/v2/paymentform")];case 1:return n.sent(),[2,function(e){if(!t._isSquareWindow(t._window))throw new gi;return new t._window.SqPaymentForm(e)}]}}))}))},e}();const mp=hp;var _p={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 yp(e){var t=e.replace(/_/g,"-").toLowerCase().split("-"),n=t[0],r=t[1],i=_p[n];if(!i)return"auto";var o=r?n+"-"+r.toUpperCase():n;return i.indexOf(o)>-1?o:i[0]}var fp=[na.SOFORT,na.EPS,na.GRABPAY,na.BANCONTACT,na.IDEAL,na.GIROPAY,na.ALIPAY,na.KLARNA],gp=function(){function e(e,t,n,r,i,o,a){this._store=e,this._paymentMethodActionCreator=t,this._paymentActionCreator=n,this._orderActionCreator=r,this._stripeScriptLoader=i,this._storeCreditActionCreator=o,this._billingAddressActionCreator=a,this._isMounted=!1}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o=this;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:if(t=e.stripeupe,n=e.methodId,r=e.gatewayId,!(null==t?void 0:t.containerId))throw new Pn(bn.PaymentNotInitialized);if(!r)throw new ae('Unable to initialize payment because "gatewayId" argument is not provided.');return this._isDeinitialize=!1,this._loadStripeElement(t,r,n).catch((function(e){var n;return null===(n=t.onError)||void 0===n?void 0:n.call(t,e)})),i=this,[4,this._store.subscribe((function(e){return(0,s.__awaiter)(o,void 0,void 0,(function(){var e,i,o,a,c;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return(e=null===(o=this._stripeElements)||void 0===o?void 0:o.getElement(ia.PAYMENT))?[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(r,{params:{method:n}})).catch((function(e){return i=e}))]:[3,4];case 1:return s.sent(),i?(this._isMounted&&(e.unmount(),this._isMounted=!1),null===(a=t.onError)||void 0===a||a.call(t,i),[3,4]):[3,2];case 2:return this._isMounted?[3,4]:[4,null===(c=this._stripeElements)||void 0===c?void 0:c.fetchUpdates()];case 3:s.sent(),e.mount("#"+t.containerId),this._isMounted=!0,s.label=4;case 4:return[2]}}))}))}),(function(e){var t=e.checkout.getCheckout();return t&&t.outstandingBalance}),(function(e){var t=e.checkout.getCheckout();return t&&t.coupons}))];case 1:return i._unsubscribe=a.sent(),[2,Promise.resolve(this._store.getState())]}}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d,l,p,h,m,_,y,f,g;return(0,s.__generator)(this,(function(v){switch(v.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!n||!n.paymentData)throw new cu(["payment.paymentData"]);if(!this._stripeUPEClient)throw new Pn(bn.PaymentNotInitialized);return i=n.paymentData,o=n.methodId,a=n.gatewayId,c=Vu(i)?i:{},u=c.shouldSaveInstrument,d=void 0!==u&&u,l=c.shouldSetAsDefaultInstrument,p=void 0!==l&&l,(h=this._store.getState().checkout.getCheckoutOrThrow().isStoreCreditApplied)?[4,this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(h))]:[3,2];case 1:v.sent(),v.label=2;case 2:return a?[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(a,{params:{method:o}}))]:[3,5];case 3:return m=v.sent().customer.getCustomerOrThrow,_=m(),y=_.email,void 0===_.isStripeLinkAuthenticated||y?[3,5]:(f=this._store.getState().billingAddress.getBillingAddressOrThrow(),[4,this._store.dispatch(this._billingAddressActionCreator.updateAddress(f))]);case 4:v.sent(),v.label=5;case 5:return Gn(i)?[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))]:[3,7];case 6:return v.sent(),g=i.instrumentId,[2,this._executeWithVaulted(n.methodId,g,p)];case 7:return(0,Z.includes)(fp,o)?[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))]:[3,9];case 8:return v.sent(),[2,this._executeWithAPM(n.methodId)];case 9:return[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 10:return v.sent(),[2,this._executeWithoutRedirect(n.methodId,d,p)]}}))}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype.deinitialize=function(){var e,t;return this._unsubscribe&&this._unsubscribe(),null===(t=null===(e=this._stripeElements)||void 0===e?void 0:e.getElement(ia.PAYMENT))||void 0===t||t.unmount(),this._isMounted=!1,this._isDeinitialize=!0,Promise.resolve(this._store.getState())},e.prototype._isCancellationError=function(e){var t,n;return e&&-1!==(null===(n=null===(t=e.payment_intent.last_payment_error)||void 0===t?void 0:t.message)||void 0===n?void 0:n.indexOf("canceled"))},e.prototype._throwDisplayableStripeError=function(e){if((0,Z.includes)(["card_error","invalid_request_error","validation_error"],e.type))throw new Error(e.message)},e.prototype._executeWithAPM=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:t=this._store.getState().paymentMethods.getPaymentMethodOrThrow(e),n={methodId:e,paymentData:{formattedPayload:{credit_card_token:{token:t.clientToken},vault_payment_instrument:!1,confirm:!1,set_as_default_stored_instrument:!1}}},i.label=1;case 1:return i.trys.push([1,3,,5]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment(n))];case 2:return[2,i.sent()];case 3:return r=i.sent(),[4,this._processAdditionalAction(r)];case 4:return[2,i.sent()];case 5:return[2]}}))}))},e.prototype._executeWithoutRedirect=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:r=this._store.getState().paymentMethods.getPaymentMethodOrThrow(e),i={methodId:e,paymentData:{formattedPayload:{credit_card_token:{token:r.clientToken},vault_payment_instrument:t,confirm:!1,set_as_default_stored_instrument:n}}},a.label=1;case 1:return a.trys.push([1,3,,5]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment(i))];case 2:return[2,a.sent()];case 3:return o=a.sent(),[4,this._processAdditionalAction(o,t,n,e)];case 4:return[2,a.sent()];case 5:return[2]}}))}))},e.prototype._executeWithVaulted=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:r=this._store.getState().paymentMethods.getPaymentMethodOrThrow(e),a.label=1;case 1:return a.trys.push([1,3,,5]),i={methodId:e,paymentData:{formattedPayload:{bigpay_token:{token:t},confirm:!1,client_token:r.clientToken,set_as_default_stored_instrument:n}}},[4,this._store.dispatch(this._paymentActionCreator.submitPayment(i))];case 2:return[2,a.sent()];case 3:return o=a.sent(),[4,this._processVaultedAdditionalAction(o,e,n)];case 4:return[2,a.sent()];case 5:return[2]}}))}))},e.prototype._loadStripeElement=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d,l,p,_,y,f,g,v,w,C;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return r=e.containerId,i=e.style,o=e.render,[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(t,{params:{method:n}}))];case 1:if(a=s.sent(),c=a.paymentMethods.getPaymentMethodOrThrow(n),u=c.initializationData,d=u.stripePublishableKey,l=u.stripeConnectedAccount,p=u.shopperLanguage,!c.clientToken)throw new m(h.MissingPaymentMethod);return _=this,[4,this._loadStripeJs(d,l)];case 2:_._stripeUPEClient=s.sent(),i&&(y={variables:{colorPrimary:(f=i).fieldInnerShadow,colorBackground:f.fieldBackground,colorText:f.labelText,colorDanger:f.fieldErrorText,colorTextSecondary:f.labelText,colorTextPlaceholder:f.fieldPlaceholderText,colorIcon:f.fieldPlaceholderText},rules:{".Input":{borderColor:f.fieldBorder,color:f.fieldText,boxShadow:f.fieldInnerShadow}}}),this._stripeElements=this._stripeScriptLoader.getElements(this._stripeUPEClient,{clientSecret:c.clientToken,locale:yp(p),appearance:y}),g=a.billingAddress.getBillingAddress,v=a.shippingAddress.getShippingAddress,w=(v()||g()||{}).postalCode,C=this._stripeElements.getElement(ia.PAYMENT)||this._stripeElements.create(ia.PAYMENT,{fields:{billingDetails:{email:ra.NEVER,address:{country:ra.NEVER,city:ra.NEVER,postalCode:w?ra.NEVER:ra.AUTO}}},wallets:{applePay:ra.NEVER,googlePay:ra.NEVER}});try{C.mount("#"+r),this._isMounted=!0}catch(e){if(!this._isDeinitialize)throw new ae("Unable to mount Stripe component without valid container ID.")}return C.on("ready",(function(){o()})),[2]}}))}))},e.prototype._processAdditionalAction=function(e,t,n,r){var i;return void 0===t&&(t=!1),void 0===n&&(n=!1),(0,s.__awaiter)(this,void 0,void 0,(function(){var o,a,c,u,d,l,p,h,m,_,y,f;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!(e instanceof x))throw e;if(!this._stripeUPEClient||!this._stripeElements)throw new Pn(bn.PaymentNotInitialized);return(0,Z.some)(e.body.errors,{code:"additional_action_required"})?(o=e.body.additional_action_required,a=o.type,c=o.data,u=c.token,d=c.redirect_url,"redirect_to_url"===a&&d?[4,this._stripeUPEClient.confirmPayment(this._mapStripePaymentData(d))]:[3,2]):[3,11];case 1:if(l=s.sent(),p=l.paymentIntent,h=l.error)throw this._throwDisplayableStripeError(h),new be;if(!p)throw new x;return[3,11];case 2:if(!r||"additional_action_requires_payment_method"!==a||!u)return[3,11];m=void 0,_=!1,y=this._mapStripePaymentData(),s.label=3;case 3:return s.trys.push([3,5,,10]),[4,this._stripeUPEClient.confirmPayment(y)];case 4:return m=s.sent(),[3,10];case 5:s.sent(),s.label=6;case 6:return s.trys.push([6,8,,9]),[4,this._stripeUPEClient.retrievePaymentIntent(u)];case 7:return m=s.sent(),[3,9];case 8:return s.sent(),_=!0,[3,9];case 9:return[3,10];case 10:if(null==m?void 0:m.error){if(this._throwDisplayableStripeError(m.error),this._isCancellationError(m.error))throw new uu;throw new be}if(!(null==m?void 0:m.paymentIntent)&&!_)throw new x;return f={methodId:r,paymentData:{formattedPayload:{credit_card_token:{token:_?u:null===(i=null==m?void 0:m.paymentIntent)||void 0===i?void 0:i.id},confirm:!1,vault_payment_instrument:t,set_as_default_stored_instrument:n}}},[2,this._store.dispatch(this._paymentActionCreator.submitPayment(f))];case 11:throw e}}))}))},e.prototype._processVaultedAdditionalAction=function(e,t,n){var r;return void 0===n&&(n=!1),(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!(e instanceof x))throw e;if(!this._stripeUPEClient||!this._stripeElements)throw new Pn(bn.PaymentNotInitialized);if(!(0,Z.some)(e.body.errors,{code:"three_d_secure_required"})||!t)return[3,9];i=e.body.three_ds_result.token,o=void 0,a=!1,s.label=1;case 1:return s.trys.push([1,3,,8]),[4,this._stripeUPEClient.confirmCardPayment(i)];case 2:return o=s.sent(),[3,8];case 3:s.sent(),s.label=4;case 4:return s.trys.push([4,6,,7]),[4,this._stripeUPEClient.retrievePaymentIntent(i)];case 5:return o=s.sent(),[3,7];case 6:return s.sent(),a=!0,[3,7];case 7:return[3,8];case 8:if(null==o?void 0:o.error){if(this._throwDisplayableStripeError(o.error),this._isCancellationError(o.error))throw new uu;throw new be}if(!(null==o?void 0:o.paymentIntent)&&!a)throw new x;return c={methodId:t,paymentData:{formattedPayload:{credit_card_token:{token:a?i:null===(r=null==o?void 0:o.paymentIntent)||void 0===r?void 0:r.id},confirm:!1,set_as_default_stored_instrument:n}}},[2,this._store.dispatch(this._paymentActionCreator.submitPayment(c))];case 9:throw e}}))}))},e.prototype._mapStripeAddress=function(e){if(e)return{city:e.city,country:e.countryCode,postal_code:e.postalCode};throw new m(h.MissingBillingAddress)},e.prototype._mapStripePaymentData=function(e){var t=this._store.getState().billingAddress.getBillingAddress(),n=this._mapStripeAddress(t),r=null==t?void 0:t.email;if(!this._stripeElements)throw new Pn(bn.PaymentNotInitialized);if(!(r&&n&&n.city&&n.country))throw new m(h.MissingBillingAddress);return{elements:this._stripeElements,redirect:ra.IF_REQUIRED,confirmParams:(0,s.__assign)({payment_method_data:{billing_details:{email:r,address:n}}},e&&{return_url:e})}},e.prototype._loadStripeJs=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){return this._stripeUPEClient?[2,this._stripeUPEClient]:[2,this._stripeScriptLoader.getStripeClient(e,t)]}))}))},e}();const vp=gp;var wp,Cp,Sp,Ip;function bp(e){return Boolean(e.cardNumberElementOptions)&&Boolean(e.cardCvcElementOptions)&&Boolean(e.cardExpiryElementOptions)}!function(e){e.Solid="solid",e.Default="default"}(wp||(wp={})),function(e){e.Alipay="alipay",e.CardCvc="cardCvc",e.CardExpiry="cardExpiry",e.CardNumber="cardNumber",e.CreditCard="card",e.IDEAL="idealBank",e.Sepa="iban"}(Cp||(Cp={})),function(e){e.Alipay="alipay",e.CreditCard="card",e.IDEAL="ideal",e.Sepa="sepa_debit"}(Sp||(Sp={})),function(e){e.AuthFailure="auth_failure"}(Ip||(Ip={}));const Pp=function(e){function t(t){var n=e.call(this,t===Ip.AuthFailure?"User did not authenticate":"There was an error while processing your payment. Please try again or contact us.")||this;return n.type="stripev3_error",n.subtype=t,n}return(0,s.__extends)(t,e),t}(p);var Ep=[Cp.Alipay,Cp.IDEAL],Ap=function(){function e(e,t,n,r,i,o,a,s){this._store=e,this._paymentMethodActionCreator=t,this._paymentActionCreator=n,this._orderActionCreator=r,this._stripeScriptLoader=i,this._storeCreditActionCreator=o,this._hostedFormFactory=a,this._locale=s}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d,l,p,h;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.stripev3,n=e.methodId,!(r=e.gatewayId))throw new ae('Unable to initialize payment because "gatewayId" argument is not provided.');return this._initializeOptions=t,this._isDeinitialize=!1,i=this._store.getState().paymentMethods.getPaymentMethodOrThrow(n),o=i.initializationData,a=o.stripePublishableKey,c=o.stripeConnectedAccount,u=o.useIndividualCardFields,d=this._getInitializeOptions().form,this._useIndividualCardFields=u,l=this,[4,this._loadStripeJs(a,c)];case 1:return l._stripeV3Client=s.sent(),this._isCreditCard(n)&&this._shouldShowTSVHostedForm(n,r)&&d?(p=this,[4,this._mountCardVerificationFields(d)]):[3,3];case 2:return p._hostedForm=s.sent(),[3,5];case 3:return h=this,[4,this._mountCardFields(n)];case 4:h._stripeElement=s.sent(),s.label=5;case 5:return[2,Promise.resolve(this._store.getState())]}}))}))},e.prototype.execute=function(e,t){var n,r;return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u,d,l,p,_,y,f,g,v,w,C,S,I,b,P,E,A,O,k;return(0,s.__generator)(this,(function(T){switch(T.label){case 0:if(i=e.payment,o=(0,s.__rest)(e,["payment"]),!i||!i.paymentData)throw new cu(["payment.paymentData"]);return u=i.paymentData,d=i.gatewayId,l=i.methodId,p=Vu(u)?u:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1},_=p.shouldSaveInstrument,y=p.shouldSetAsDefaultInstrument,f=(0,Z.includes)(Ep,l),(g=this._store.getState().checkout.getCheckoutOrThrow().isStoreCreditApplied)?[4,this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(g))]:[3,2];case 1:T.sent(),T.label=2;case 2:return T.trys.push([2,13,,15]),f?[4,this._store.dispatch(this._orderActionCreator.submitOrder(o,t))]:[3,4];case 3:T.sent(),T.label=4;case 4:return[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(""+d,{params:{method:l}}))];case 5:return v=T.sent(),Gn(u)?[4,this._store.dispatch(this._orderActionCreator.submitOrder(o,t))]:[3,8];case 6:if(T.sent(),w=u.instrumentId,C=v.paymentMethods.getPaymentMethodOrThrow(i.methodId),!(S=C.clientToken))throw new m(h.MissingPaymentMethod);return[4,this._executeWithVaulted(i,w,y,S)];case 7:return[2,T.sent()];case 8:return I=v.paymentMethods.getPaymentMethodOrThrow(l),[4,this._confirmStripePayment(I)];case 9:return b=T.sent(),P=I.clientToken,E=I.method,A=(null!==(r=null!==(n=b.paymentIntent)&&void 0!==n?n:b.paymentMethod)&&void 0!==r?r:{id:""}).id,c=b.error,a={credit_card_token:{token:A},vault_payment_instrument:_,confirm:!1,set_as_default_stored_instrument:y},E===Cp.CreditCard&&(a.client_token=P),f?[3,11]:[4,this._store.dispatch(this._orderActionCreator.submitOrder(o,t))];case 10:T.sent(),T.label=11;case 11:return O=this._buildPaymentPayload(l,a,y),[4,this._store.dispatch(this._paymentActionCreator.submitPayment(O))];case 12:return[2,T.sent()];case 13:return k=T.sent(),[4,this._processAdditionalAction(this._handleEmptyPaymentIntentError(k,c),l,_,y)];case 14:return[2,T.sent()];case 15:return[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype.deinitialize=function(){return this._hostedForm&&this._hostedForm.detach(),this._isDeinitialize=!0,this._unmountElement(),Promise.resolve(this._store.getState())},e.prototype._buildPaymentPayload=function(e,t,n){return{methodId:e,paymentData:n?{formattedPayload:(0,s.__assign)((0,s.__assign)({},t),{set_as_default_stored_instrument:n})}:{formattedPayload:t}}},e.prototype._isCancellationError=function(e){var t,n;return e&&-1!==(null===(n=null===(t=e.payment_intent.last_payment_error)||void 0===t?void 0:t.message)||void 0===n?void 0:n.indexOf("canceled"))},e.prototype._isAuthError=function(e){return"payment_intent_authentication_failure"===(null==e?void 0:e.code)},e.prototype._isCreditCard=function(e){return e===Sp.CreditCard},e.prototype._isHostedFieldAvailable=function(){var e,t=this._getInitializeOptions(),n=(0,Z.omitBy)(null===(e=t.form)||void 0===e?void 0:e.fields,Z.isEmpty);return!(0,Z.isEmpty)(n)},e.prototype._isHostedPaymentFormEnabled=function(e,t){var n=(0,this._store.getState().paymentMethods.getPaymentMethodOrThrow)(e,t);return Boolean(n.config.isHostedFormEnabled)},e.prototype._confirmStripePayment=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a;return(0,s.__generator)(this,(function(s){if(t=e.clientToken,n=e.method,r=e.returnUrl,!t)throw new m(h.MissingPaymentMethod);switch(n){case Cp.Alipay:return[2,this._getStripeJs().confirmAlipayPayment(t,{return_url:r},{handleActions:!1})];case Cp.IDEAL:return i=this._mapStripePaymentData(Sp.IDEAL,r),[2,this._getStripeJs().confirmIdealPayment(t,i,{handleActions:!1})];case Cp.Sepa:return i=this._mapStripePaymentData(Sp.Sepa),[2,this._getStripeJs().confirmSepaDebitPayment(t,i)];default:return o=this._useIndividualCardFields?this._getStripeCardElements()[0]:this._getStripeElement(),a=this._mapStripeBillingDetails(this._store.getState().billingAddress.getBillingAddress(),this._store.getState().customer.getCustomer()),[2,this._getStripeJs().createPaymentMethod({type:Sp.CreditCard,card:o,billing_details:a})]}return[2]}))}))},e.prototype._executeWithVaulted=function(e,t,n,r){var i;return(0,s.__awaiter)(this,void 0,void 0,(function(){var o,a,c;return(0,s.__generator)(this,(function(u){switch(u.label){case 0:return o={bigpay_token:{token:t},confirm:!0,client_token:r,set_as_default_stored_instrument:n},this._isHostedPaymentFormEnabled(e.methodId,e.gatewayId)&&this._hostedForm?(a=this._hostedForm,e.paymentData&&Gn(e.paymentData)&&(e.paymentData=(0,s.__assign)((0,s.__assign)({},e.paymentData),{instrumentId:JSON.stringify({token:(null===(i=e.paymentData)||void 0===i?void 0:i.instrumentId)||"",client_token:r})})),[4,a.validate()]):[3,3];case 1:return u.sent(),[4,a.submit(e)];case 2:return u.sent(),[2,this._store.dispatch(this._orderActionCreator.loadCurrentOrder())];case 3:return c=this._buildPaymentPayload(e.methodId,o,n),[2,this._store.dispatch(this._paymentActionCreator.submitPayment(c))]}}))}))},e.prototype._getInitializeOptions=function(){if(!this._initializeOptions)throw new Pn(bn.PaymentNotInitialized);return this._initializeOptions},e.prototype._getStripeCardElements=function(){if(!this._stripeCardElements)throw new Pn(bn.PaymentNotInitialized);return this._stripeCardElements},e.prototype._getStripeElement=function(){if(!this._stripeElement)throw new Pn(bn.PaymentNotInitialized);return this._stripeElement},e.prototype._getStripeJs=function(){if(!this._stripeV3Client)throw new Pn(bn.PaymentNotInitialized);return this._stripeV3Client},e.prototype._handleEmptyPaymentIntentError=function(e,t){return e instanceof x&&(0,Z.some)(e.body.errors,{code:"required_field"})&&t?new Error(t.message):e},e.prototype._loadStripeJs=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){return this._stripeV3Client?[2,Promise.resolve(this._stripeV3Client)]:[2,this._stripeScriptLoader.load(e,t,this._locale)]}))}))},e.prototype._mapStripeAddress=function(e){return e?{city:e.city,country:e.countryCode,line1:e.address1,line2:e.address2,postal_code:e.postalCode,state:e.stateOrProvinceCode}:{line1:""}},e.prototype._mapStripeBillingDetails=function(e,t){var n=e||t||{firstName:"Guest",lastName:""},r=(n.firstName+" "+n.lastName).trim(),i=this._getInitializeOptions().options;if(this._useIndividualCardFields&&bp(i)){var o=i.zipCodeElementOptions;if(o){var a=document.getElementById(o.containerId)?document.getElementById(o.containerId).value:"";a&&e&&(e=(0,s.__assign)((0,s.__assign)({},e),{postalCode:a}))}}var c,u={address:this._mapStripeAddress(e)};if(t&&t.addresses[0]&&or(t.addresses[0])){var d=t.addresses[0],l=t.email;return(c=d.phone)?(0,s.__assign)((0,s.__assign)({},u),{email:l,name:r,phone:c}):(0,s.__assign)((0,s.__assign)({},u),{email:l,name:r})}return e?(l=e.email,(c=e.phone)?(0,s.__assign)((0,s.__assign)({},u),{email:l,name:r,phone:c}):(0,s.__assign)((0,s.__assign)({},u),{email:l,name:r})):(0,s.__assign)((0,s.__assign)({},u),{name:r})},e.prototype._mapStripePaymentData=function(e,t){var n,r=this._store.getState().customer.getCustomer(),i=this._store.getState().billingAddress.getBillingAddress(),o={payment_method:(n={},n[e]=this._getStripeElement(),n.billing_details=this._mapStripeBillingDetails(i,r),n)};return e===Sp.IDEAL?(0,s.__assign)((0,s.__assign)({},o),{return_url:t}):o},e.prototype._mountCardFields=function(e){var t,n=this,r=this._getInitializeOptions(),i=r.options,o=r.containerId;return new Promise((function(r,a){switch(n._stripeElements||(n._stripeElements=n._getStripeJs().elements()),e){case Cp.CreditCard:if(n._useIndividualCardFields&&bp(i)){var s=i.cardNumberElementOptions,c=i.cardExpiryElementOptions,u=i.cardCvcElementOptions,d=n._stripeElements.getElement(Cp.CardNumber)||n._stripeElements.create(Cp.CardNumber,s),l=n._stripeElements.getElement(Cp.CardExpiry)||n._stripeElements.create(Cp.CardExpiry,c),p=n._stripeElements.getElement(Cp.CardCvc)||n._stripeElements.create(Cp.CardCvc,u);n._stripeCardElements=[d,l,p],t=n._stripeCardElements[0];try{d.mount("#"+s.containerId),l.mount("#"+c.containerId),p.mount("#"+u.containerId)}catch(e){n._isDeinitialize||a(new ae("Unable to mount Stripe component without valid container ID."))}}else{t=n._stripeElements.getElement(e)||n._stripeElements.create(e,i);try{t.mount("#"+o)}catch(e){n._isDeinitialize||a(new ae("Unable to mount Stripe component without valid container ID."))}}break;case Cp.IDEAL:case Cp.Sepa:t=n._stripeElements.getElement(e)||n._stripeElements.create(e,i);try{t.mount("#"+o)}catch(e){n._isDeinitialize||a(new ae("Unable to mount Stripe component without valid container ID."))}case Cp.Alipay:}r(t)}))},e.prototype._mountCardVerificationFields=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(t=this._store.getState().config,!(n=t.getStoreConfig()))throw new m(h.MissingCheckoutConfig);return r=n.paymentSettings.bigpayBaseUrl,[4,(i=this._hostedFormFactory.create(r,e)).attach()];case 1:return o.sent(),[2,i]}}))}))},e.prototype._processAdditionalAction=function(e,t,n,r){return void 0===n&&(n=!1),void 0===r&&(r=!1),(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u,d,l,p,h,m,_;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!(e instanceof x))throw e;if(i=(0,Z.some)(e.body.errors,{code:"additional_action_required"}),o=(0,Z.some)(e.body.errors,{code:"three_d_secure_required"}),i&&(a=e.body.additional_action_required)&&"redirect_to_url"===a.type)return[2,new Promise((function(){a.data.redirect_url&&window.location.replace(a.data.redirect_url)}))];if(!o)return[3,8];c=e.body.three_ds_result.token,u=!1,d=!1,l=void 0,s.label=1;case 1:return s.trys.push([1,3,,4]),[4,this._getStripeJs().confirmCardPayment(c)];case 2:return l=s.sent(),[3,4];case 3:return s.sent(),d=!0,[3,4];case 4:if(null==l?void 0:l.error){if(this._isCancellationError(l.error))throw new uu;if(this._isAuthError(l.error))throw new Pp(Ip.AuthFailure);throw new Error(l.error.message)}p=this._getPaymentToken(null==l?void 0:l.paymentIntent,c,d),h={credit_card_token:{token:p},vault_payment_instrument:n,confirm:u},m=this._buildPaymentPayload(t,h,r),s.label=5;case 5:return s.trys.push([5,7,,8]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment(m))];case 6:return[2,s.sent()];case 7:throw _=s.sent(),this._handleEmptyPaymentIntentError(_,null==l?void 0:l.error);case 8:throw e}}))}))},e.prototype._getPaymentToken=function(e,t,n){return!e||n?t:e.id},e.prototype._shouldShowTSVHostedForm=function(e,t){return this._isHostedFieldAvailable()&&this._isHostedPaymentFormEnabled(e,t)},e.prototype._unmountElement=function(){this._stripeElement&&(this._stripeElement.unmount(),this._stripeElement=void 0)},e}();const Op=Ap,kp=function(){function e(e,t){void 0===t&&(t=window),this._scriptLoader=e,this._window=t}return e.prototype.load=function(e,t,n){var r=this;return this._scriptLoader.loadScript("https://js.stripe.com/v3/").then((function(){if(!r._window.Stripe)throw new gi;return r._window.Stripe(e,{stripeAccount:t,locale:n,betas:["payment_intent_beta_3","alipay_pm_beta_1"],apiVersion:"2020-03-02;alipay_beta=v1"})}))},e}(),Tp=function(){function e(e){this._scriptLoader=e}return e.prototype.initialize=function(){var e=this;return this._scriptLoader.loadScript("//static.wepay.com/min/js/risk.1.latest.js").then((function(){return e._riskClient=window.WePay.risk})).then((function(){return e}))},e.prototype.getRiskToken=function(){if(!this._riskClient)throw new Pn(bn.PaymentNotInitialized);return this._riskClient.generate_risk_token(),this._riskClient.get_risk_token()},e}(),Mp=function(e){function t(t,n,r,i,o){var a=e.call(this,t,n,r,i)||this;return a._wepayRiskClient=o,a}return(0,s.__extends)(t,e),t.prototype.initialize=function(t){return this._wepayRiskClient.initialize(),e.prototype.initialize.call(this,t)},t.prototype.execute=function(t,n){var r=this._wepayRiskClient.getRiskToken(),i=(0,Z.merge)({},t,{payment:{paymentData:{deviceSessionId:r}}});return e.prototype.execute.call(this,i,n)},t}(wu);var Dp,Rp="Payment cannot continue",zp=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return(0,s.__extends)(t,e),t.prototype.initialize=function(t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){if(this._initializeOptions=t&&t.worldpay,!this._initializeOptions)throw new Pn(bn.PaymentNotInitialized);return[2,e.prototype.initialize.call(this,t)]}))}))},t.prototype.execute=function(t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(r=t.payment,Dp=this._submitAdditionalAction(),!r)throw new cu(["payment"]);o.label=1;case 1:return o.trys.push([1,3,,5]),[4,e.prototype.execute.call(this,t,n)];case 2:return[2,o.sent()];case 3:return i=o.sent(),[4,this._processAdditionalAction(i,r)];case 4:return[2,o.sent()];case 5:return[2]}}))}))},t.prototype._processAdditionalAction=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n=this;return(0,s.__generator)(this,(function(r){return e instanceof x&&(0,Z.some)(e.body.errors,{code:"additional_action_required"})?[2,new Promise((function(r,i){var o,a=function(e){return(0,s.__awaiter)(n,void 0,void 0,(function(){var n,u,d,l,p,h;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if("string"!=typeof e.data||!this._isValidJsonWithSessionId(e.data))return[2,i(new Error(Rp))];window.removeEventListener("message",a),window.removeEventListener("remove_event_message",c),o.remove(),n=JSON.parse(e.data),u=(0,Z.merge)({},t,{paymentData:{threeDSecure:{token:n.SessionId}}}),s.label=1;case 1:return s.trys.push([1,3,,4]),d=r,[4,Dp(u)];case 2:return d.apply(void 0,[s.sent()]),[3,4];case 3:if(!((l=s.sent())instanceof x&&(0,Z.some)(l.body.errors,{code:"three_d_secure_required"})))return[2,i(l)];if(!this._initializeOptions)return[2,i(new Pn(bn.PaymentNotInitialized))];p=this._initializeOptions.onLoad,h=this._createIframe(l.body.three_ds_result);try{p(h,(function(){return i(new Error("Payment was cancelled"))}))}catch(e){i(new Error(Rp))}return[3,4];case 4:return[2]}}))}))},c=function(){return window.removeEventListener("remove_event_message",c),window.removeEventListener("message",a),o.remove(),i(new Error(Rp))};window.addEventListener("message",a),window.addEventListener("remove_event_message",c);try{o=n._createHiddenIframe(e.body)}catch(e){throw window.removeEventListener("remove_event_message",c),window.removeEventListener("message",a),new Error(Rp)}}))]:[2,Promise.reject(e)]}))}))},t.prototype._createHiddenIframe=function(e){var t=document.createElement("iframe");if(!t)throw new Error;if(document.body.appendChild(t),!t.contentWindow)throw new Error;t.id="worldpay_hosted_hidden_payment_page",t.height="0px",t.width="0px";var n=document.createElement("form"),r="collectionForm";n.id=r,n.name="devicedata",n.method="post";var i=e.additional_action_required.data.redirect_url;n.action=i;var o=document.createElement("input");o.name="Bin",o.type="hidden",o.value=e.provider_data.source_id,n.appendChild(o);var a=document.createElement("input");a.name="JWT",a.type="hidden",a.value=e.provider_data.data,n.appendChild(a);var s=document.createElement("button");s.type="submit",s.id="btnsubmit",n.appendChild(s),navigator.userAgent.match("Firefox")?t.srcdoc=n.outerHTML:t.contentWindow.document.body.appendChild(n);var c=document.createElement("script");return c.innerHTML="\n const data = new URLSearchParams()\n data.append('Bin', '"+e.provider_data.source_id+"');\n data.append('JWT', '"+e.provider_data.data+"');\n\n window.parent.fetch('"+i+"', {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: data\n })\n .then((response) => {\n if (!response.ok) {\n window.parent.dispatchEvent(new Event('remove_event_message'));\n } else {\n document.getElementById('"+r+"').submit();\n }\n })\n .catch((error) => {\n window.parent.dispatchEvent(new Event('remove_event_message'));\n })\n ",t.contentWindow.document.body.appendChild(c),t},t.prototype._createIframe=function(e){var t=document.createElement("form");t.id="challengeForm",t.method="POST",t.action=e.acs_url;var n=document.createElement("input");n.name="JWT",n.type="hidden",n.value=e.payer_auth_request,t.appendChild(n);var r=document.createElement("input");r.name="MD",r.type="hidden",r.value="merchantSessionId="+e.merchant_data,t.appendChild(r);var i=document.createElement("script");i.type="text/javascript",i.innerHTML="window.onload = function() { document.getElementById('challengeForm').submit(); }";var o=document.createElement("iframe");return o.name="worldpay_hosted_payment_page",o.height="400",o.width="100%",o.srcdoc=t.outerHTML+" "+i.outerHTML,o},t.prototype._submitAdditionalAction=function(){var e=this;if(this._shouldRenderHostedForm){if(!this._hostedForm||!this._hostedForm.submit)throw new Pn(bn.PaymentNotInitialized);var t=this._hostedForm;return function(n){return(0,s.__awaiter)(e,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){switch(e.label){case 0:return[4,t.submit(n)];case 1:return e.sent(),[2,this._store.getState()]}}))}))}}return function(t){return(0,s.__awaiter)(e,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){return[2,this._store.dispatch(this._paymentActionCreator.submitPayment(t))]}))}))}},t.prototype._isValidJsonWithSessionId=function(e){try{return!!JSON.parse(e).SessionId}catch(e){return!1}},t}(wu);const Np=zp;var Lp=function(){function e(e,t,n,r,i,o,a){this._store=e,this._paymentMethodActionCreator=t,this._storeCreditActionCreator=n,this._remoteCheckoutActionCreator=r,this._orderActionCreator=i,this._storefrontPaymentRequestSender=o,this._paymentActionCreator=a}return e.prototype.initialize=function(){return Promise.resolve(this._store.getState())},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d,l,p,_;return(0,s.__generator)(this,(function(y){switch(y.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!n)throw new cu(["payment"]);return i=n.methodId,[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(i,t))];case 1:if(o=y.sent().paymentMethods.getPaymentMethodOrThrow,a=o(i),c=a.clientToken,u=a.initializationData,d=(void 0===u?{}:u).redirectUrl,!c||!d)throw new m(h.MissingPaymentMethod);if(!(l=JSON.parse(c).id))throw new m(h.MissingPaymentToken);return p=this._store.getState().checkout.getCheckoutOrThrow().isStoreCreditApplied,[4,this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(p))];case 2:return y.sent(),[4,this._store.dispatch(this._remoteCheckoutActionCreator.initializePayment(i,{useStoreCredit:p}))];case 3:return y.sent(),[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 4:return y.sent(),[4,this._prepareForReferredRegistration(i,l)];case 5:y.sent(),y.label=6;case 6:return y.trys.push([6,8,,9]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment({methodId:i,paymentData:{nonce:l}}))];case 7:return[2,y.sent()];case 8:if((_=y.sent())instanceof x&&"additional_action_required"===_.body.status)return[2,new Promise((function(){return window.location.replace(d)}))];throw _;case 9:return[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype.deinitialize=function(){return Promise.resolve(this._store.getState())},e.prototype._prepareForReferredRegistration=function(e,t){return this._storefrontPaymentRequestSender.saveExternalId(e,t)},e}();const Fp=Lp;var Bp;!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"}(Bp||(Bp={}));var Up=function(){function e(e){this._instrumentRequestSender=e}return e.prototype.loadInstruments=function(){var e=this;return function(t){return u.Observable.create((function(n){n.next((0,c.createAction)(Bp.LoadInstrumentsRequested));var r=e._getSessionContext(t),i=e._getCurrentAccessToken(t),o=e._getShippingAddress(t);return e._getValidAccessToken(i).then((function(t){return e._instrumentRequestSender.loadInstruments((0,s.__assign)((0,s.__assign)({},r),{authToken:t.vaultAccessToken}),o).then((function(e){var r=e.body;n.next((0,c.createAction)(Bp.LoadInstrumentsSucceeded,r,t)),n.complete()}))})).catch((function(e){n.error((0,c.createErrorAction)(Bp.LoadInstrumentsFailed,e))}))}))}},e.prototype.deleteInstrument=function(e){var t=this;return function(n){return u.Observable.create((function(r){r.next((0,c.createAction)(Bp.DeleteInstrumentRequested,void 0,{instrumentId:e}));var i=t._getSessionContext(n),o=t._getCurrentAccessToken(n);return t._getValidAccessToken(o).then((function(n){return t._instrumentRequestSender.deleteInstrument((0,s.__assign)((0,s.__assign)({},i),{authToken:n.vaultAccessToken}),e).then((function(t){var i=t.body;r.next((0,c.createAction)(Bp.DeleteInstrumentSucceeded,i,(0,s.__assign)({instrumentId:e},n))),r.complete()}))})).catch((function(t){r.error((0,c.createErrorAction)(Bp.DeleteInstrumentFailed,t,{instrumentId:e}))}))}))}},e.prototype._isValidVaultAccessToken=function(e){return!(!e||!e.vaultAccessToken)&&function(e){return e.valueOf()>Date.now()}((t=new Date(e.vaultAccessExpiry),2,(n=new Date(t.getTime())).setMinutes(t.getMinutes()+2),n));var t,n},e.prototype._getCurrentAccessToken=function(e){var t=e.getState().instruments.getInstrumentsMeta();if(t)return{vaultAccessToken:t.vaultAccessToken,vaultAccessExpiry:t.vaultAccessExpiry}},e.prototype._getValidAccessToken=function(e){return e&&this._isValidVaultAccessToken(e)?Promise.resolve(e):this._instrumentRequestSender.getVaultAccessToken().then((function(e){return e.body}))},e.prototype._getShippingAddress=function(e){var t=e.getState(),n=t.shippingAddress.getShippingAddresses();return n.length>1?n:t.shippingAddress.getShippingAddress()},e.prototype._getSessionContext=function(e){var t=e.getState(),n=t.config.getStoreConfig(),r=t.cart.getCart();if(!n)throw new m(h.MissingCheckoutConfig);if(!r)throw new m(h.MissingCart);return{customerId:r.customerId,storeId:n.storeProfile.storeId,currencyCode:(n.shopperCurrency.isTransactional?n.shopperCurrency:n.currency).code}},e}();const xp=Up;var qp=function(){function e(){}return e.prototype.transformResponse=function(e){var t=this._transformResponse(e),n=t.body,r=(0,s.__rest)(t,["body"]);return(0,s.__assign)((0,s.__assign)({},r),{body:{vaultedInstruments:this._transformVaultedInstruments(n.vaulted_instruments)}})},e.prototype.transformErrorResponse=function(e){return this._transformResponse(e)},e.prototype.transformVaultAccessResponse=function(e){return(0,s.__assign)((0,s.__assign)({},e),{body:{vaultAccessToken:e.body.data.token,vaultAccessExpiry:e.body.data.expires_at}})},e.prototype._transformVaultedInstruments=function(e){var t=this;return void 0===e&&(e=[]),e.map((function(e){return t._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):t._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)}))},e.prototype._isPayPalInstrument=function(e){return"paypal"===e.method_type},e.prototype._isBankInstrument=function(e){return"bank"===e.method_type},e.prototype._transformResponse=function(e){var t=e.data,n=(0,s.__rest)(e,["data"]);return(0,s.__assign)((0,s.__assign)({},n),{body:t})},e}();const Vp=qp;var Gp=function(){function e(e,t){this._client=e,this._requestSender=t,this._transformer=new Vp}return e.prototype.getVaultAccessToken=function(e){var t=(void 0===e?{}:e).timeout;return this._requestSender.get("/internalapi/v1/checkout/payments/vault-access-token",{timeout:t}).then((function(e){return(0,s.__assign)((0,s.__assign)({},e),{body:{vaultAccessToken:e.body.data.token,vaultAccessExpiry:e.body.data.expires_at}})}))},e.prototype.loadInstruments=function(e,t){return t?this._loadInstrumentsWithAddress(e,t):this._loadInstruments(e)},e.prototype.deleteInstrument=function(e,t){var n=this,r=(0,s.__assign)((0,s.__assign)({},e),{instrumentId:t});return new Promise((function(e,t){n._client.deleteShopperInstrument(r,(function(r,i){return r?t(n._transformer.transformErrorResponse(r)):e(n._transformer.transformResponse(i))}))}))},e.prototype._loadInstruments=function(e){var t=this;return new Promise((function(n,r){t._client.loadInstruments(e,(function(e,i){return e?r(t._transformer.transformErrorResponse(e)):n(t._transformer.transformResponse(i))}))}))},e.prototype._loadInstrumentsWithAddress=function(e,t){var n=this,r=(0,s.__assign)((0,s.__assign)({},e),{shippingAddress:Array.isArray(t)?t.map((function(e){return ar(e)})):ar(t)});return new Promise((function(e,t){n._client.loadInstrumentsWithAddress(r,(function(r,i){return r?t(n._transformer.transformErrorResponse(r)):e(n._transformer.transformResponse(i))}))}))},e}();const Hp=Gp;var Yp;!function(e){e.LoadPickupOptionsRequested="LOAD_PICKUP_OPTIONS_REQUESTED",e.LoadPickupOptionsSucceeded="LOAD_PICKUP_OPTIONS_SUCCEEDED",e.LoadPickupOptionsFailed="LOAD_PICKUP_OPTIONS_FAILED"}(Yp||(Yp={}));const jp=function(){function e(e){this._pickupOptionRequestSender=e}return e.prototype.loadPickupOptions=function(e){var t=this;return function(n){return new u.Observable((function(r){var i=t._hydrateApiQuery(n,e);r.next((0,c.createAction)(Yp.LoadPickupOptionsRequested)),t._pickupOptionRequestSender.fetchPickupOptions(i).then((function(t){r.next((0,c.createAction)(Yp.LoadPickupOptionsSucceeded,t.body.results,e)),r.complete()})).catch((function(e){r.error((0,c.createErrorAction)(Yp.LoadPickupOptionsFailed,e))}))}))}},e.prototype._hydrateApiQuery=function(e,t){var n=e.getState(),r=n.cart.getCartOrThrow();if(!r)throw new m(h.MissingCart);var i=n.consignments.getConsignmentById(t.consignmentId);if(!i)throw new m(h.MissingConsignments);var o=i.lineItemIds,a=r.lineItems.physicalItems.filter((function(e){return(0,Z.includes)(o,e.id)})).map((function(e){return{variantId:e.variantId,quantity:e.quantity}}));return{searchArea:t.searchArea,items:a}},e}(),Wp=function(){function e(e){this._requestSender=e}return e.prototype.fetchPickupOptions=function(e){return this._requestSender.post("/api/storefront/pickup-options",{headers:(0,s.__assign)({Accept:w.Json},C),body:e})},e}();var Kp;!function(e){e.LoadShippingCountriesRequested="LOAD_SHIPPING_COUNTRIES_REQUESTED",e.LoadShippingCountriesSucceeded="LOAD_SHIPPING_COUNTRIES_SUCCEEDED",e.LoadShippingCountriesFailed="LOAD_SHIPPING_COUNTRIES_FAILED"}(Kp||(Kp={}));const Jp=function(){function e(e){this._shippingCountryRequestSender=e}return e.prototype.loadCountries=function(e){var t=this;return u.Observable.create((function(n){n.next((0,c.createAction)(Kp.LoadShippingCountriesRequested)),t._shippingCountryRequestSender.loadCountries(e).then((function(e){n.next((0,c.createAction)(Kp.LoadShippingCountriesSucceeded,e.body.data)),n.complete()})).catch((function(e){n.error((0,c.createErrorAction)(Kp.LoadShippingCountriesFailed,e))}))}))},e}();var Zp=function(){function e(e,t){this._requestSender=e,this._config=t}return e.prototype.loadCountries=function(e){var t=(void 0===e?{}:e).timeout,n=(0,s.__assign)({"Accept-Language":this._config.locale},C);return this._requestSender.get("/internalapi/v1/shipping/countries",{headers:n,timeout:t})},e}();const Qp=Zp;var Xp;!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"}(Xp||(Xp={}));const $p=function(){function e(e){this._strategyRegistry=e}return e.prototype.updateAddress=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o=r.getState().payment.getPaymentId(),a=t&&t.methodId||o&&o.providerId;i.next((0,c.createAction)(Xp.UpdateAddressRequested,void 0,{methodId:a})),n._strategyRegistry.get(a).updateAddress(e,(0,s.__assign)((0,s.__assign)({},t),{methodId:a})).then((function(){i.next((0,c.createAction)(Xp.UpdateAddressSucceeded,void 0,{methodId:a})),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(Xp.UpdateAddressFailed,e,{methodId:a}))}))}))}},e.prototype.selectOption=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o=r.getState().payment.getPaymentId(),a=t&&t.methodId||o&&o.providerId;i.next((0,c.createAction)(Xp.SelectOptionRequested,void 0,{methodId:a})),n._strategyRegistry.get(a).selectOption(e,(0,s.__assign)((0,s.__assign)({},t),{methodId:a})).then((function(){i.next((0,c.createAction)(Xp.SelectOptionSucceeded,void 0,{methodId:a})),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(Xp.SelectOptionFailed,e,{methodId:a}))}))}))}},e.prototype.initialize=function(e){var t=this;return function(n){return u.Observable.create((function(r){var i=n.getState(),o=i.payment.getPaymentId(),a=e&&e.methodId||o&&o.providerId,u=(0,s.__assign)((0,s.__assign)({},e),{methodId:a});if(a&&i.shippingStrategies.isInitialized(a))return r.complete();r.next((0,c.createAction)(Xp.InitializeRequested,void 0,{methodId:a})),t._strategyRegistry.get(a).initialize(u).then((function(){r.next((0,c.createAction)(Xp.InitializeSucceeded,void 0,{methodId:a})),r.complete()})).catch((function(e){r.error((0,c.createErrorAction)(Xp.InitializeFailed,e,{methodId:a}))}))}))}},e.prototype.deinitialize=function(e){var t=this;return function(n){return u.Observable.create((function(r){var i=n.getState(),o=i.payment.getPaymentId(),a=e&&e.methodId||o&&o.providerId;if(a&&!i.shippingStrategies.isInitialized(a))return r.complete();r.next((0,c.createAction)(Xp.DeinitializeRequested,void 0,{methodId:a})),t._strategyRegistry.get(a).deinitialize((0,s.__assign)((0,s.__assign)({},e),{methodId:a})).then((function(){r.next((0,c.createAction)(Xp.DeinitializeSucceeded,void 0,{methodId:a})),r.complete()})).catch((function(e){r.error((0,c.createErrorAction)(Xp.DeinitializeFailed,e,{methodId:a}))}))}))}},e.prototype.widgetInteraction=function(e,t){return u.Observable.create((function(n){var r={methodId:t&&t.methodId};n.next((0,c.createAction)(Xp.WidgetInteractionStarted,void 0,r)),e().then((function(){n.next((0,c.createAction)(Xp.WidgetInteractionFinished,void 0,r)),n.complete()})).catch((function(e){n.error((0,c.createErrorAction)(Xp.WidgetInteractionFailed,e,r))}))}))},e}();var eh=function(){function e(e,t,n,r,i){this._store=e,this._consignmentActionCreator=t,this._paymentMethodActionCreator=n,this._amazonPayV2PaymentProcessor=r,this._shippingStrategyActionCreator=i}return e.prototype.updateAddress=function(e,t){var n=this._store.getState().shippingAddress.getShippingAddress();if(!n)throw new m(h.MissingShippingAddress);var r=(0,s.__assign)((0,s.__assign)({},n),{customFields:e.customFields});return this._store.dispatch(this._consignmentActionCreator.updateAddress(r,t))},e.prototype.selectOption=function(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))},e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.amazonpay,n=e.methodId,!t||!n)throw new ae('Unable to proceed because "options.amazonpay" argument is not provided.');return[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n))];case 1:return r=s.sent(),i=r.paymentMethods.getPaymentMethodOrThrow(n),[4,this._amazonPayV2PaymentProcessor.initialize(i)];case 2:return s.sent(),o=i.initializationData,a=o.paymentToken,c=o.region,u=t.editAddressButtonId,a&&u&&(d=this._shouldShowLoadingSpinner(c),this._bindEditButton(u,a,"changeAddress",d)),[2,this._store.getState()]}}))}))},e.prototype.deinitialize=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){switch(e.label){case 0:return[4,this._amazonPayV2PaymentProcessor.deinitialize()];case 1:return e.sent(),[2,Promise.resolve(this._store.getState())]}}))}))},e.prototype._bindEditButton=function(e,t,n,r){var i=this,o=document.getElementById(e);if(o&&o.parentNode){if(r){var a=o.cloneNode(!0);o.parentNode.replaceChild(a,o),a.addEventListener("click",(function(){return i._showLoadingSpinner()}))}this._amazonPayV2PaymentProcessor.bindButton(e,t,n)}},e.prototype._showLoadingSpinner=function(){return this._store.dispatch(this._shippingStrategyActionCreator.widgetInteraction((function(){return new Promise(u.noop)})),{queueId:"widgetInteraction"})},e.prototype._shouldShowLoadingSpinner=function(e){return"us"!==e},e}();const th=eh,nh=function(){function e(e,t){this._store=e,this._consignmentActionCreator=t}return e.prototype.updateAddress=function(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))},e.prototype.selectOption=function(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))},e.prototype.initialize=function(){return Promise.resolve(this._store.getState())},e.prototype.deinitialize=function(){return Promise.resolve(this._store.getState())},e}();var rh=function(){function e(e,t,n,r){this._store=e,this._stripeUPEScriptLoader=t,this._consignmentActionCreator=n,this._paymentMethodActionCreator=r}return e.prototype.updateAddress=function(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))},e.prototype.selectOption=function(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))},e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d,l,p,_,y,f,g,v,w,C,S,I,b,P,E,A,O,k,T,M,D,R,z,N,L,F,B=this;return(0,s.__generator)(this,(function(U){switch(U.label){case 0:if(!e.stripeupe)throw new ae('Unable to proceed because "options" argument is not provided.');return t=e.stripeupe,n=t.container,r=t.gatewayId,i=t.methodId,o=t.onChangeShipping,a=t.getStyles,c=t.availableCountries,u=t.getStripeState,Object.entries(e.stripeupe).forEach((function(e){var t=e[0];if(!e[1])throw new ae('Unable to proceed because "'+t+'" argument is not provided.')})),[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(r,{params:{method:i}}))];case 1:if(d=U.sent(),l=d.paymentMethods.getPaymentMethodOrThrow(i,r),p=l.initializationData,_=p.stripePublishableKey,y=p.stripeConnectedAccount,!l||!l.initializationData.stripePublishableKey||!l.clientToken)throw new m(h.MissingPaymentMethod);return f=this,[4,this._stripeUPEScriptLoader.getStripeClient(_,y)];case 2:return f._stripeUPEClient=U.sent(),v=a&&a(),w=this._store.getState(),C=w.form.getShippingAddressFields,S=w.shippingAddress.getShippingAddress,I=C([],""),g=v?{variables:{colorPrimary:v.fieldInnerShadow,colorBackground:v.fieldBackground,colorText:v.labelText,colorDanger:v.fieldErrorText,colorTextSecondary:v.labelText,colorTextPlaceholder:v.fieldPlaceholderText,spacingUnit:"4px",borderRadius:"4px"},rules:{".Input":{borderColor:v.fieldBorder,color:v.fieldText,boxShadow:v.fieldInnerShadow}}}:{variables:{spacingUnit:"4px",borderRadius:"4px"}},this._stripeElements=this._stripeUPEScriptLoader.getElements(this._stripeUPEClient,{clientSecret:l.clientToken,appearance:g}),b=S(),P=I.find((function(e){return"phone"===e.name})),E={mode:ea.SHIPPING,allowedCountries:[c],fields:{phone:"always"},validation:{phone:{required:P&&P.required?"always":"never"}},display:{name:ta.SPLIT}},b&&(A=b.stateOrProvinceCode,O=b.countryCode,k=b.lastName,T=b.firstName,M=b.phone,D=b.address1,R=b.address2,z=b.city,N=b.postalCode,L=A&&O?u(O,A):A,E=(0,s.__assign)((0,s.__assign)({},E),{defaultValues:{firstName:T,lastName:k,phone:M,address:{line1:D,line2:R,city:z,state:L,postal_code:N,country:O}}})),(F=this._stripeElements.getElement(ia.SHIPPING))&&F.destroy(),(F=this._stripeElements.create(ia.SHIPPING,E)).on("change",(function(e){if(!("isNewAddress"in e))throw new m(h.MissingShippingAddress);(e.complete||e.isNewAddress)&&(B.sendData&&clearTimeout(B.sendData),B.sendData=setTimeout((function(){o((0,s.__assign)((0,s.__assign)({},e),{phoneFieldRequired:!!P&&P.required}))}),1e3))})),F.mount("#"+n),[2,Promise.resolve(this._store.getState())]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve(this._store.getState())},e}();const ih=rh;var oh;!function(e){e.SendSignInEmailRequested="SEND_SIGNIN_EMAIL_REQUESTED",e.SendSignInEmailSucceeded="SEND_SIGNIN_EMAIL_SUCCEEDED",e.SendSignInEmailFailed="SEND_SIGNIN_EMAIL_FAILED"}(oh||(oh={}));var ah=function(){function e(e){this._requestSender=e}return e.prototype.sendSignInEmail=function(e,t){var n=this;return(0,u.concat)((0,u.of)((0,c.createAction)(oh.SendSignInEmailRequested)),(0,u.defer)((function(){return(0,s.__awaiter)(n,void 0,void 0,(function(){var n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._requestSender.sendSignInEmail(e,t)];case 1:return n=r.sent().body,[2,(0,c.createAction)(oh.SendSignInEmailSucceeded,n)]}}))}))}))).pipe((0,d.catchError)((function(e){return l(oh.SendSignInEmailFailed,e)})))},e}();const sh=ah;var ch=function(){function e(e){this._requestSender=e}return e.prototype.sendSignInEmail=function(e,t){var n=e.email,r=e.redirectUrl,i=(void 0===t?{}:t).timeout,o=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.post("/login.php?action=passwordless_login",{body:{email:n,redirect_url:r||hn(window.top.location.href).pathname},headers:o,timeout:i})},e}();const uh=ch,dh=require("reselect");function lh(e){return function(){for(var t=[],n=0;n0}})),W=ph(x,(function(e){return function(t){return!(!t||!t.nonce)||e()===Iu||e()===bu}})),(0,z.memoizeOne)((function(e,t){return{getPaymentId:B({checkout:e,order:t}),getPaymentIdOrThrow:U({checkout:e,order:t}),getPaymentStatus:x({checkout:e,order:t}),getPaymentStatusOrThrow:q({checkout:e,order:t}),getPaymentToken:V({checkout:e,order:t}),getPaymentTokenOrThrow:G({checkout:e,order:t}),getPaymentRedirectUrl:H({checkout:e,order:t}),getPaymentRedirectUrlOrThrow:Y({checkout:e,order:t}),isPaymentDataRequired:j({checkout:e,order:t}),isPaymentDataSubmitted:W({checkout:e,order:t})}}))),Ce=function(){var e=ph((function(e){return e.errors.applyError}),(function(e){return function(){return e}})),t=ph((function(e){return!!e.statuses.isApplying}),(function(e){return function(){return e}}));return(0,z.memoizeOne)((function(n){return void 0===n&&(n=ty),{getApplyError:e(n),isApplying:t(n)}}))}(),Se=function(){var e=ph((function(e){return e.errors.updateError}),(function(e){return function(){return e}})),t=ph((function(e){return!!e.statuses.isUpdating}),(function(e){return function(){return e}}));return(0,z.memoizeOne)((function(n){return void 0===n&&(n=G_),{getUpdateError:e(n),isUpdating:t(n)}}))}(),Ie=(K=ph((function(e){return e.data}),(function(e){return function(){return e}})),J=ph((function(e){return e.errors.sendError}),(function(e){return function(){return e}})),Q=ph((function(e){return!!e.statuses.isSending}),(function(e){return function(){return e}})),(0,z.memoizeOne)((function(e){return void 0===e&&(e=z_),{getEmail:K(e),getSendError:J(e),isSending:Q(e)}}))),be=function(){var e=ph((function(e){return e.data}),(function(e){return function(){return e}})),t=ph((function(e){return e.data}),(function(e){return function(t){return null==e?void 0:e.find((function(e){return e.region===t}))}})),n=ph((function(e){return e.errors.loadError}),(function(e){return function(){return e}})),r=ph((function(e){return e.statuses.isLoading}),(function(e){return function(){return!!e}}));return(0,z.memoizeOne)((function(i){return void 0===i&&(i=wm),{getExtensions:e(i),getExtensionByRegion:t(i),getLoadError:n(i),isLoading:r(i)}}))}();return function(e,t){void 0===t&&(t={});var n,r=X(e.billingAddress),i=$(e.cart),o=ee(e.checkoutButton),a=ne(e.countries),s=re(e.coupons),c=ie(e.customer),u=oe(e.customerStrategies),d=be(e.extensions),l=ce(e.formFields),p=ae(e.giftCertificates),h=se(e.instruments),m=ve(e.orderBillingAddress),_=ue(e.paymentMethods),y=de(e.paymentStrategies),f=le(e.pickupOptions),g=pe(e.remoteCheckout),v=he(e.consignments),w=me(e.shippingCountries),C=_e(e.shippingStrategies),S=Se(e.subscriptions),I=Ce(e.storeCredit),b=Ie(e.signInEmail),P=ye(e.consignments,i),E=fe(e.checkout,r,i,P,s,c,p),A=ge(e.order,m,s),O=we(E,A),k={billingAddress:r,cart:i,checkout:E,checkoutButton:o,config:te(e.config,e.formFields),consignments:P,countries:a,coupons:s,customer:c,customerStrategies:u,extensions:d,form:l,giftCertificates:p,instruments:h,order:A,orderBillingAddress:m,payment:O,paymentMethods:_,paymentStrategies:y,pickupOptions:f,remoteCheckout:g,shippingAddress:v,shippingCountries:w,shippingStrategies:C,signInEmail:b,subscriptions:S,storeCredit:I};return t.shouldWarnMutation?(n=k,Object.keys(n).reduce((function(e,t){return e[t]=X_(n[t]),e}),{})):k}}function ry(e,t){void 0===e&&(e={});var n,r,i=(n=new Sh,["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((function(e){n.register(e,(function(e,t){return new vh(e,t)}))})),n.register("invalid_payment_provider",(function(e){return new Te(e)})),n.register("payment_config_not_found",(function(e){return new Te(e)})),r=n,function(e){return(0,u.from)(e).pipe((0,d.catchError)((function(e){if(e instanceof Error||e.payload instanceof Error)throw e;if((n=e.payload)&&"object"==typeof n&&["body","headers","status","statusText"].every((function(e){return Object.prototype.hasOwnProperty.call(n,e)}))){var t=e.payload.body&&e.payload.body.detail;throw(0,s.__assign)((0,s.__assign)({},e),{payload:r.createError(e.payload,t)})}var n;throw e})))}),o=ny();return(0,c.createDataStore)((0,c.combineReducers)({billingAddress:kh,cart:Fh,checkout:K_,checkoutButton:Yh,config:Zh,consignments:h_,countries:Mm,coupons:tm,customer:lm,customerStrategies:ym,extensions:Cm,formFields:Em,giftCertificates:am,instruments:i_,orderBillingAddress:Vm,order:Lm,payment:Hm,paymentMethods:Wm,paymentStrategies:$m,pickupOptions:w_,remoteCheckout:d_,shippingCountries:P_,shippingStrategies:T_,signInEmail:N_,subscriptions:H_,storeCredit:x_}),e,(0,s.__assign)({actionTransformer:i,stateTransformer:function(e){return o(e)}},t))}function iy(e){"https:"!==document.location.protocol&&R().warn("The BigCommerce Checkout SDK should not be used on a non-HTTPS page"),"production"!==A()&&R().warn("Note that the development build is not optimized. To create a production build, set process.env.NODE_ENV to `production`.");var n={meta:{externalSource:e&&e.externalSource,host:null==e?void 0:e.host,locale:null==e?void 0:e.locale,variantIdentificationToken:window.checkoutVariantIdentificationToken},errors:{},statuses:{}},r=e||{},i=r.locale,s=void 0===i?"":i,c=r.shouldWarnMutation,u=void 0===c||c,d=(0,o.createRequestSender)({host:e&&e.host}),l=ry({config:n},{shouldWarnMutation:u}),p=ir(l),h=new Xn(d),m=new Vt(d),_=new F(new H(d)),y=Tn((0,a.createScriptLoader)()),f=new Br(d),v=new Lr(y,f),w=new Kn(h,new sn(m)),C=new Wr(new Jr(d)),S=new Kt(new Zt(d)),I=new Yt(m,_,S),P=ai(l),O=Gc(P,t,{useFallback:!0}),k=Mt(P),T=new la(new pa(d));return new gh(l,new g(new b(d),C),I,_,new Nt(new Ft(d),I,v),new Tr(new Rr(d),m),new xc(new Vc(d,{locale:s})),new W(new $(d)),new Ut(function(e,t,n){var r=new ce,i=(0,a.getScriptLoader)(),o=new Vt(t),s=new Yt(o,new F(new H(t)),new Kt(new Zt(t))),c=(0,xe.createFormPoster)(),u=new $t(new tn(t)),d=new wo(t),l=new Io(d,s),p=new Lr(Tn(i),new Br(t)),h=new Nt(new Ft(t),s,p),m=new Pi(new Oi(i)),_=Mt(ai(e));return r.register("googlepayadyenv2",(function(){return new jo(e,l,Yi(e,new Wi),c)})),r.register("googlepayadyenv3",(function(){return new jo(e,l,Yi(e,new Ji),c)})),r.register("amazonpay",(function(){return new Eo(e,u,l,Ci())})),r.register("braintreevisacheckout",(function(){return new Oo(e,s,u,new Ut(r,_),l,Mi(i,t),new Di(i),c)})),r.register("braintreepaypalcredit",(function(){return new Bo(e,s,h,u,m,c,window)})),r.register("chasepay",(function(){return new xo(e,u,l,new Ri(i),t,c)})),r.register("squarev2",(function(){return new $o(e,new Io(d,s))})),r.register("masterpass",(function(){return new Qo(e,u,l,new yo(i),n)})),r.register("googlepayauthorizenet",(function(){return new jo(e,l,Yi(e,new Xi),c)})),r.register("googlepaybnz",(function(){return new jo(e,l,Yi(e,new eo),c)})),r.register("googlepaybraintree",(function(){return new jo(e,l,Yi(e,new to(m)),c)})),r.register("googlepaycheckoutcom",(function(){return new jo(e,l,Yi(e,new ro(t)),c)})),r.register("googlepaycybersourcev2",(function(){return new jo(e,l,Yi(e,new oo),c)})),r.register("googlepayorbital",(function(){return new jo(e,l,Yi(e,new so),c)})),r.register("googlepaystripe",(function(){return new jo(e,l,Yi(e,new uo),c)})),r.register("googlepaystripeupe",(function(){return new jo(e,l,Yi(e,new po),c)})),r.register("googlepayworldpayaccess",(function(){return new jo(e,l,Yi(e,new mo),c)})),r.register("stripeupe",(function(){return new aa(e,new go(i),h,u,new Tr(new Rr(t),new Vt(t)))})),r.register("default",(function(){return new Vo(e,h)})),r}(l,d,s),k),new E,new ne(new ie(d)),new xp(new Hp(p,d)),w,new $t(new tn(d)),new Jc(function(e,t,n,r,i){var o=new tu(e,{defaultToken:Wc.CREDIT_CARD}),s=(0,a.getScriptLoader)(),c=new Ar,u=new nr(t),d=new g(new b(n),new Wr(new Jr(n))),l=Gc(ai(e)),p=function(e){var t=new Oi(e),n=new Pi(t),r=new Bu(n),i=new Tu;return new qu(n,r,i)}(s),h=new Vt(n),m=new sn(h),_=new Lr(r,new Br(n)),y=new Kn(new Xn(n),m),f=new qr(new Gr(n)),v=new In(Tn((0,a.createScriptLoader)())),w=new tr(u,y,c,v),C=new $t(new tn(n)),S=new wo(n),I=new F(new H(n)),P=new Kt(new Zt(n)),E=new Yt(h,I,P),A=new Io(S,E),O=new Jc(o,l,y,_),k=(0,xe.createFormPoster)(),T=Kl(k,v),M=new Yn(e),D=new ru(n);return o.register(Wc.ADYENV2_GOOGLEPAY,(function(){return new Qd(e,E,C,O,w,y,Yi(e,new Wi),new $d(e,w,new ou(s,(0,a.getStylesheetLoader)())))})),o.register(Wc.ADYENV3_GOOGLEPAY,(function(){return new Qd(e,E,C,O,w,y,Yi(e,new Ji),new tl(e,w,new su(s,(0,a.getStylesheetLoader)())))})),o.register(Wc.AFFIRM,(function(){return new lu(e,y,w,C,new pu)})),o.register(Wc.AFTERPAY,(function(){return new _u(e,m,y,w,C,S,f,new yu(s))})),o.register(Wc.AMAZONPAY,(function(){return new gu(e,O,y,w,Ci())})),o.register(Wc.AUTHORIZENET_GOOGLE_PAY,(function(){return new Qd(e,E,C,O,w,y,Yi(e,new Xi))})),o.register(Wc.BARCLAYS,(function(){return new Su(e,y,w,M,new $u(e,w,new cd(new ud(s))))})),o.register(Wc.BLUESNAPV2,(function(){return new Eu(e,y,w)})),o.register(Wc.BRAINTREE,(function(){return new Hu(e,y,w,C,p)})),o.register(Wc.BRAINTREE_GOOGLE_PAY,(function(){return new Qd(e,E,C,O,w,y,Yi(e,new to(new Pi(new Oi(s)))),void 0,new Pi(new Oi(s)))})),o.register(Wc.BRAINTREE_PAYPAL,(function(){return new Wu(e,y,w,C,p)})),o.register(Wc.BRAINTREE_VENMO,(function(){return new Ju(e,y,w,C,p)})),o.register(Wc.BRAINTREE_PAYPAL_CREDIT,(function(){return new Wu(e,y,w,C,p,!0)})),o.register(Wc.BRAINTREE_VISA_CHECKOUT,(function(){return new Qu(e,E,C,O,w,y,Mi(s,n),new Di(s))})),o.register(Wc.CBA_MPGS,(function(){return new md(e,y,w,M,C,new yd(s),i)})),o.register(Wc.CONVERGE,(function(){return new Ld(e,y,w,M,k)})),o.register(Wc.CLEARPAY,(function(){return new Rd(e,m,y,w,C,S,f,new Nd(s))})),o.register(Wc.CYBERSOURCE,(function(){return new xd(e,y,w,M,new ld(e,w,C,new cd(new ud(s))))})),o.register(Wc.CYBERSOURCEV2,(function(){return new Vd(e,y,w,M,new $u(e,w,new cd(new ud(s))))})),o.register(Wc.BNZ,(function(){return new Ou(e,y,w,M,new $u(e,w,new cd(new ud(s))))})),o.register(Wc.CYBERSOURCEV2_GOOGLE_PAY,(function(){return new Qd(e,E,C,O,w,y,Yi(e,new oo))})),o.register(Wc.BNZ_GOOGLEPAY,(function(){return new Qd(e,E,C,O,w,y,Yi(e,new eo))})),o.register(Wc.CHECKOUTCOM,(function(){return new Bd(e,y,w,M,k)})),o.register(Wc.CHECKOUTCOM_APM,(function(){return new Pd(e,y,w,M)})),o.register(Wc.CHECKOUTCOM_FAWRY,(function(){return new Ad(e,y,w,M)})),o.register(Wc.CHECKOUTCOM_GOOGLE_PAY,(function(){return new Qd(e,E,C,O,w,y,Yi(e,new ro(n)),new nl)})),o.register(Wc.CHECKOUTCOM_IDEAL,(function(){return new kd(e,y,w,M)})),o.register(Wc.CHECKOUTCOM_SEPA,(function(){return new Md(e,y,w,M)})),o.register(Wc.CHASE_PAY,(function(){return new vd(e,E,y,w,C,O,n,new Ri(s),new Tp(s))})),o.register(Wc.DIGITALRIVER,(function(){return new jd(e,C,y,w,f,new Kd(s,(0,a.getStylesheetLoader)()),d)})),o.register(Wc.KLARNA,(function(){return new cl(e,y,C,A,new ul(s))})),o.register(Wc.KLARNAV2,(function(){return new ll(e,y,A,new pl(s),new ml(n))})),o.register(Wc.HUMM,(function(){return new il(e,y,w,k,C)})),o.register(Wc.MASTERPASS,(function(){return new _l(e,y,w,new yo(s),i)})),o.register(Wc.MOLLIE,(function(){return new vl(M,e,new Cl(s),y,w)})),o.register(Wc.MONERIS,(function(){return new bl(M,e,y,w,f)})),o.register(Wc.OPY,(function(){return new Tl(e,y,C,D,w,new Nl(s))})),o.register(Wc.ORBITAL_GOOGLE_PAY,(function(){return new Qd(e,E,C,O,w,y,Yi(e,new so))})),o.register(Wc.PAYPAL,(function(){return new Fl(e,y,w,M,new ld(e,w,C,new cd(new ud(s))))})),o.register(Wc.PAYPAL_EXPRESS,(function(){return new Bl(e,y,new xl(s))})),o.register(Wc.PAYPAL_EXPRESS_CREDIT,(function(){return new Bl(e,y,new xl(s))})),o.register(Wc.PPSDK,(function(){return new Ql(e,y,np(e,y,n,T,M),new rp(n,T),new Zc("PPSDK"))})),o.register(Wc.QUADPAY,(function(){return new op(e,y,w,C,f,A,D)})),o.register(Wc.SAGE_PAY,(function(){return new ap(e,y,w,M,k)})),o.register(Wc.SQUARE,(function(){return new pp(e,E,y,w,C,O,n,new mp(s))})),o.register(Wc.STRIPE_GOOGLE_PAY,(function(){return new Qd(e,E,C,O,w,y,Yi(e,new uo))})),o.register(Wc.STRIPE_UPE_GOOGLE_PAY,(function(){return new Qd(e,E,C,O,w,y,Yi(e,new po))})),o.register(Wc.STRIPEV3,(function(){return new Op(e,C,w,y,new kp(s),f,M,i)})),o.register(Wc.STRIPE_UPE,(function(){return new vp(e,C,w,y,new go(s),f,d)})),o.register(Wc.WE_PAY,(function(){return new Mp(e,y,w,M,new Tp(s))})),o.register(Wc.WORLDPAYACCESS,(function(){return new Np(e,y,w,M)})),o.register(Wc.WORLDPAYACCESS_GOOGLE_PAY,(function(){return new Qd(e,E,C,O,w,y,Yi(e,new mo))})),o.register(Wc.ZIP,(function(){return new Fp(e,C,f,A,y,D,w)})),o}(l,p,d,y,s),O,w,v),new jp(new Wp(d)),new Jp(new Qp(d,{locale:s})),new $p(function(e,t){var n=new ce,r=new Vt(t),i=new Rr(t),o=new Tr(i,r),s=new $t(new tn(t)),c=(0,a.getScriptLoader)();return n.register("amazonpay",(function(){return new th(e,o,new $t(new tn(t)),Ci(),new $p(n))})),n.register("stripeupe",(function(){return new ih(e,new go(c),o,s)})),n.register("default",(function(){return new nh(e,o)})),n}(l,d)),new sh(new uh(d)),v,new qr(new Gr(d)),C,S,T)}function oy(e){return Object.prototype.hasOwnProperty.call(e,"cacheKey")}var ay=function(){function e(e){this._lastId=0,this._map={maps:[]},this._usedMaps=[],this._options=(0,s.__assign)({maxSize:0,isEqual:mh(),onExpire:Z.noop},e)}return e.prototype.getKey=function(){for(var e=[],t=0;t55?55:e<25?25:e}var Iy=function(){function e(e,t,n,r,i,o){this._store=e,this._checkoutActionCreator=t,this._cartRequestSender=n,this._braintreeSDKCreator=r,this._formPoster=i,this._window=o}return e.prototype.initialize=function(e){var t,n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d,l,p,_,y,f,g=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(r=e.braintreepaypal,i=e.containerId,o=e.methodId,c=(a=r||{}).messagingContainerId,u=a.onError,!o)throw new ae('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new ae('Unable to initialize payment because "options.containerId" argument is not provided.');if(!r)throw new ae('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');if(!r.buyNowInitializeOptions)return[3,1];if(d=this._store.getState(),l=d.paymentMethods.getPaymentMethodOrThrow(o),!r.currencyCode)throw new ae('Unable to initialize payment because "options.braintreepaypal.currencyCode" argument is not provided.');return p=r.currencyCode,[3,3];case 1:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 2:d=s.sent(),l=d.paymentMethods.getPaymentMethodOrThrow(o),p=d.cart.getCartOrThrow().currency.code,s.label=3;case 3:if(!l.clientToken)throw new m(h.MissingPaymentMethod);return _={currency:p,intent:null===(t=l.initializationData)||void 0===t?void 0:t.intent,isCreditEnabled:null===(n=l.initializationData)||void 0===n?void 0:n.isCreditEnabled},y=function(e){g._renderPayPalComponents(e,r,i,o,Boolean(l.config.testMode))},f=function(e){return g._handleError(e,i,c,u)},this._braintreeSDKCreator.initialize(l.clientToken),[4,this._braintreeSDKCreator.getPaypalCheckout(_,y,f)];case 4:return s.sent(),[2]}}))}))},e.prototype.deinitialize=function(){return this._braintreeSDKCreator.teardown(),Promise.resolve()},e.prototype._renderPayPalComponents=function(e,t,n,r,i){var o=t.messagingContainerId;this._renderPayPalMessages(o),this._renderPayPalButton(e,t,n,r,i)},e.prototype._renderPayPalButton=function(e,t,n,r,i){var o=this,a=t.style,s=t.shouldProcessPayment,c=t.onAuthorizeError,u=this._window.paypal,d=null==u?void 0:u.FUNDING.PAYPAL;if(u&&d){var l=a?Cy(a):{},p=u.Buttons({env:i?"sandbox":"production",commit:!1,fundingSource:d,style:l,createOrder:function(){return o._setupPayment(e,t,r)},onApprove:function(t){return o._tokenizePayment(t,e,r,s,c)}});p.isEligible()&&p.render("#"+n)}else this._removeElement(n)},e.prototype._renderPayPalMessages=function(e){var t=e&&Boolean(document.getElementById(e)),n=this._window.paypal;if(n&&t){var r=this._store.getState().cart.getCartOrThrow();n.Messages({amount:r.cartAmount,placement:"cart"}).render("#"+e)}else this._removeElement(e)},e.prototype._setupPayment=function(e,t,n){var r,i;return(0,s.__awaiter)(this,void 0,void 0,(function(){var o,a,c,u,d,l,p,h,m,_,y,f;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:o=t.buyNowInitializeOptions,a=t.shippingAddress,c=t.onPaymentError,s.label=1;case 1:return s.trys.push([1,7,,8]),d=this,[4,this._createBuyNowCart({buyNowInitializeOptions:o})];case 2:return d._buyNowCart=s.sent(),this._buyNowCart?(u=this._store.getState(),[3,5]):[3,3];case 3:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 4:u=s.sent(),s.label=5;case 5:return l=u.customer.getCustomer(),p=u.paymentMethods.getPaymentMethodOrThrow(n),h=this._buyNowCart?this._buyNowCart.cartAmount:u.checkout.getCheckoutOrThrow().outstandingBalance,m=null!==(r=t.currencyCode)&&void 0!==r?r:u.config.getStoreConfigOrThrow().currency.code,_=a||(null==l?void 0:l.addresses[0]),y=_?Mo(_):void 0,[4,e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:y,amount:h,currency:m,offerCredit:!1,intent:null===(i=p.initializationData)||void 0===i?void 0:i.intent})];case 6:return[2,s.sent()];case 7:throw f=s.sent(),c&&c(f),f;case 8:return[2]}}))}))},e.prototype._createBuyNowCart=function(e){var t=e.buyNowInitializeOptions;return(0,s.__awaiter)(this,void 0,void 0,(function(){var e;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:if("function"!=typeof(null==t?void 0:t.getBuyNowCartRequestBody))return[3,4];if(!(e=t.getBuyNowCartRequestBody()))throw new m(h.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._cartRequestSender.createBuyNowCart(e)];case 2:return[2,n.sent().body];case 3:throw n.sent(),new _y;case 4:return[2]}}))}))},e.prototype._tokenizePayment=function(e,t,n,r,i){var o;return(0,s.__awaiter)(this,void 0,void 0,(function(){var a,c,u,d,l,p;return(0,s.__generator)(this,(function(h){switch(h.label){case 0:return h.trys.push([0,3,,4]),[4,this._braintreeSDKCreator.getDataCollector({paypal:!0})];case 1:return a=h.sent().deviceData,[4,t.tokenizePayment(e)];case 2:return c=h.sent(),u=c.details,d=c.nonce,l=null===(o=this._buyNowCart)||void 0===o?void 0:o.id,this._formPoster.postForm("/checkout.php",(0,s.__assign)({payment_type:"paypal",provider:n,action:r?"process_payment":"set_external_checkout",nonce:d,device_data:a,billing_address:JSON.stringify(ko(u)),shipping_address:JSON.stringify(To(u))},l&&{cart_id:l})),[2,c];case 3:throw p=h.sent(),i&&i(p),p;case 4:return[2]}}))}))},e.prototype._handleError=function(e,t,n,r){this._removeElement(t),this._removeElement(n),r&&r(e)},e.prototype._removeElement=function(e){var t=e&&document.getElementById(e);t&&t.remove()},e}();const by=Iy;var Py=function(){function e(e,t,n,r,i,o){this._store=e,this._checkoutActionCreator=t,this._cartRequestSender=n,this._braintreeSDKCreator=r,this._formPoster=i,this._window=o}return e.prototype.initialize=function(e){var t,n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d,l,p,_=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(r=e.braintreepaypalcredit,i=e.containerId,!(o=e.methodId))throw new ae('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new ae('Unable to initialize payment because "options.containerId" argument is not provided.');if(!r)throw new ae('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');if(!r.buyNowInitializeOptions)return[3,1];if(a=this._store.getState(),c=a.paymentMethods.getPaymentMethodOrThrow(o),!r.currencyCode)throw new ae('Unable to initialize payment because "options.braintreepaypalcredit.currencyCode" argument is not provided.');return u=r.currencyCode,[3,3];case 1:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 2:a=s.sent(),c=a.paymentMethods.getPaymentMethodOrThrow(o),u=a.cart.getCartOrThrow().currency.code,s.label=3;case 3:if(!c.clientToken)throw new m(h.MissingPaymentMethod);return d={currency:u,intent:null===(t=c.initializationData)||void 0===t?void 0:t.intent,isCreditEnabled:null===(n=c.initializationData)||void 0===n?void 0:n.isCreditEnabled},l=function(e){return _._renderPayPalButton(e,r,i,o,Boolean(c.config.testMode))},p=function(e){return _._handleError(e,i,r.onError)},this._braintreeSDKCreator.initialize(c.clientToken),[4,this._braintreeSDKCreator.getPaypalCheckout(d,l,p)];case 4:return s.sent(),[2]}}))}))},e.prototype.deinitialize=function(){return this._braintreeSDKCreator.teardown(),Promise.resolve()},e.prototype._renderPayPalButton=function(e,t,n,r,i){var o=this,a=t.style,c=t.shouldProcessPayment,u=t.onAuthorizeError,d=this._window.paypal,l=!1;if(d){var p=[d.FUNDING.PAYLATER,d.FUNDING.CREDIT],h=a?Cy(a):{};p.forEach((function(a){var p=a===d.FUNDING.CREDIT?(0,s.__assign)({label:No.CREDIT},h):h;if(!l){var m=d.Buttons({env:i?"sandbox":"production",commit:!1,fundingSource:a,style:p,createOrder:function(){return o._setupPayment(e,t,r)},onApprove:function(t){return o._tokenizePayment(t,e,r,c,u)}});m.isEligible()&&(m.render("#"+n),l=!0)}}))}d&&l||this._removeElement(n)},e.prototype._setupPayment=function(e,t,n){var r,i;return(0,s.__awaiter)(this,void 0,void 0,(function(){var o,a,c,u,d,l,p,h,m,_,y,f;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:o=t.onPaymentError,a=t.shippingAddress,c=t.buyNowInitializeOptions,s.label=1;case 1:return s.trys.push([1,7,,8]),d=this,[4,this._createBuyNowCart({buyNowInitializeOptions:c})];case 2:return d._buyNowCart=s.sent(),this._buyNowCart?(u=this._store.getState(),[3,5]):[3,3];case 3:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 4:u=s.sent(),s.label=5;case 5:return l=u.customer.getCustomer(),p=u.paymentMethods.getPaymentMethodOrThrow(n),h=this._buyNowCart?this._buyNowCart.cartAmount:u.checkout.getCheckoutOrThrow().outstandingBalance,m=null!==(r=t.currencyCode)&&void 0!==r?r:u.config.getStoreConfigOrThrow().currency.code,_=a||(null==l?void 0:l.addresses[0]),y=_?Mo(_):void 0,[4,e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:y,amount:h,currency:m,offerCredit:!0,intent:null===(i=p.initializationData)||void 0===i?void 0:i.intent})];case 6:return[2,s.sent()];case 7:throw f=s.sent(),o&&o(f),f;case 8:return[2]}}))}))},e.prototype._createBuyNowCart=function(e){var t=e.buyNowInitializeOptions;return(0,s.__awaiter)(this,void 0,void 0,(function(){var e;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:if("function"!=typeof(null==t?void 0:t.getBuyNowCartRequestBody))return[3,4];if(!(e=t.getBuyNowCartRequestBody()))throw new m(h.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._cartRequestSender.createBuyNowCart(e)];case 2:return[2,n.sent().body];case 3:throw n.sent(),new _y;case 4:return[2]}}))}))},e.prototype._tokenizePayment=function(e,t,n,r,i){var o;return(0,s.__awaiter)(this,void 0,void 0,(function(){var a,c,u,d,l,p;return(0,s.__generator)(this,(function(h){switch(h.label){case 0:return h.trys.push([0,3,,4]),[4,this._braintreeSDKCreator.getDataCollector({paypal:!0})];case 1:return a=h.sent().deviceData,[4,t.tokenizePayment(e)];case 2:return c=h.sent(),u=c.details,d=c.nonce,l=null===(o=this._buyNowCart)||void 0===o?void 0:o.id,this._formPoster.postForm("/checkout.php",(0,s.__assign)({payment_type:"paypal",provider:n,action:r?"process_payment":"set_external_checkout",nonce:d,device_data:a,billing_address:JSON.stringify(ko(u)),shipping_address:JSON.stringify(To(u))},l&&{cart_id:l})),[2,c];case 3:throw p=h.sent(),i&&i(p),p;case 4:return[2]}}))}))},e.prototype._handleError=function(e,t,n){this._removeElement(t),n&&n(e)},e.prototype._removeElement=function(e){var t=e&&document.getElementById(e);t&&t.remove()},e}();const Ey=Py;var Ay={backgroundColor:"#3D95CE",backgroundPosition:"50% 50%",backgroundSize:"80px auto",backgroundImage:'url("/app/assets/img/payment-providers/venmo-logo-white.svg")',backgroundRepeat:"no-repeat",borderRadius:"4px",cursor:"pointer",transition:"0.2s ease",minHeight:"40px",minWidth:"150px",height:"100%",width:"100%"},Oy=function(){function e(e,t,n,r,i){this._store=e,this._paymentMethodActionCreator=t,this._cartRequestSender=n,this._braintreeSDKCreator=r,this._formPoster=i,this._onError=Z.noop}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.braintreevenmo,n=e.containerId,!(r=e.methodId))throw new ae('Unable to initialize payment because "options.methodId" argument is not provided.');return[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(r))];case 1:if(i=s.sent(),!(o=i.paymentMethods.getPaymentMethodOrThrow(r)).clientToken)throw new m(h.MissingPaymentMethod);if(!n)throw new ae('Unable to initialize payment because "options.containerId" argument is not provided.');return this._onError=(null==t?void 0:t.onError)||this._handleError,this._braintreeSDKCreator.initialize(o.clientToken),[4,this._braintreeSDKCreator.getVenmoCheckout((function(e){return a._handleInitializationVenmoSuccess(e,n,null==t?void 0:t.buyNowInitializeOptions)}),(function(e){return a._handleInitializationVenmoError(e,n)}))];case 2:return s.sent(),[2]}}))}))},e.prototype.deinitialize=function(){return this._braintreeSDKCreator.teardown(),Promise.resolve()},e.prototype._handleError=function(e){throw new Error(e.message)},e.prototype._handleInitializationVenmoSuccess=function(e,t,n){return this._renderVenmoButton(e,t,n)},e.prototype._handleInitializationVenmoError=function(e,t){return this._removeVenmoContainer(t),this._onError(e)},e.prototype._removeVenmoContainer=function(e){var t=document.getElementById(e);t&&t.remove()},e.prototype._renderVenmoButton=function(e,t,n){var r=this,i=document.getElementById(t);if(!i)throw new ae("Unable to create wallet button without valid container ID.");i.setAttribute("aria-label","Venmo"),Object.assign(i.style,Ay),i.addEventListener("click",(function(){return(0,s.__awaiter)(r,void 0,void 0,(function(){var t,r=this;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:return i.setAttribute("disabled","true"),[4,this._createBuyNowCart(n)];case 1:return t=o.sent(),e.tokenize&&e.tokenize((function(e,n){return(0,s.__awaiter)(r,void 0,void 0,(function(){return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return i.removeAttribute("disabled"),e?[2,this._onError(e)]:[4,this._handlePostForm(n,null==t?void 0:t.id)];case 1:return r.sent(),[2]}}))}))})),[2]}}))}))})),i.addEventListener("mouseenter",(function(){i.style.backgroundColor="#0a7fc2"})),i.addEventListener("mouseleave",(function(){i.style.backgroundColor=Ay.backgroundColor}))},e.prototype._createBuyNowCart=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:if("function"!=typeof(null==e?void 0:e.getBuyNowCartRequestBody))return[3,4];if(!(t=e.getBuyNowCartRequestBody()))throw new m(h.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._cartRequestSender.createBuyNowCart(t)];case 2:return[2,n.sent().body];case 3:throw n.sent(),new _y;case 4:return[2]}}))}))},e.prototype._handlePostForm=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:return[4,this._braintreeSDKCreator.getDataCollector()];case 1:return n=o.sent().deviceData,r=e.nonce,i=e.details,this._formPoster.postForm("/checkout.php",(0,s.__assign)({nonce:r,provider:mr.BRAINTREE_VENMO,payment_type:"paypal",device_data:n,action:"set_external_checkout",billing_address:JSON.stringify(ko(i)),shipping_address:JSON.stringify(To(i))},t&&{cart_id:t})),[2]}}))}))},e}();const ky=Oy;var Ty=function(){function e(e,t,n,r,i){this._store=e,this._formPoster=t,this._checkoutActionCreator=n,this._googlePayPaymentProcessor=r,this._cartRequestSender=i}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.containerId,n=e.methodId,r=e.currencyCode,i=this._getGooglePayOptions(e),o=i.buyNowInitializeOptions,!t||!n)throw new ye('Unable to proceed because "containerId" argument is not provided.');if(a=this._store.getState(),c=a.paymentMethods.getPaymentMethod(n),u=((null==c?void 0:c.config)||{}).testMode,this._methodId=n,this._isBuyNowFlow=!!o,!this._isBuyNowFlow)return[3,2];if(!r)throw new ye('Unable to initialize payment because "options.currencyCode" argument is not provided.');return d=i.buyNowInitializeOptions,this._googlePayPaymentProcessor.updateBuyNowFlowFlag(this._isBuyNowFlow),[4,this._googlePayPaymentProcessor.initialize(this._getMethodId(),this._getGooglePayClientOptions(r,u,d))];case 1:return s.sent(),[3,5];case 2:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 3:return s.sent(),[4,this._googlePayPaymentProcessor.initialize(this._getMethodId())];case 4:s.sent(),s.label=5;case 5:return this._walletButton=this._createSignInButton(t,i,r),[2]}}))}))},e.prototype.deinitialize=function(){return this._walletButton&&this._walletButton.parentNode&&(this._walletButton.parentNode.removeChild(this._walletButton),this._walletButton=void 0),this._googlePayPaymentProcessor.deinitialize()},e.prototype._getGooglePayClientOptions=function(e,t,n){var r=this;return{environment:t?"TEST":"PRODUCTION",paymentDataCallbacks:{onPaymentDataChanged:function(t){var i=t.callbackTrigger;return(0,s.__awaiter)(r,void 0,void 0,(function(){var t,r,o,a,c;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(i!==Ni.INITIALIZE)return[2];s.label=1;case 1:return s.trys.push([1,5,,6]),t=this,[4,this._createBuyNowCart(n)];case 2:return t._buyNowCart=s.sent(),this._buyNowCart?(r=this._buyNowCart,o=r.id,a=r.cartAmount,[4,this._store.dispatch(this._checkoutActionCreator.loadCheckout(o))]):[3,4];case 3:return s.sent(),[2,{newTransactionInfo:{currencyCode:e,totalPrice:String(a),totalPriceStatus:Li.FINAL}}];case 4:return[3,6];case 5:throw c=s.sent(),new _y(c);case 6:return[2]}}))}))}}}},e.prototype._createSignInButton=function(e,t,n){var r=this,i=document.getElementById(e),o=t.buttonType,a=t.buttonColor;if(!i)throw new ye("Unable to create sign-in button without valid container ID.");var s=this._googlePayPaymentProcessor.createButton((function(e){return r._handleWalletButtonClick(e,n)}),o,a);return i.appendChild(s),s},e.prototype._getMethodId=function(){if(!this._methodId)throw new Ee(Pe.PaymentNotInitialized);return this._methodId},e.prototype._getGooglePayOptions=function(e){if(e.methodId===mr.GOOGLEPAY_ADYENV2&&e.googlepayadyenv2)return e.googlepayadyenv2;if(e.methodId===mr.GOOGLEPAY_ADYENV3&&e.googlepayadyenv3)return e.googlepayadyenv3;if(e.methodId===mr.GOOGLEPAY_AUTHORIZENET&&e.googlepayauthorizenet)return e.googlepayauthorizenet;if(e.methodId===mr.GOOGLEPAY_BNZ&&e.googlepaybnz)return e.googlepaybnz;if(e.methodId===mr.GOOGLEPAY_BRAINTREE&&e.googlepaybraintree)return e.googlepaybraintree;if(e.methodId===mr.GOOGLEPAY_CHECKOUTCOM&&e.googlepaycheckoutcom)return e.googlepaycheckoutcom;if(e.methodId===mr.GOOGLEPAY_CYBERSOURCEV2&&e.googlepaycybersourcev2)return e.googlepaycybersourcev2;if(e.methodId===mr.GOOGLEPAY_ORBITAL&&e.googlepayorbital)return e.googlepayorbital;if(e.methodId===mr.GOOGLEPAY_STRIPE&&e.googlepaystripe)return e.googlepaystripe;if(e.methodId===mr.GOOGLEPAY_STRIPEUPE&&e.googlepaystripeupe)return e.googlepaystripeupe;if(e.methodId===mr.GOOGLEPAY_WORLDPAYACCESS&&e.googlepayworldpayaccess)return e.googlepayworldpayaccess;throw new ye},e.prototype._createBuyNowCart=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:if("function"!=typeof(null==e?void 0:e.getBuyNowCartRequestBody))return[3,4];if(!(t=e.getBuyNowCartRequestBody()))throw new me(he.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._cartRequestSender.createBuyNowCart(t)];case 2:return[2,n.sent().body];case 3:throw n.sent(),new _y;case 4:return[2]}}))}))},e.prototype._handleWalletButtonClick=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:e.preventDefault(),i.label=1;case 1:return i.trys.push([1,7,,8]),this._isBuyNowFlow&&t&&this._googlePayPaymentProcessor.updatePaymentDataRequest({transactionInfo:{currencyCode:t,totalPrice:"0",totalPriceStatus:Li.ESTIMATED},callbackIntents:[Fi.OFFER]}),[4,this._googlePayPaymentProcessor.displayWallet()];case 2:return n=i.sent(),[4,this._googlePayPaymentProcessor.handleSuccess(n)];case 3:return i.sent(),si(this._store.getState().cart.getCartOrThrow())>0&&n.shippingAddress?[4,this._googlePayPaymentProcessor.updateShippingAddress(n.shippingAddress)]:[3,5];case 4:i.sent(),i.label=5;case 5:return[4,this._onPaymentSelectComplete()];case 6:return i.sent(),[3,8];case 7:if((r=i.sent())&&"CANCELED"!==r.message)throw r;return[3,8];case 8:return[2]}}))}))},e.prototype._onPaymentSelectComplete=function(){var e,t=null===(e=this._buyNowCart)||void 0===e?void 0:e.id;this._formPoster.postForm("/checkout.php",(0,s.__assign)({headers:(0,s.__assign)({Accept:"text/html","Content-Type":"application/x-www-form-urlencoded"},C)},t&&{action:"set_external_checkout",provider:this._methodId,cart_id:t}))},(0,s.__decorate)([yn],e.prototype,"_handleWalletButtonClick",null),e}();const My=Ty,Dy=function(){function e(e,t,n,r){this._store=e,this._checkoutActionCreator=t,this._masterpassScriptLoader=n,this._locale=r}return e.prototype.initialize=function(e){var t=this,n=e.containerId,r=e.methodId;if(!n||!r)throw new ae('Unable to proceed because "containerId" argument is not provided.');return this._methodId=r,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()).then((function(e){var n=e.paymentMethods.getPaymentMethod(r);if(!n||!n.initializationData.checkoutId)throw new m(h.MissingPaymentMethod);var i={useMasterpassSrc:n.initializationData.isMasterpassSrcEnabled,language:Jo(t._locale),testMode:n.config.testMode,checkoutId:n.initializationData.checkoutId};return t._masterpassScriptLoader.load(i)})).then((function(e){t._masterpassClient=e,t._signInButton=t._createSignInButton(n)}))},e.prototype.deinitialize=function(){return this._signInButton&&this._signInButton.parentNode&&(this._signInButton.removeEventListener("click",this._handleWalletButtonClick),this._signInButton.parentNode.removeChild(this._signInButton),this._signInButton=void 0),Promise.resolve()},e.prototype._createSignInButton=function(e){var t=document.getElementById(e),n=this._store.getState(),r=this._methodId?n.paymentMethods.getPaymentMethod(this._methodId):null,i=n.config.getStoreConfig();if(!t)throw new Error("Need a container to place the button");if(!r)throw new m(h.MissingPaymentMethod);if(!i)throw new ae("Unable to retrieve store configuration");var o=document.createElement("input");if(o.type="image",r.initializationData.isMasterpassSrcEnabled){var a=r.config.testMode?"sandbox.":"",s=r.initializationData.checkoutId,c=["locale="+Jo(this._locale),"paymentmethod=master,visa,amex,discover","checkoutid="+s];o.src=["https://"+a+"src.mastercard.com/assets/img/btn/src_chk_btn_126x030px.svg",c.join("&")].join("?")}else o.src="https://static.masterpass.com/dyn/img/btn/global/mp_chk_btn_160x037px.svg";return t.appendChild(o),o.addEventListener("click",this._handleWalletButtonClick),o},e.prototype._createMasterpassPayload=function(){var e=this._store.getState(),t=e.checkout.getCheckout(),n=this._methodId?e.paymentMethods.getPaymentMethod(this._methodId):null;if(!t)throw new m(h.MissingCheckout);if(!n)throw new m(h.MissingPaymentMethod);return{checkoutId:n.initializationData.checkoutId,allowedCardTypes:n.initializationData.allowedCardTypes,amount:t.cart.cartAmount.toString(),currency:t.cart.currency.code,cartId:t.cart.id,callbackUrl:Wo("cart")}},e.prototype._handleWalletButtonClick=function(){if(!this._masterpassClient)throw new Pn(bn.CheckoutButtonNotInitialized);this._masterpassClient.checkout(this._createMasterpassPayload())},(0,s.__decorate)([yn],e.prototype,"_handleWalletButtonClick",null),e}();var Ry=function(){function e(e,t,n,r,i){void 0===i&&(i=""),this._store=e,this._checkoutActionCreator=t,this._paypalScriptLoader=n,this._formPoster=r,this._host=i}return e.prototype.initialize=function(e){var t=this,n=e.paypal,r=this._store.getState(),i=this._paymentMethod=r.paymentMethods.getPaymentMethod(e.methodId);if(!n)throw new ae;if(!i)throw new m(h.MissingPaymentMethod);return this._paypalScriptLoader.loadPaypal(i.config.merchantId).then((function(r){var o,a,c;if(!i||!i.config.merchantId)throw new m(h.MissingPaymentMethod);var u=i.config.merchantId,d=i.config.testMode?"sandbox":"production",l=((o={})[d]=n.clientId,o),p=r.FUNDING.CREDIT||"credit",_=n.allowCredit?[p]:[],y=n.allowCredit?[]:[p];return r.Button.render({env:d,client:l,commit:n.shouldProcessPayment,funding:{allowed:_,disallowed:y},style:(0,s.__assign)((0,s.__assign)({shape:Lo.RECT},(0,Z.pick)(n.style,"layout","color","label","shape","tagline","fundingicons")),{size:"paypalexpress"===i.id&&"small"===(null===(a=n.style)||void 0===a?void 0:a.size)?Ro.RESPONSIVE:null===(c=n.style)||void 0===c?void 0:c.size}),payment:function(e,r){return t._setupPayment(u,r,n.onPaymentError)},onAuthorize:function(e,r){return t._tokenizePayment(e,r,n.shouldProcessPayment,n.onAuthorizeError)}},e.containerId)}))},e.prototype.deinitialize=function(){return this._paymentMethod=void 0,Promise.resolve()},e.prototype._setupPayment=function(e,t,n){var r=this;if(!t)throw new Pn(bn.CheckoutButtonNotInitialized);return this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()).then((function(n){var i=n.cart.getCart(),o=i?i.id:"";return t.request.post(r._host+"/api/storefront/payment/paypalexpress",{merchantId:e,cartId:o},{headers:(0,s.__assign)({"X-API-INTERNAL":V},C)})})).then((function(e){return e.id})).catch((function(e){throw n&&n(e),e}))},e.prototype._tokenizePayment=function(e,t,n,r){var i=this;if(!this._paymentMethod)throw new Pn(bn.CheckoutButtonNotInitialized);if(!t)throw new Pn(bn.CheckoutButtonNotInitialized);if(!e.paymentID||!e.payerID)throw new m(h.MissingPayment);var o=this._paymentMethod.id;return t.payment.get(e.paymentID).then((function(t){i._formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:o,action:n?"process_payment":"set_external_checkout",paymentId:e.paymentID,payerId:e.payerID,payerInfo:JSON.stringify(t.payer.payer_info)})}))},e}();const zy=Ry;var Ny;!function(e){e.Subtotal="Subtotal",e.Shipping="Shipping"}(Ny||(Ny={}));var Ly=function(){function e(e,t,n){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=n,this._onAuthorizeCallback=Z.noop,this._subTotalLabel=Ny.Subtotal,this._shippingLabel=Ny.Shipping}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.methodId,n=e.containerId,r=e.applepay,ge(window),!t||!r)throw new me(he.MissingPaymentMethod);return i=r.buttonClassName,o=r.onPaymentAuthorize,a=r.buyNowInitializeOptions,c=r.requiresShipping,this._requiresShipping=c,this._buyNowInitializeOptions=a,this._onAuthorizeCallback=o,a?[3,2]:[4,this._paymentIntegrationService.loadDefaultCheckout()];case 1:s.sent(),s.label=2;case 2:return[4,this._paymentIntegrationService.loadPaymentMethod(t)];case 3:return s.sent(),u=this._paymentIntegrationService.getState(),this._paymentMethod=u.getPaymentMethodOrThrow(t),[4,this._paymentIntegrationService.verifyCheckoutSpamProtection()];case 4:return s.sent(),this._applePayButton=this._createButton(n,i),this._applePayButton.addEventListener("click",this._handleWalletButtonClick.bind(this)),[2,Promise.resolve()]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype._createButton=function(e,t){void 0===t&&(t="apple-pay-checkout-button");var n=document.getElementById(e);if(!n)throw new ye("Unable to create wallet button without valid container ID.");document.body.classList.add("apple-pay-supported");var r=document.createElement("div");return r.setAttribute("class",t),r.setAttribute("role","button"),r.setAttribute("aria-label","Apple Pay button"),n.appendChild(r),r},e.prototype._handleWalletButtonClick=function(e){var t;return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d,l,p,h,m;return(0,s.__generator)(this,(function(s){if(e.preventDefault(),!this._paymentMethod||!this._paymentMethod.initializationData)throw new me(he.MissingPaymentMethod);return this._buyNowInitializeOptions&&"function"==typeof this._buyNowInitializeOptions.getBuyNowCartRequestBody?(n=this._paymentMethod.initializationData,r=n.countryCode,i=n.currencyCode,o=n.merchantCapabilities,a=n.supportedNetworks,c=n.storeName,h=this._getRequestWithEmptyTotal(r,i,a,o),this._requiresShipping&&(null===(t=h.requiredShippingContactFields)||void 0===t||t.push("postalAddress")),m=this._sessionFactory.create(h),this._handleApplePayEvents(m,this._paymentMethod,c),m.begin()):(u=this._paymentIntegrationService.getState(),d=u.getCartOrThrow(),l=u.getStoreConfigOrThrow(),p=u.getCheckoutOrThrow(),h=this._getBaseRequest(d,p,l,this._paymentMethod),m=this._sessionFactory.create(h),this._handleApplePayEvents(m,this._paymentMethod,l.storeProfile.storeName),m.begin()),[2]}))}))},e.prototype._getRequestWithEmptyTotal=function(e,t,n,r){return{countryCode:e,currencyCode:t,supportedNetworks:n,merchantCapabilities:r,total:{label:"",amount:"0",type:"pending"},requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"]}},e.prototype._getBaseRequest=function(e,t,n,r){var i,o=n.storeProfile,a=o.storeCountryCode,s=o.storeName,c=e.currency,u=c.code,d=c.decimalPlaces,l=r.initializationData,p=l.merchantCapabilities,h=l.supportedNetworks,m=e.lineItems.physicalItems.length>0,_={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:a,currencyCode:u,merchantCapabilities:p,supportedNetworks:h,lineItems:[],total:m?{label:s,amount:""+t.grandTotal.toFixed(d),type:"pending"}:{label:s,amount:""+t.grandTotal.toFixed(d),type:"final"}};if(m)null===(i=_.requiredShippingContactFields)||void 0===i||i.push("postalAddress");else{var y=[{label:this._subTotalLabel,amount:""+t.subtotal.toFixed(d)}];t.taxes.forEach((function(e){return y.push({label:e.name,amount:""+e.amount.toFixed(d)})})),_.lineItems=y}return _},e.prototype._handleApplePayEvents=function(e,t,n){var r=this;e.onvalidatemerchant=function(n){return(0,s.__awaiter)(r,void 0,void 0,(function(){var r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this._onValidateMerchant(t,n)];case 1:return r=i.sent().body,e.completeMerchantValidation(r),[3,3];case 2:throw i.sent(),new Error("Merchant validation failed");case 3:return[2]}}))}))},this._buyNowInitializeOptions&&!this._requiresShipping&&(e.onpaymentmethodselected=function(){return(0,s.__awaiter)(r,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this._createBuyNowCart()];case 1:return t.sent(),this._handlePaymentMethodSelected(e),[2]}}))}))}),e.onshippingcontactselected=function(t){return(0,s.__awaiter)(r,void 0,void 0,(function(){return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return this._buyNowInitializeOptions&&this._requiresShipping?[4,this._createBuyNowCart()]:[3,2];case 1:r.sent(),r.label=2;case 2:return[4,this._handleShippingContactSelected(e,n,t)];case 3:return r.sent(),[2]}}))}))},e.onshippingmethodselected=function(t){return(0,s.__awaiter)(r,void 0,void 0,(function(){return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._handleShippingMethodSelected(e,n,t)];case 1:return r.sent(),[2]}}))}))},e.oncancel=function(){return(0,s.__awaiter)(r,void 0,void 0,(function(){var e;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return n.trys.push([0,3,,4]),e="/remote-checkout/"+t.id+"/signout",[4,this._requestSender.get(e)];case 1:return n.sent(),[4,this._paymentIntegrationService.loadCheckout()];case 2:return[2,n.sent()];case 3:throw n.sent(),new fe;case 4:return[2]}}))}))},e.onpaymentauthorized=function(n){return(0,s.__awaiter)(r,void 0,void 0,(function(){return(0,s.__generator)(this,(function(r){return[2,this._onPaymentAuthorized(n,e,t)]}))}))}},e.prototype._createBuyNowCart=function(){var e,t;return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:if(i.trys.push([0,3,,4]),!(n=null===(t=null===(e=this._buyNowInitializeOptions)||void 0===e?void 0:e.getBuyNowCartRequestBody)||void 0===t?void 0:t.call(e)))throw new me(he.MissingCart);return[4,this._paymentIntegrationService.createBuyNowCart(n)];case 1:return r=i.sent(),[4,this._paymentIntegrationService.loadCheckout(r.id)];case 2:return i.sent(),[3,4];case 3:throw i.sent(),new rt;case 4:return[2]}}))}))},e.prototype._handlePaymentMethodSelected=function(e){var t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow(),r=t.getStoreConfigOrThrow(),i=t.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new me(he.MissingPaymentMethod);var o=this._getBaseRequest(n,i,r,this._paymentMethod);delete o.total.type,e.completePaymentMethodSelection({newTotal:o.total,newLineItems:o.lineItems})},e.prototype._handleShippingContactSelected=function(e,t,n){var r;return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u,d,l,p,h,m,_,y;return(0,s.__generator)(this,(function(f){switch(f.label){case 0:i=this._transformContactToAddress(n.shippingContact),f.label=1;case 1:return f.trys.push([1,3,,4]),[4,this._paymentIntegrationService.updateShippingAddress(i)];case 2:return f.sent(),[3,4];case 3:throw f.sent(),e.abort(),new Error("Shipping address update failed");case 4:if(o=this._paymentIntegrationService.getState(),a=o.getCartOrThrow().currency.decimalPlaces,c=o.getCheckoutOrThrow(),u=null===(r=c.consignments[0].selectedShippingOption)||void 0===r?void 0:r.id,d=c.consignments[0].availableShippingOptions,l=null==d?void 0:d.find((function(e){return e.id===u})),p=null==d?void 0:d.filter((function(e){return e.id!==u})),h=l?[{label:l.description,amount:""+l.cost.toFixed(a),detail:l.additionalDescription,identifier:l.id}]:[],p&&(0,s.__spreadArrays)(p.filter((function(e){return e.isRecommended})),p.filter((function(e){return!e.isRecommended}))).forEach((function(e){return h.push({label:e.description,amount:""+e.cost.toFixed(a),detail:e.additionalDescription,identifier:e.id})})),!(d instanceof Array))throw new Error("Shipping options not available.");if(0===d.length)return e.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:t,amount:""+c.grandTotal.toFixed(a)},[]),[2];m=d.find((function(e){return e.isRecommended})),_=m?m.id:d[0].id,y=l?l.id:_,f.label=5;case 5:return f.trys.push([5,7,,8]),[4,this._updateShippingOption(y)];case 6:return f.sent(),[3,8];case 7:throw f.sent(),new Error("Shipping options update failed");case 8:return o=this._paymentIntegrationService.getState(),c=o.getCheckoutOrThrow(),e.completeShippingContactSelection({newShippingMethods:h,newTotal:{type:"final",label:t,amount:""+c.grandTotal.toFixed(a)},newLineItems:this._getUpdatedLineItems(c,a)}),[2]}}))}))},e.prototype._handleShippingMethodSelected=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:r=n.shippingMethod.identifier,s.label=1;case 1:return s.trys.push([1,3,,4]),[4,this._updateShippingOption(r)];case 2:return s.sent(),[3,4];case 3:throw s.sent(),e.abort(),new Error("Shipping option selection update failed.");case 4:return i=this._paymentIntegrationService.getState(),o=i.getCartOrThrow().currency.decimalPlaces,a=i.getCheckoutOrThrow(),e.completeShippingMethodSelection({newTotal:{type:"final",label:t,amount:""+a.grandTotal.toFixed(o)},newLineItems:this._getUpdatedLineItems(a,o)}),[2]}}))}))},e.prototype._getUpdatedLineItems=function(e,t){var n=[{label:this._subTotalLabel,amount:""+e.subtotal.toFixed(t)}];return e.taxes.forEach((function(e){return n.push({label:e.name,amount:""+e.amount.toFixed(t)})})),n.push({label:this._shippingLabel,amount:""+e.shippingCostTotal.toFixed(t)}),n},e.prototype._updateShippingOption=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){return[2,this._paymentIntegrationService.selectShippingOption(e)]}))}))},e.prototype._onValidateMerchant=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n;return(0,s.__generator)(this,(function(r){return n=["validationUrl="+t.validationURL,"merchantIdentifier="+e.initializationData.merchantId,"displayName="+e.initializationData.storeName,"domainName="+window.location.hostname].join("&"),[2,this._requestSender.post((i=e.initializationData.paymentsUrl,i+"/api/public/v1/payments/applepay/validate_merchant"),{credentials:!1,headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","X-XSRF-TOKEN":null},body:n})];var i}))}))},e.prototype._onPaymentAuthorized=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d,l,p,h,m,_;return(0,s.__generator)(this,(function(y){switch(y.label){case 0:r=e.payment,i=r.token,o=r.billingContact,a=r.shippingContact,c=this._paymentIntegrationService.getState(),u=c.getCartOrThrow(),d=u.lineItems.physicalItems.length>0,l={methodId:n.id,paymentData:{formattedPayload:{apple_pay_token:{payment_data:i.paymentData,payment_method:i.paymentMethod,transaction_id:i.transactionIdentifier}}}},p=this._transformContactToAddress(o),h=this._transformContactToAddress(a),m=null==a?void 0:a.emailAddress,_=(null==a?void 0:a.phoneNumber)||"",y.label=1;case 1:return y.trys.push([1,7,,8]),[4,this._paymentIntegrationService.updateBillingAddress((0,s.__assign)((0,s.__assign)({},p),{email:m,phone:_}))];case 2:return y.sent(),d?[4,this._paymentIntegrationService.updateShippingAddress(h)]:[3,4];case 3:y.sent(),y.label=4;case 4:return[4,this._paymentIntegrationService.submitOrder({useStoreCredit:!1})];case 5:return y.sent(),[4,this._paymentIntegrationService.submitPayment(l)];case 6:return y.sent(),t.completePayment(ApplePaySession.STATUS_SUCCESS),[2,this._onAuthorizeCallback()];case 7:throw y.sent(),t.completePayment(ApplePaySession.STATUS_FAILURE),new Error("Payment cannot complete");case 8:return[2]}}))}))},e.prototype._transformContactToAddress=function(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:[]}},e}();const Fy=Ly,By=le((function(e){var t=e.getState().getHost;return new Fy((0,o.createRequestSender)({host:t()}),e,new ve)}),[{id:"applepay"}]);var Uy=function(){function e(e,t,n){void 0===n&&(n=window),this.paymentIntegrationService=e,this.boltScriptLoader=t,this.boltHostWindow=n}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d,l,p,h,m;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.bolt,n=e.containerId,r=e.methodId,o=(i=t||{}).buyNowInitializeOptions,a=i.style,!r)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new ye('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new ye('Unable to initialize payment because "options.bolt" argument is not provided.');if(!Boolean(o))throw new _e("Only buy now flow is implemented for Bolt button");if(!(null==o?void 0:o.storefrontApiToken)||"string"!=typeof o.storefrontApiToken)throw new ye('Unable to initialize payment because "options.storefrontApiToken" argument is not provided.');return c=this.paymentIntegrationService.getState(),u=c.getPaymentMethodOrThrow(r),d=u.initializationData,l=u.config,h=(p=d||{}).publishableKey,m=p.developerConfig,[4,this.boltScriptLoader.loadBoltClient(h,l.testMode,m,"BigCommerce",o.storefrontApiToken)];case 1:return s.sent(),this.renderButton(n,u,a),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.renderButton=function(e,t,n){var r;"function"==typeof(null===(r=this.boltHostWindow.BoltConnect)||void 0===r?void 0:r.setupProductPageCheckout)&&(this.addButtonContainer(e,t,n),this.boltHostWindow.BoltConnect.setupProductPageCheckout())},e.prototype.addButtonContainer=function(e,t,n){var r=document.getElementById(e);if(r){var i=document.createElement("div"),o=document.createElement("object");i.setAttribute("id","product-page-checkout-wrapper"),i.setAttribute("class","bolt-button-wrapper"),i.setAttribute("style","display:none"),i.setAttribute("data-tid","product-page-checkout-wrapper"),o.setAttribute("data",this.getBoltObjectData(t,n)),o.setAttribute("class","bolt-product-checkout-button"),i.append(o),r.innerHTML="",r.append(i)}},e.prototype.getBoltObjectData=function(e,t){var n=e.initializationData,r=e.config,i=n||{},o=i.publishableKey,a=i.developerConfig,s=this.boltScriptLoader.getDomainURL(!!r.testMode,a),c=this.getButtonHeight(null==t?void 0:t.size),u=this.getButtonBorderRadius(null==t?void 0:t.shape,c);return(0,ql.stringifyUrl)({url:"https://"+s+"/v1/checkout_button",query:{publishable_key:o,variant:"ppc",height:c,border_radius:u}})},e.prototype.getButtonHeight=function(e){if(e)switch(e){case Ne.Small:return 25;case Ne.Large:return 45;case Ne.Medium:default:return 40}},e.prototype.getButtonBorderRadius=function(e,t){if(e)switch(e){case Le.Pill:return t?Math.round(t/2):void 0;case Le.Rect:default:return 4}},e}();const xy=Uy,qy=le((function(e){return new xy(e,new Be((0,a.getScriptLoader)()))}),[{id:"bolt"}]);var Vy=function(){function e(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}return e.prototype.initialize=function(e){var t;return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(n=e.paypalcommerce,r=e.containerId,i=e.methodId,o=Boolean(null==n?void 0:n.buyNowInitializeOptions),!i)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new ye('Unable to initialize payment because "options.containerId" argument is not provided.');if(!n)throw new ye('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');if(o&&!n.currencyCode)throw new ye('Unable to initialize payment because "options.paypalcommerce.currencyCode" argument is not provided.');if(o&&"function"!=typeof(null===(t=n.buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody))throw new ye('Unable to initialize payment because "options.paypalcommerce.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');return o?[3,2]:[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:s.sent(),s.label=2;case 2:return a=o?n.currencyCode:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,[4,this.paypalCommerceIntegrationService.loadPayPalSdk(i,a,!1)];case 3:return s.sent(),this.renderButton(r,i,n),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.renderButton=function(e,t,n){var r=this,i=n.buyNowInitializeOptions,o=n.style,a=n.onComplete,c=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),u=(this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t).initializationData||{}).isHostedCheckoutEnabled,d={createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommerce")},onApprove:function(e){var n=e.orderID;return r.paypalCommerceIntegrationService.tokenizePayment(t,n)}},l={onClick:function(){return r.handleClick(i)},onCancel:function(){return r.paymentIntegrationService.loadDefaultCheckout()}},p={onShippingAddressChange:function(e){return r.onShippingAddressChange(e)},onShippingOptionsChange:function(e){return r.onShippingOptionsChange(e)},onApprove:function(e,n){return r.onHostedCheckoutApprove(e,n,t,a)}},h=(0,s.__assign)((0,s.__assign)((0,s.__assign)({fundingSource:c.FUNDING.PAYPAL,style:this.paypalCommerceIntegrationService.getValidButtonStyle(o)},d),i&&l),u&&p),m=c.Buttons(h);m.isEligible()?m.render("#"+e):this.paypalCommerceIntegrationService.removeElement(e)},e.prototype.handleClick=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return e?[4,this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e)]:[3,3];case 1:return t=n.sent(),[4,this.paymentIntegrationService.loadCheckout(t.id)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},e.prototype.onHostedCheckoutApprove=function(e,t,n,r){return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!e.orderID)throw new me(he.MissingOrderId);return i=this.paymentIntegrationService.getState(),o=i.getCartOrThrow(),[4,t.order.get()];case 1:a=s.sent(),s.label=2;case 2:return s.trys.push([2,9,,10]),c=this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(a),[4,this.paymentIntegrationService.updateBillingAddress(c)];case 3:return s.sent(),o.lineItems.physicalItems.length>0?(u=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(a),[4,this.paymentIntegrationService.updateShippingAddress(u)]):[3,6];case 4:return s.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:s.sent(),s.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return s.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,e.orderID)];case 8:return s.sent(),r&&"function"==typeof r&&r(),[2,!0];case 9:throw d=s.sent(),new Error(d);case 10:return[2]}}))}))},e.prototype.onShippingAddressChange=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:t=this.paypalCommerceIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.country_code,postalCode:e.shippingAddress.postal_code,stateOrProvinceCode:e.shippingAddress.state}),i.label=1;case 1:return i.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(t)];case 2:return i.sent(),[4,this.paymentIntegrationService.updateShippingAddress(t)];case 3:return i.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return i.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return i.sent(),[3,7];case 6:throw r=i.sent(),new Error(r);case 7:return[2]}}))}))},e.prototype.onShippingOptionsChange=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:t=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(t.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:throw n=r.sent(),new Error(n);case 5:return[2]}}))}))},e}();const Gy=Vy,Hy=le((function(e){return new Gy(e,Ct(e))}),[{id:"paypalcommerce"}]);var Yy=function(){function e(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.paypalcommercecredit,n=e.containerId,r=e.methodId,o=(i=t||{}).buyNowInitializeOptions,a=i.currencyCode,c=i.messagingContainerId,u=!!o,!r)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new ye('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new ye('Unable to initialize payment because "options.paypalcommercecredit" argument is not provided.');if(u&&!a)throw new ye('Unable to initialize payment because "options.paypalcommercecredit.currencyCode" argument is not provided.');if(u&&"function"!=typeof(null==o?void 0:o.getBuyNowCartRequestBody))throw new ye('Unable to initialize payment because "options.paypalcommercecredit.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');return u?[3,2]:[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:s.sent(),s.label=2;case 2:return d=u?a:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,[4,this.paypalCommerceIntegrationService.loadPayPalSdk(r,d,!1)];case 3:return s.sent(),this.renderButton(n,r,t),this.renderMessages(c),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.renderButton=function(e,t,n){var r=this,i=n.buyNowInitializeOptions,o=n.style,a=n.onComplete,c=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),u=(this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t).initializationData||{}).isHostedCheckoutEnabled,d={createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommercecredit")},onApprove:function(e){var n=e.orderID;return r.paypalCommerceIntegrationService.tokenizePayment(t,n)}},l={onClick:function(){return r.handleClick(i)},onCancel:function(){return r.paymentIntegrationService.loadDefaultCheckout()}},p={onShippingAddressChange:function(e){return r.onShippingAddressChange(e)},onShippingOptionsChange:function(e){return r.onShippingOptionsChange(e)},onApprove:function(e,n){return r.onHostedCheckoutApprove(e,n,t,a)}},h=[c.FUNDING.PAYLATER,c.FUNDING.CREDIT],m=!1;h.forEach((function(t){if(!m){var n=(0,s.__assign)((0,s.__assign)((0,s.__assign)({fundingSource:t,style:r.paypalCommerceIntegrationService.getValidButtonStyle(o)},d),i&&l),u&&p),a=c.Buttons(n);a.isEligible()&&(a.render("#"+e),m=!0)}})),m||this.paypalCommerceIntegrationService.removeElement(e)},e.prototype.handleClick=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return e?[4,this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e)]:[3,3];case 1:return t=n.sent(),[4,this.paymentIntegrationService.loadCheckout(t.id)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},e.prototype.onHostedCheckoutApprove=function(e,t,n,r){return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!e.orderID)throw new me(he.MissingOrderId);return i=this.paymentIntegrationService.getState(),o=i.getCartOrThrow(),[4,t.order.get()];case 1:a=s.sent(),s.label=2;case 2:return s.trys.push([2,9,,10]),c=this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(a),[4,this.paymentIntegrationService.updateBillingAddress(c)];case 3:return s.sent(),o.lineItems.physicalItems.length>0?(u=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(a),[4,this.paymentIntegrationService.updateShippingAddress(u)]):[3,6];case 4:return s.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:s.sent(),s.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return s.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,e.orderID)];case 8:return s.sent(),r&&"function"==typeof r&&r(),[2,!0];case 9:throw d=s.sent(),new Error(d);case 10:return[2]}}))}))},e.prototype.onShippingAddressChange=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:t=this.paypalCommerceIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.country_code,postalCode:e.shippingAddress.postal_code,stateOrProvinceCode:e.shippingAddress.state}),i.label=1;case 1:return i.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(t)];case 2:return i.sent(),[4,this.paymentIntegrationService.updateShippingAddress(t)];case 3:return i.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return i.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return i.sent(),[3,7];case 6:throw r=i.sent(),new Error(r);case 7:return[2]}}))}))},e.prototype.onShippingOptionsChange=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:t=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(t.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:throw n=r.sent(),new Error(n);case 5:return[2]}}))}))},e.prototype.renderMessages=function(e){var t=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();if(e&&document.getElementById(e)){var n={amount:this.paymentIntegrationService.getState().getCartOrThrow().cartAmount,placement:"cart",style:{layout:"text"}};t.Messages(n).render("#"+e)}},e}();const jy=Yy,Wy=le((function(e){return new jy(e,Ct(e))}),[{id:"paypalcommercecredit"}]);var Ky=function(){function e(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.paypalcommercevenmo,n=e.containerId,r=e.methodId,o=(i=t||{}).buyNowInitializeOptions,a=i.currencyCode,c=!!o,!r)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new ye('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new ye('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');if(c&&!a)throw new ye('Unable to initialize payment because "options.paypalcommercevenmo.currencyCode" argument is not provided.');if(c&&"function"!=typeof(null==o?void 0:o.getBuyNowCartRequestBody))throw new ye('Unable to initialize payment because "options.paypalcommercevenmo.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');return c?[3,2]:[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:s.sent(),s.label=2;case 2:return u=c?a:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,[4,this.paypalCommerceIntegrationService.loadPayPalSdk(r,u,!1)];case 3:return s.sent(),this.renderButton(n,r,t),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.renderButton=function(e,t,n){var r=this,i=n.buyNowInitializeOptions,o=n.style,a=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),c=a.FUNDING.VENMO,u={createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommercevenmo")},onApprove:function(e){var n=e.orderID;return r.paypalCommerceIntegrationService.tokenizePayment(t,n)}},d={onClick:function(){return r.handleClick(i)},onCancel:function(){return r.paymentIntegrationService.loadDefaultCheckout()}},l=(0,s.__assign)((0,s.__assign)({fundingSource:c,style:this.getValidVenmoButtonStyles(o)},u),i&&d),p=a.Buttons(l);p.isEligible()?p.render("#"+e):this.paypalCommerceIntegrationService.removeElement(e)},e.prototype.getValidVenmoButtonStyles=function(e){var t=this.paypalCommerceIntegrationService.getValidButtonStyle(e);return t.color===st.gold?(0,s.__assign)((0,s.__assign)({},t),{color:void 0}):t},e.prototype.handleClick=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return e?[4,this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e)]:[3,3];case 1:return t=n.sent(),[4,this.paymentIntegrationService.loadCheckout(t.id)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},e}();const Jy=Ky,Zy=le((function(e){return new Jy(e,Ct(e))}),[{id:"paypalcommercevenmo"}]);var Qy=function(){function e(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.paypalcommercealternativemethods,n=e.containerId,r=e.methodId,o=(i=t||{}).apm,a=i.buyNowInitializeOptions,c=i.currencyCode,u=!!a,!r)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new ye('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new ye('Unable to initialize payment because "options.paypalcommercealternativemethods" argument is not provided.');if(!o)throw new ye('Unable to initialize payment because "options.paypalcommercealternativemethods.apm" argument is not provided.');if(u&&!c)throw new ye('Unable to initialize payment because "options.paypalcommercealternativemethods.currencyCode" argument is not provided.');if(u&&"function"!=typeof(null==a?void 0:a.getBuyNowCartRequestBody))throw new ye('Unable to initialize payment because "options.paypalcommercealternativemethods.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');return u?[3,2]:[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:s.sent(),s.label=2;case 2:return d=u?c:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,[4,this.paypalCommerceIntegrationService.loadPayPalSdk(r,d,!1)];case 3:return s.sent(),this.renderButton(n,r,t),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.renderButton=function(e,t,n){var r=this,i=n.apm,o=n.buyNowInitializeOptions,a=n.style,c=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();if(!Object.values(c.FUNDING).includes(i))throw new ye('Unable to initialize PayPal button because "options.paypalcommercealternativemethods.apm" argument is not valid funding source.');var u={createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommercealternativemethod")},onApprove:function(e){var n=e.orderID;return r.paypalCommerceIntegrationService.tokenizePayment(t,n)}},d={onClick:function(){return r.handleClick(o)},onCancel:function(){return r.paymentIntegrationService.loadDefaultCheckout()}},l=(0,s.__assign)((0,s.__assign)({fundingSource:i,style:this.paypalCommerceIntegrationService.getValidButtonStyle(a)},u),o&&d),p=c.Buttons(l);p.isEligible()?p.render("#"+e):this.paypalCommerceIntegrationService.removeElement(e)},e.prototype.handleClick=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return e?[4,this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e)]:[3,3];case 1:return t=n.sent(),[4,this.paymentIntegrationService.loadCheckout(t.id)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},e}();const Xy=Qy,$y=le((function(e){return new Xy(e,Ct(e))}),[{id:"paypalcommercealternativemethods"}]);var ef,tf,nf,rf,of;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(ef||(ef={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(tf||(tf={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black"}(nf||(nf={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(rf||(rf={})),function(e){e.PILL="pill",e.RECT="rect"}(of||(of={}));var af=function(){function e(e,t,n){this.paymentIntegrationService=e,this.paypalExpressScriptLoader=t,this.formPoster=n}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:if(t=this.paymentIntegrationService.getState(),n=t.getPaymentMethodOrThrow(e.methodId),!e.paypal)throw new ye;if(!n.config.merchantId)throw new me(he.MissingPaymentMethod);return[4,this.paypalExpressScriptLoader.loadPaypalSDK(n.config.merchantId)];case 1:return r=i.sent(),this.renderButton(e,r),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.renderButton=function(e,t){var n,r=this,i=e.containerId,o=e.methodId,a=e.paypal,s=a.allowCredit,c=a.clientId,u=a.onPaymentError,d=a.shouldProcessPayment,l=a.style,p=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId);if(!p.config.merchantId)throw new me(he.MissingPaymentMethod);var h=p.config.merchantId,m=p.config.testMode?"sandbox":"production",_=((n={})[m]=c,n),y=t.FUNDING.CREDIT||"credit",f=s?[y]:[],g=s?[]:[y];return t.Button.render({env:m,client:_,commit:d,funding:{allowed:f,disallowed:g},style:this.getStyle(l),payment:function(e,t){return r.setupPayment(h,t,u)},onAuthorize:function(e,t){return r.tokenizePayment(e,o,t,d)}},i)},e.prototype.getStyle=function(e){var t=e||{},n=t.color,r=t.fundingicons,i=t.label,o=t.layout,a=t.shape,s=t.size,c=t.tagline;return{color:n,fundingicons:r,label:i,layout:o,shape:a||of.RECT,size:"small"===s?tf.RESPONSIVE:s,tagline:c}},e.prototype.setupPayment=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a;return(0,s.__generator)(this,(function(c){switch(c.label){case 0:if(!t)throw new Ee(Pe.CheckoutButtonNotInitialized);c.label=1;case 1:return c.trys.push([1,4,,5]),[4,this.paymentIntegrationService.loadDefaultCheckout()];case 2:return r=c.sent(),i=r.getCartOrThrow().id,o=r.getHost()||"",[4,t.request.post(o+"/api/storefront/payment/paypalexpress",{merchantId:e,cartId:i},{headers:(0,s.__assign)({"X-API-INTERNAL":mt},yt)})];case 3:return[2,c.sent().id];case 4:throw a=c.sent(),n&&n(a),a;case 5:return[2]}}))}))},e.prototype.tokenizePayment=function(e,t,n,r){return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!n)throw new Ee(Pe.CheckoutButtonNotInitialized);if(!e.paymentID||!e.payerID)throw new me(he.MissingPayment);return i=this.paymentIntegrationService.getState(),o=i.getPaymentMethodOrThrow(t),[4,n.payment.get(e.paymentID)];case 1:return a=s.sent(),[2,this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:o.id,action:r?"process_payment":"set_external_checkout",paymentId:e.paymentID,payerId:e.payerID,payerInfo:JSON.stringify(a.payer.payer_info)})]}}))}))},e}();const sf=af;var cf=function(){function e(e){this.scriptLoader=e,this.window=window}return e.prototype.loadPaypalSDK=function(e){return void 0===e&&(e=""),(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return t=(0,s.__assign)({async:!0,attributes:{"data-merchant-id":e}},e&&{attributes:{"data-merchant-id":e}}),[4,this.scriptLoader.loadScript("//www.paypalobjects.com/api/checkout.min.js",t)];case 1:if(n.sent(),!this.window.paypal)throw new Re;return[2,this.window.paypal]}}))}))},e}();const uf=cf,df=le((function(e){return new sf(e,new uf((0,a.getScriptLoader)()),(0,xe.createFormPoster)())}),[{id:"paypalexpress"}]);function lf(e){var t=null!=e?e:{},n=t.host,r=t.locale,s=void 0===r?"en":r,c=ry(),u=(0,o.createRequestSender)({host:n}),d=(0,xe.createFormPoster)({host:n}),l=function(e,t){void 0===t&&(t=i);for(var n=new de,r=function(t){if(!oe(t))return"continue";for(var r=0,i=t.resolveIds;r6e5)&&e instanceof _f&&e.subtype===mf.MissingContent?(this._storage.removeItem(gf),this._storage.removeItem(ff),this._allowCookie()):Promise.reject()},(0,s.__decorate)([yn],e)}();const wf=vf;var Cf=function(){function e(e){this._options=e}return e.prototype.createFrame=function(e,t){var n=document.getElementById(t),r=(this._options||{}).timeout,i=void 0===r?6e4:r;if(!n)throw new _f("Unable to embed the iframe because the container element could not be found.",mf.MissingContainer);var o=document.createElement("iframe");return o.src=e,o.style.border="none",o.style.display="none",o.style.width="100%",o.allowPaymentRequest=!0,n.appendChild(o),this._toResizableFrame(o,i).catch((function(e){throw n.removeChild(o),e}))},e.prototype._toResizableFrame=function(e,t){return new Promise((function(r,i){var o=window.setTimeout((function(){i(new _f("Unable to embed the iframe because the content could not be loaded."))}),t),a=function(t){var o,a;if(t.origin===hn(e.src).origin&&(mn(t.data,pf.FrameError)&&(s(),i(new _f(t.data.payload.message,mf.MissingContent))),mn(t.data,pf.FrameLoaded))){e.style.display="";var c=(o={scrolling:!1,sizeWidth:!1,heightCalculationMethod:t.data.payload&&t.data.payload.contentId?"taggedElement":"lowestElement"},a=e,(0,n(780).iframeResizer)(o,a));s(),r(c[c.length-1])}},s=function(){window.removeEventListener("message",a),window.clearTimeout(o)};window.addEventListener("message",a)}))},e}();const Sf=Cf;var If="BigCommerce.EmbeddedCheckout";function bf(e){var t=hn(e.url).origin;return new wf(new Sf,new gn(t),new _n(t),new Gs({styles:e.styles&&e.styles.loadingIndicator}),(0,o.createRequestSender)(),new Zc(If),window.location,e).attach()}function Pf(e){if(e.payload&&e.payload.contentId){var t=document.getElementById(e.payload.contentId);t&&!t.hasAttribute("data-iframe-height")&&t.setAttribute("data-iframe-height","")}}function Ef(e){return"object"==typeof e&&null!==e&&"message"in e&&"type"in e}var Af=function(){function e(e,t,n,r){void 0===r&&(r={}),this._messageListener=e,this._messagePoster=t,this._untargetedMessagePoster=n,this._messageHandlers=r,this._messageListener.listen()}return e.prototype.postComplete=function(){var e={type:pf.CheckoutComplete};this._postMessage(e)},e.prototype.postError=function(e){var t={type:pf.CheckoutError,payload:this._transformError(e)};this._postMessage(t)},e.prototype.postFrameError=function(e){var t={type:pf.FrameError,payload:this._transformError(e)};this._postMessage(t,{untargeted:!0})},e.prototype.postFrameLoaded=function(e){var t={type:pf.FrameLoaded,payload:e};this._postMessage(t)},e.prototype.postLoaded=function(){var e={type:pf.CheckoutLoaded};this._postMessage(e)},e.prototype.postSignedOut=function(){var e={type:pf.SignedOut};this._postMessage(e)},e.prototype.receiveStyles=function(e){this._messageListener.addListener(yf.StyleConfigured,(function(t){var n=t.payload;e(n)}))},e.prototype._postMessage=function(e,t){if(this._notifyMessageHandlers(e),t&&t.untargeted)return this._untargetedMessagePoster.post(e);this._messagePoster.post(e)},e.prototype._notifyMessageHandlers=function(e){var t=this;Object.keys(this._messageHandlers).forEach((function(n){if(e.type===n){var r=t._messageHandlers[n];r&&r.call(null,e)}}))},e.prototype._transformError=function(e){return{message:e.message,type:Ef(e)?e.type:void 0,subtype:Ef(e)?e.subtype:void 0}},(0,s.__decorate)([yn],e)}();const Of=Af,kf=function(){function e(){}return e.prototype.postComplete=function(){},e.prototype.postError=function(){},e.prototype.postFrameError=function(){},e.prototype.postFrameLoaded=function(){},e.prototype.postLoaded=function(){},e.prototype.postSignedOut=function(){},e.prototype.receiveStyles=function(){},(0,s.__decorate)([yn],e)}();function Tf(e){var t;n(252);var r=e.parentWindow||window.parent;return window===r?new kf:new Of(new gn(e.parentOrigin),new _n(e.parentOrigin,r),new _n("*",r),((t={})[pf.FrameLoaded]=Pf,t))}const Mf=require("messageformat");var Df=n.n(Mf),Rf="en",zf="optimized_checkout",Nf=function(){function e(e,t){this._logger=t;var n=this._transformConfig(e),r=n.locale,i=n.locales,o=n.translations;this._locale=r,this._locales=i,this._translations=o,this._formatters={}}return e.prototype.mapKeys=function(e){var t=this;Object.keys(e).forEach((function(n){var r=zf+"."+e[n];t._translations[zf+"."+n]=t._translations[r]}))},e.prototype.getLocale=function(){return this._hasTranslations()?this._locale:Rf},e.prototype.translate=function(e,t){void 0===t&&(t={});var n=zf+"."+e;if("string"!=typeof this._translations[n])return this._logger.warn('Translation key "'+n+'" is missing'),n;if(!this._formatters[n]){var r=new(Df())(this._locales[n]);this._formatters[n]=r.compile(this._translations[n]||"")}return this._formatters[n](this._transformData(t))},e.prototype._transformConfig=function(e){void 0===e&&(e={});var t={defaultLocale:"",defaultTranslations:{},translations:{},locales:{},locale:e.locale||Rf},n=e.locales||{},r=this._flattenObject(e.translations||{}),i=this._flattenObject(e.defaultTranslations||{}),o=this._flattenObject(e.fallbackTranslations||{});return(0,Z.union)(Object.keys(o),Object.keys(i),Object.keys(r)).forEach((function(a){var s,c;r&&r[a]?(t.translations[a]=r[a],t.locales[a]=n[a]||t.locale):i[a]?(t.translations[a]=i[a],t.locales[a]=null!==(s=e.defaultLocale)&&void 0!==s?s:Rf):(t.translations[a]=o[a],t.locales[a]=null!==(c=e.fallbackLocale)&&void 0!==c?c:Rf)})),t},e.prototype._flattenObject=function(e,t,n){var r=this;void 0===t&&(t={}),void 0===n&&(n="");try{Object.keys(e).forEach((function(i){var o=e[i],a=n?n+"."+i:i;if((0,Z.isObject)(o))return r._flattenObject(o,t,a);t[a]=o}))}catch(e){this._logger.warn("Unable to parse object: "+e)}return t},e.prototype._transformData=function(e){return Object.keys(e).reduce((function(t,n){var r=e[n];return t[n]=null==r?"":r,t}),{})},e.prototype._hasTranslations=function(){var e=this;return Object.keys(this._locales).map((function(t){return e._locales[t]})).filter((function(t){return t.split("-")[0]===e._locale.split("-")[0]})).length>0},(0,s.__decorate)([yn],e)}();const Lf=Nf;function Ff(e){return void 0===e&&(e={}),new Lf(e,R())}var Bf=function(){function e(e){if(!e)throw new Error("Currency settings missing");var t=e.decimalPlaces,n=e.symbolLocation,r=e.symbol,i=e.thousandsSeparator,o=e.decimalSeparator;if("string"!=typeof n||"string"!=typeof r||"string"!=typeof i||"string"!=typeof o||"string"!=typeof t)throw new ae("Invalid currency settings provided");this._decimalPlaces=parseInt(t,10),this._symbolLocation=n,this._symbol=r,this._thousandsSeparator=i,this._decimalSeparator=o}return e.prototype.format=function(e){if("number"!=typeof e)throw new ae("Invalid amount provided");var t=this._formatNumber(e),n=this._formatCurrency(t);return e<0?"-"+n:n},e.prototype._formatNumber=function(e){var t=Math.abs(e),n=this._toFixed(t,this._decimalPlaces).split("."),r=n[0],i=n[1],o=void 0===i?"":i,a=r.replace(/\B(?=(\d{3})+(?!\d))/g,this._thousandsSeparator);return this._decimalPlaces<1?a:[a,o].join(this._decimalSeparator)},e.prototype._formatCurrency=function(e){return"left"===this._symbolLocation.toLowerCase()?""+this._symbol+e:""+e+this._symbol},e.prototype._toFixed=function(e,t){return(+(Math.round(+(e+"e"+t))+"e"+-t)).toFixed(t)},e}();const Uf=Bf,xf=function(){function e(e){this._storeConfig=e,this._customerFormatter=new Uf(this._storeConfig.shopperCurrency),this._storeFormatter=new Uf(this._storeConfig.currency)}return e.prototype.toCustomerCurrency=function(e){var t=this._storeConfig.shopperCurrency.exchangeRate;return this._customerFormatter.format(e*t)},e.prototype.toStoreCurrency=function(e){return this._storeFormatter.format(e)},(0,s.__decorate)([yn],e)}();function qf(e){return new xf(e)}function Vf(e){return e&&"ga"in e&&"function"==typeof e.ga}function Gf(e,t){Vf(window)&&window.ga("send",e,(0,s.__assign)((0,s.__assign)({},t),{nonInteraction:!1}))}function Hf(e){return Yf(e).length>=8096}function Yf(e){return Object.keys(e).reduce((function(t,n){var r=typeof e[n];return"string"===r||"number"===r?(0,s.__spreadArrays)(t,[n+"="+e[n]]):"object"===r&&null!==e[n]?(0,s.__spreadArrays)(t,[Yf(e[n])]):t}),[]).join("&")}var jf;!function(e){e[e.CUSTOMER=1]="CUSTOMER",e[e.SHIPPING=2]="SHIPPING",e[e.BILLING=3]="BILLING",e[e.PAYMENT=4]="PAYMENT"}(jf||(jf={}));var Wf={customer:jf.CUSTOMER,shipping:jf.SHIPPING,billing:jf.BILLING,payment:jf.PAYMENT},Kf=function(){function e(e,t,n,r){var i=(void 0===r?{}:r).checkoutSteps;if(this.checkoutService=e,this.analyticsExtraItemsManager=t,this.analytics=n,this._checkoutStarted=!1,this._completedSteps={},this._viewedSteps={},this._analyticStepOrder=["customer","shipping","billing","payment"],void 0!==i){if(i.some((function(e){return!(e in Wf)})))throw new ae("Invalid checkout steps provided. Valid values are: "+(0,Z.keys)(Wf).join(", ")+".");this._analyticStepOrder=i}}return e.prototype.trackCheckoutStarted=function(){if(!this._checkoutStarted){var e=this.getCheckout();if(e){var t=e.coupons,n=e.grandTotal,r=e.shippingCostTotal,i=e.taxTotal,o=e.cart,a=o.lineItems,s=o.discountAmount,c=o.id,u=this.analyticsExtraItemsManager.saveExtraItemsData(c,a);this.analytics.track("Checkout Started",this.getTrackingPayload({revenue:n,shipping:r,tax:i,discount:s,coupons:t,lineItems:a,extraItemsData:u})),this._checkoutStarted=!0}}},e.prototype.trackOrderComplete=function(){var e,t=this.getOrder();if(t){var n=t.isComplete,r=t.orderId,i=t.orderAmount,o=t.shippingCostTotal,a=t.taxTotal,s=t.discountAmount,c=t.coupons,u=t.lineItems,d=t.cartId;if(n){var l=this.analyticsExtraItemsManager.readExtraItemsData(d);if(null!==l){var p=null===(e=this.checkoutService.getState().data.getConfig())||void 0===e?void 0:e.checkoutSettings.features["DATA-6891.missing_orders_within_GA"],h=this.getTrackingPayload({orderId:r,revenue:i,shipping:o,tax:a,discount:s,coupons:c,extraItemsData:l,lineItems:u});if(p&&Os(window)&&Vf(window)&&Hf(h))return Gf("transaction",{"&ti":h.orderId,"&ta":h.affiliation,"&tr":h.revenue,"&ts":h.shipping,"&tt":h.tax,"&tcc":h.coupon,"&cu":h.currency}),h.products.forEach((function(e){Gf("item",{"&ti":h.orderId,"&in":e.name,"&ic":e.sku,"&iv":""+e.category,"&ip":e.price,"&iq":e.quantity})})),this.analyticsExtraItemsManager.clearExtraItemData(d);this.analytics.track("Order Completed",h),this.analyticsExtraItemsManager.clearExtraItemData(d)}}}},e.prototype.trackStepViewed=function(e){var t=this.getIdFromStep(e);t&&!this.hasStepViewed(t)&&(this.trackViewed(t),this.backfill(t))},e.prototype.trackStepCompleted=function(e){var t=this.getIdFromStep(e);t&&!this.hasStepCompleted(t)&&(this.backfill(t),this.trackCompleted(t))},e.prototype.backfill=function(e){for(var t=0,n=this._analyticStepOrder;t0?e.salePrice:e.listPrice,sku:e.sku,variant_id:e.variantId,discount:e.discountAmount,brand_name:e.brand,currency:t,category_names:(n=e,Array.isArray(n.categoryNames)?n.categoryNames:Array.isArray(n.categories)?(0,Z.flatten)(n.categories).map((function(e){return e.name})):[]),retail_price:e.retailPrice}}));return(0,s.__spreadArrays)(n,i,r).map((function(e){return(0,s.__assign)((0,s.__assign)({},e),{product_id:String(e.product_id)})}))},e.prototype._hasStepCompleted=function(e){return this._completedSteps[e]},e}();const tg=eg,ng=function(){function e(){}return e.prototype.checkoutBegin=function(){},e.prototype.orderPurchased=function(){},e.prototype.stepCompleted=function(){},e.prototype.customerEmailEntry=function(){},e.prototype.customerSuggestionInit=function(){},e.prototype.customerSuggestionExecute=function(){},e.prototype.customerPaymentMethodExecuted=function(){},e.prototype.showShippingMethods=function(){},e.prototype.selectedPaymentMethod=function(){},e.prototype.clickPayButton=function(){},e.prototype.paymentRejected=function(){},e.prototype.paymentComplete=function(){},e.prototype.exitCheckout=function(){},e}();function rg(e){return function(e){return"bodlEvents"in e}(window)?new tg(e,window.bodlEvents.checkout):new ng}})(),module.exports=r})(); +(()=>{"use strict";var e={780:e=>{e.exports=require("iframe-resizer")},252:e=>{e.exports=require("iframe-resizer/js/iframeResizer.contentWindow")}},t={};function n(r){var i=t[r];if(void 0!==i)return i.exports;var o=t[r]={exports:{}};return e[r](o,o.exports,n),o.exports}n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var r={};(()=>{n.r(r),n.d(r,{createBodlService:()=>rg,createCheckoutButtonInitializer:()=>lf,createCheckoutService:()=>iy,createCurrencyService:()=>qf,createEmbeddedCheckoutMessenger:()=>Tf,createLanguageService:()=>Ff,createStepTracker:()=>Qf,createTimeout:()=>o.createTimeout,embedCheckout:()=>bf});var e={};n.r(e),n.d(e,{createApplePayCustomerStrategy:()=>Ie,createBoltCustomerStrategy:()=>Ue,createBraintreePaypalCustomerStrategy:()=>nt,createPayPalCommerceCreditCustomerStrategy:()=>At,createPayPalCommerceCustomerStrategy:()=>bt,createPayPalCommerceVenmoCustomerStrategy:()=>Tt});var t={};n.r(t),n.d(t,{createAdyenV2PaymentStrategy:()=>Ta,createAdyenV3PaymentStrategy:()=>Va,createApplePayPaymentStrategy:()=>ja,createBlueSnapDirectAPMPaymentStrategy:()=>bs,createBlueSnapDirectCreditCardPaymentStrategy:()=>gs,createBlueSnapDirectEcpPaymentStrategy:()=>Cs,createBoltPaymentStrategy:()=>Rs,createBraintreeLocalMethodsPaymentStrategy:()=>Hs,createBraintreePaypalAchPaymentStrategy:()=>Fs,createCreditCardPaymentStrategy:()=>Ws,createExternalPaymentStrategy:()=>Zs,createLegacyPaymentStrategy:()=>$s,createNoPaymentStrategy:()=>nc,createOfflinePaymentStrategy:()=>oc,createOffsitePaymentStrategy:()=>dc,createPayPalCommerceAlternativeMethodsPaymentStrategy:()=>Ic,createPayPalCommerceCreditCardsPaymentStrategy:()=>Ac,createPayPalCommerceCreditPaymentStrategy:()=>yc,createPayPalCommercePaymentStrategy:()=>hc,createPayPalCommerceVenmoPaymentStrategy:()=>vc,createSezzlePaymentStrategy:()=>kc,createSquareV2PaymentStrategy:()=>Bc});var i={};n.r(i),n.d(i,{createApplePayButtonStrategy:()=>By,createBoltButtonStrategy:()=>qy,createPayPalCommerceAlternativeMethodsButtonStrategy:()=>$y,createPayPalCommerceButtonStrategy:()=>Hy,createPayPalCommerceCreditButtonStrategy:()=>Wy,createPayPalCommerceVenmoButtonStrategy:()=>Zy,createPaypalExpressButtonStrategy:()=>df});const o=require("@bigcommerce/request-sender"),a=require("@bigcommerce/script-loader"),s=require("tslib"),c=require("@bigcommerce/data-store"),u=require("rxjs"),d=require("rxjs/operators");function l(e,t,n){return(r=t)&&r.type&&r.error?(0,u.concat)((0,u.of)(t),(0,u.throwError)((0,c.createErrorAction)(e,t.payload,n))):(0,u.throwError)((0,c.createErrorAction)(e,t,n));var r}const p=function(e){function t(t){var n,r,i=this.constructor,o=e.call(this,t||"An unexpected error has occurred.")||this;return o.name="StandardError",o.type="standard",n=o,r=i.prototype,Object.setPrototypeOf?Object.setPrototypeOf(n,r):n.__proto__=r,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(o,i):o.stack=new Error(o.message).stack,o}return(0,s.__extends)(t,e),t}(Error);var h;!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"}(h||(h={}));const m=function(e){function t(t){var n=e.call(this,function(e){switch(e){case h.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case h.MissingCart:return"Unable to proceed because cart data is unavailable.";case h.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case h.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case h.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case h.MissingCheckoutConfig:case h.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case h.MissingOrder:return"Unable to proceed because order data is unavailable.";case h.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case h.MissingPayment:return"Unable to proceed because payment data is unavailable.";case h.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case h.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case h.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(t))||this;return n.subtype=t,n.name="MissingDataError",n.type="missing_data",n}return(0,s.__extends)(t,e),t}(p);var _;!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"}(_||(_={}));const y=function(e){function t(t){var n=e.call(this,t||"Unable to continue as a guest because the customer is already signed in.")||this;return n.name="UnableToContinueAsGuestError",n.type="unable_to_continue_as_guest",n}return(0,s.__extends)(t,e),t}(p);var f=function(){function e(e,t){this._requestSender=e,this._subscriptionActionCreator=t}return e.prototype.continueAsGuest=function(e,t){var n=this;return function(r){var i=r.getState(),o=i.checkout.getCheckout();if(!o)throw new m(h.MissingCheckout);var a=i.customer.getCustomer();if(a&&!a.isGuest)throw new y;var p,f=i.billingAddress.getBillingAddress();if(f){f.country;var g=(0,s.__rest)(f,["country"]);p=(0,s.__assign)((0,s.__assign)({},g),e)}else p=e;return(0,u.merge)((0,u.concat)((0,u.of)((0,c.createAction)(_.ContinueAsGuestRequested)),(0,u.defer)((function(){return(0,s.__awaiter)(n,void 0,void 0,(function(){var e;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return[4,this._createOrUpdateBillingAddress(o.id,p,t)];case 1:return e=n.sent().body,[2,(0,c.createAction)(_.ContinueAsGuestSucceeded,e)]}}))}))}))).pipe((0,d.catchError)((function(e){return l(_.ContinueAsGuestFailed,e)}))),n._updateCustomerConsent(e,t))}},e.prototype.updateAddress=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o=r.getState(),a=o.checkout.getCheckout();if(!a)throw new m(h.MissingCheckout);i.next((0,c.createAction)(_.UpdateBillingAddressRequested));var u=o.billingAddress.getBillingAddress(),d=(0,s.__assign)((0,s.__assign)({},e),{email:void 0===e.email&&u?u.email:e.email});u&&u.id&&(d.id=u.id),n._createOrUpdateBillingAddress(a.id,d,t).then((function(e){var t=e.body;i.next((0,c.createAction)(_.UpdateBillingAddressSucceeded,t)),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(_.UpdateBillingAddressFailed,e))}))}))}},e.prototype._updateCustomerConsent=function(e,t){var n=e.email,r=e.acceptsAbandonedCartEmails,i=e.acceptsMarketingNewsletter;return null==r&&null==i?(0,u.empty)():this._subscriptionActionCreator.updateSubscriptions({email:n,acceptsMarketingNewsletter:i||!1,acceptsAbandonedCartEmails:r||!1},t)},e.prototype._createOrUpdateBillingAddress=function(e,t,n){return t.id?this._requestSender.updateAddress(e,t,n):this._requestSender.createAddress(e,t,n)},e}();const g=f;var v;!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(v||(v={}));const w=v;var C={"X-Checkout-SDK-Version":"1.398.2"},S={include:["cart.lineItems.physicalItems.options","cart.lineItems.digitalItems.options","customer","promotions.banners"].join(",")},I=function(){function e(e){this._requestSender=e}return e.prototype.createAddress=function(e,t,n){var r=(void 0===n?{}:n).timeout,i="/api/storefront/checkouts/"+e+"/billing-address",o=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.post(i,{body:t,params:S,headers:o,timeout:r})},e.prototype.updateAddress=function(e,t,n){var r=(void 0===n?{}:n).timeout,i=t.id,o=(0,s.__rest)(t,["id"]),a="/api/storefront/checkouts/"+e+"/billing-address/"+i,c=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.put(a,{params:S,body:o,headers:c,timeout:r})},e}();const b=I;var P;!function(e){e.ClearError="CLEAR_ERROR"}(P||(P={}));const E=function(){function e(){}return e.prototype.clearError=function(e){return{type:P.ClearError,payload:e}},e}();function A(){try{return process.env.NODE_ENV||0}catch(e){return"development"}}var O=function(){function e(e){this._console=e}return e.prototype.log=function(){for(var e=[],t=0;t=400&&e.status<500)throw new q(e);throw e}))},e}();const H=G;var Y;!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"}(Y||(Y={}));var j=function(){function e(e){this._couponRequestSender=e}return e.prototype.applyCoupon=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o=r.getState().checkout.getCheckout();if(!o)throw new m(h.MissingCheckout);i.next((0,c.createAction)(Y.ApplyCouponRequested)),n._couponRequestSender.applyCoupon(o.id,e,t).then((function(e){var t=e.body;i.next((0,c.createAction)(Y.ApplyCouponSucceeded,t)),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(Y.ApplyCouponFailed,e))}))}))}},e.prototype.removeCoupon=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o=r.getState().checkout.getCheckout();if(!o)throw new m(h.MissingCheckout);i.next((0,c.createAction)(Y.RemoveCouponRequested)),n._couponRequestSender.removeCoupon(o.id,e,t).then((function(e){var t=e.body;i.next((0,c.createAction)(Y.RemoveCouponSucceeded,t)),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(Y.RemoveCouponFailed,e))}))}))}},e}();const W=j,K=["cart.lineItems.physicalItems.options","cart.lineItems.digitalItems.options","customer","customer.customerGroup","payments","promotions.banners"];var J;!function(e){e.AvailableShippingOptions="consignments.availableShippingOptions",e.PhysicalItemsCategoryNames="cart.lineItems.physicalItems.categoryNames",e.DigitalItemsCategoryNames="cart.lineItems.digitalItems.categoryNames"}(J||(J={}));const Z=require("lodash");function Q(e){return(0,Z.uniq)(e).join(",")}var X=function(){function e(e){this._requestSender=e}return e.prototype.applyCoupon=function(e,t,n){var r=(void 0===n?{}:n).timeout,i="/api/storefront/checkouts/"+e+"/coupons",o=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.post(i,{headers:o,timeout:r,params:{include:Q((0,s.__spreadArrays)(K,[J.AvailableShippingOptions]))},body:{couponCode:t}})},e.prototype.removeCoupon=function(e,t,n){var r=(void 0===n?{}:n).timeout,i="/api/storefront/checkouts/"+e+"/coupons/"+t,o=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.delete(i,{headers:o,timeout:r,params:{include:Q((0,s.__spreadArrays)(K,[J.AvailableShippingOptions]))}})},e}();const $=X;var ee;!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"}(ee||(ee={}));var te=function(){function e(e){this._giftCertificateRequestSender=e}return e.prototype.applyGiftCertificate=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o=r.getState().checkout.getCheckout();if(!o)throw new m(h.MissingCheckout);i.next((0,c.createAction)(ee.ApplyGiftCertificateRequested)),n._giftCertificateRequestSender.applyGiftCertificate(o.id,e,t).then((function(e){var t=e.body;i.next((0,c.createAction)(ee.ApplyGiftCertificateSucceeded,t)),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(ee.ApplyGiftCertificateFailed,e))}))}))}},e.prototype.removeGiftCertificate=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o=r.getState().checkout.getCheckout();if(!o)throw new m(h.MissingCheckout);i.next((0,c.createAction)(ee.RemoveGiftCertificateRequested)),n._giftCertificateRequestSender.removeGiftCertificate(o.id,e,t).then((function(e){var t=e.body;i.next((0,c.createAction)(ee.RemoveGiftCertificateSucceeded,t)),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(ee.RemoveGiftCertificateFailed,e))}))}))}},e}();const ne=te;var re=function(){function e(e){this._requestSender=e}return e.prototype.applyGiftCertificate=function(e,t,n){var r=(void 0===n?{}:n).timeout,i="/api/storefront/checkouts/"+e+"/gift-certificates",o=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.post(i,{headers:o,timeout:r,params:{include:Q(K)},body:{giftCertificateCode:t}})},e.prototype.removeGiftCertificate=function(e,t,n){var r=(void 0===n?{}:n).timeout,i="/api/storefront/checkouts/"+e+"/gift-certificates/"+t,o=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.delete(i,{headers:o,timeout:r,params:{include:Q(K)}})},e}();const ie=re;function oe(e){return"resolveIds"in e}const ae=function(e){function t(t){var n=e.call(this,t||"Invalid arguments have been provided.")||this;return n.name="InvalidArgumentError",n.type="invalid_argument",n}return(0,s.__extends)(t,e),t}(p);var se=function(){function e(e){var t,n,r;this._factories={},this._instances={},this._defaultToken=null!==(t=null==e?void 0:e.defaultToken)&&void 0!==t?t:"default",this._useFallback=null===(n=null==e?void 0:e.useFallback)||void 0===n||n,this._tokenResolver=null!==(r=null==e?void 0:e.tokenResolver)&&void 0!==r?r:function(e){return e}}return e.prototype.get=function(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)}},e.prototype.register=function(e,t){if(this._hasFactory(e))throw new ae("'"+e+"' is already registered.");this._factories[e]=t},e.prototype._hasFactory=function(e){return!!this._factories[e]},e.prototype._hasInstance=function(e){return!!this._instances[e]},e.prototype._getInstance=function(e,t){if(!this._hasInstance(t)){var n=this._tokenResolver(e,Object.keys(this._factories)),r=n&&this._factories[n];if(!r)throw new ae("'"+e+"' is not registered.");this._instances[t]=r()}return this._instances[t]},e}();const ce=se;var ue=function(){function e(e){void 0===e&&(e=!1),this._useFallback=e,this._registry=new ce({tokenResolver:this._resolveToken.bind(this),useFallback:this._useFallback})}return e.prototype.get=function(e){return this._registry.get(this._encodeToken(e))},e.prototype.register=function(e,t){this._registry.register(this._encodeToken(e),t)},e.prototype._encodeToken=function(e){return btoa(JSON.stringify(e))},e.prototype._decodeToken=function(e){return JSON.parse(atob(e))},e.prototype._resolveToken=function(e,t){var n,r=this,i=this._decodeToken(e),o=[];t.forEach((function(e){for(var t=r._decodeToken(e),n={token:e,matches:0,default:!1},a=0,s=Object.entries(t);a0}));a.length>1&&a[0].matches===a[1].matches&&"development"===A()&&R().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.");var s=a[0];if(s&&s.token)return s.token;if(this._useFallback){var c=null===(n=o.find((function(e){return e.default})))||void 0===n?void 0:n.token;if(c)return c}throw new Error("Unable to resolve to a registered token with the provided token.")},e}();const de=ue;function le(e,t){return Object.assign(e,{resolveIds:t})}const pe=function(e){function t(t){var n,r,i=this.constructor,o=e.call(this,t||"An unexpected error has occurred.")||this;return o.name="StandardError",o.type="standard",n=o,r=i.prototype,Object.setPrototypeOf?Object.setPrototypeOf(n,r):n.__proto__=r,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(o,i):o.stack=new Error(o.message).stack,o}return(0,s.__extends)(t,e),t}(Error);var he;!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"}(he||(he={}));const me=function(e){function t(t){var n=e.call(this,function(e){switch(e){case he.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case he.MissingCart:return"Unable to proceed because cart data is unavailable.";case he.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case he.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case he.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case he.MissingCheckoutConfig:case he.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case he.MissingOrder:return"Unable to proceed because order data is unavailable.";case he.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case he.MissingPayment:return"Unable to proceed because payment data is unavailable.";case he.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case he.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case he.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(t))||this;return n.subtype=t,n.name="MissingDataError",n.type="missing_data",n}return(0,s.__extends)(t,e),t}(pe),_e=function(e){function t(t){var n=e.call(this,t||"Not implemented.")||this;return n.name="NotImplementedError",n.type="not_implemented",n}return(0,s.__extends)(t,e),t}(pe);const ye=function(e){function t(t){var n=e.call(this,t||"Invalid arguments have been provided.")||this;return n.name="InvalidArgumentError",n.type="invalid_argument",n}return(0,s.__extends)(t,e),t}(pe),fe=function(e){function t(t){var n=e.call(this,t||"Payment process was cancelled.")||this;return n.name="PaymentMethodCancelledError",n.type="payment_cancelled",n}return(0,s.__extends)(t,e),t}(pe);function ge(e){if(!function(e){return"ApplePaySession"in e}(e))throw new Error("Apple pay is not supported")}const ve=function(){function e(){}return e.prototype.create=function(e){return ge(window),new ApplePaySession(1,e)},e}();var we;!function(e){e.Subtotal="Subtotal",e.Shipping="Shipping"}(we||(we={}));var Ce=function(){function e(e,t,n){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=n,this._onAuthorizeCallback=Z.noop,this._onError=Z.noop,this._subTotalLabel=we.Subtotal,this._shippingLabel=we.Shipping}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.methodId,n=e.applepay,ge(window),!t||!n)throw new me(he.MissingPaymentMethod);return r=n.container,i=n.shippingLabel,o=n.subtotalLabel,a=n.onError,c=void 0===a?Z.noop:a,u=n.onPaymentAuthorize,this._shippingLabel=i||we.Shipping,this._subTotalLabel=o||we.Subtotal,this._onAuthorizeCallback=u,this._onError=c,[4,this._paymentIntegrationService.loadPaymentMethod(t)];case 1:return s.sent(),d=this._paymentIntegrationService.getState(),this._paymentMethod=d.getPaymentMethodOrThrow(t),[4,this._paymentIntegrationService.verifyCheckoutSpamProtection()];case 2:return s.sent(),this._applePayButton=this._createButton(r),this._applePayButton.addEventListener("click",this._handleWalletButtonClick.bind(this)),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.signIn=function(){throw new _e('In order to sign in via Apple, the shopper must click on "Apple Pay" button.')},e.prototype.signOut=function(){throw new _e("Need to do signout via apple.")},e.prototype.executePaymentMethodCheckout=function(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()},e.prototype._createButton=function(e){var t=document.getElementById(e);if(!t)throw new ye("Unable to create sign-in button without valid container ID.");var n=document.createElement("button");return n.setAttribute("type","button"),n.setAttribute("aria-label","Apple Pay"),t.appendChild(n),n},e.prototype._handleWalletButtonClick=function(e){e.preventDefault();var t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow(),r=t.getStoreConfigOrThrow(),i=t.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new me(he.MissingPaymentMethod);var o=this._getBaseRequest(n,i,r,this._paymentMethod),a=this._sessionFactory.create(o);this._handleApplePayEvents(a,this._paymentMethod,r),a.begin()},e.prototype._getBaseRequest=function(e,t,n,r){var i,o=n.storeProfile,a=o.storeCountryCode,s=o.storeName,c=e.currency,u=c.code,d=c.decimalPlaces,l=r.initializationData,p=l.merchantCapabilities,h=l.supportedNetworks,m=e.lineItems.physicalItems.length>0,_={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:a,currencyCode:u,merchantCapabilities:p,supportedNetworks:h,lineItems:[],total:m?{label:s,amount:""+t.grandTotal.toFixed(d),type:"pending"}:{label:s,amount:""+t.grandTotal.toFixed(d),type:"final"}};if(m)null===(i=_.requiredShippingContactFields)||void 0===i||i.push("postalAddress");else{var y=[{label:this._subTotalLabel,amount:""+t.subtotal.toFixed(d)}];t.taxes.forEach((function(e){return y.push({label:e.name,amount:""+e.amount.toFixed(d)})})),_.lineItems=y}return _},e.prototype._handleApplePayEvents=function(e,t,n){var r=this;e.onvalidatemerchant=function(n){return(0,s.__awaiter)(r,void 0,void 0,(function(){var r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),[4,this._onValidateMerchant(t,n)];case 1:return r=o.sent().body,e.completeMerchantValidation(r),[3,3];case 2:return i=o.sent(),this._onError(i),[3,3];case 3:return[2]}}))}))},e.onshippingcontactselected=function(t){return(0,s.__awaiter)(r,void 0,void 0,(function(){return(0,s.__generator)(this,(function(r){return[2,this._handleShippingContactSelected(e,n,t)]}))}))},e.onshippingmethodselected=function(t){return(0,s.__awaiter)(r,void 0,void 0,(function(){return(0,s.__generator)(this,(function(r){return[2,this._handleShippingMethodSelected(e,n,t)]}))}))},e.oncancel=function(){return(0,s.__awaiter)(r,void 0,void 0,(function(){var e;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return n.trys.push([0,3,,4]),e="/remote-checkout/"+t.id+"/signout",[4,this._requestSender.get(e)];case 1:return n.sent(),[4,this._paymentIntegrationService.loadCheckout()];case 2:return[2,n.sent()];case 3:return n.sent(),[2,this._onError(new fe)];case 4:return[2]}}))}))},e.onpaymentauthorized=function(n){return(0,s.__awaiter)(r,void 0,void 0,(function(){return(0,s.__generator)(this,(function(r){return[2,this._onPaymentAuthorized(n,e,t)]}))}))}},e.prototype._handleShippingContactSelected=function(e,t,n){var r;return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u,d,l,p,h,m,_,y,f,g,v;return(0,s.__generator)(this,(function(w){switch(w.label){case 0:i=this._transformContactToAddress(n.shippingContact),w.label=1;case 1:return w.trys.push([1,3,,4]),[4,this._paymentIntegrationService.updateShippingAddress(i)];case 2:return w.sent(),[3,4];case 3:return o=w.sent(),e.abort(),[2,this._onError(o)];case 4:if(a=t.storeProfile.storeName,c=this._paymentIntegrationService.getState(),u=c.getCartOrThrow().currency.decimalPlaces,d=c.getCheckoutOrThrow(),l=null===(r=d.consignments[0].selectedShippingOption)||void 0===r?void 0:r.id,p=d.consignments[0].availableShippingOptions,h=null==p?void 0:p.find((function(e){return e.id===l})),m=null==p?void 0:p.filter((function(e){return e.id!==l})),_=h?[{label:h.description,amount:""+h.cost.toFixed(u),detail:h.additionalDescription,identifier:h.id}]:[],m&&(0,s.__spreadArrays)(m.filter((function(e){return e.isRecommended})),m.filter((function(e){return!e.isRecommended}))).forEach((function(e){return _.push({label:e.description,amount:""+e.cost.toFixed(u),detail:e.additionalDescription,identifier:e.id})})),!(p instanceof Array))throw new Error("Shipping options not available.");if(0===p.length)return e.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:a,amount:""+d.grandTotal.toFixed(u)},[]),[2];y=p.find((function(e){return e.isRecommended})),f=y?y.id:p[0].id,g=h?h.id:f,w.label=5;case 5:return w.trys.push([5,7,,8]),[4,this._updateShippingOption(g)];case 6:return w.sent(),[3,8];case 7:return v=w.sent(),[2,this._onError(v)];case 8:return c=this._paymentIntegrationService.getState(),d=c.getCheckoutOrThrow(),e.completeShippingContactSelection({newShippingMethods:_,newTotal:{type:"final",label:a,amount:""+d.grandTotal.toFixed(u)},newLineItems:this._getUpdatedLineItems(d,u)}),[2]}}))}))},e.prototype._handleShippingMethodSelected=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:r=t.storeProfile.storeName,i=n.shippingMethod.identifier,s.label=1;case 1:return s.trys.push([1,3,,4]),[4,this._updateShippingOption(i)];case 2:return s.sent(),[3,4];case 3:return o=s.sent(),e.abort(),[2,this._onError(o)];case 4:return a=this._paymentIntegrationService.getState(),c=a.getCartOrThrow().currency.decimalPlaces,u=a.getCheckoutOrThrow(),e.completeShippingMethodSelection({newTotal:{type:"final",label:r,amount:""+u.grandTotal.toFixed(c)},newLineItems:this._getUpdatedLineItems(u,c)}),[2]}}))}))},e.prototype._getUpdatedLineItems=function(e,t){var n=[{label:this._subTotalLabel,amount:""+e.subtotal.toFixed(t)}];return e.taxes.forEach((function(e){return n.push({label:e.name,amount:""+e.amount.toFixed(t)})})),n.push({label:this._shippingLabel,amount:""+e.shippingCostTotal.toFixed(t)}),n},e.prototype._updateShippingOption=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){return[2,this._paymentIntegrationService.selectShippingOption(e)]}))}))},e.prototype._onValidateMerchant=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n;return(0,s.__generator)(this,(function(r){return n=["validationUrl="+t.validationURL,"merchantIdentifier="+e.initializationData.merchantId,"displayName="+e.initializationData.storeName,"domainName="+window.location.hostname].join("&"),[2,this._requestSender.post((i=e.initializationData.paymentsUrl,i+"/api/public/v1/payments/applepay/validate_merchant"),{credentials:!1,headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","X-XSRF-TOKEN":null},body:n})];var i}))}))},e.prototype._onPaymentAuthorized=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d,l,p,h,m,_,y;return(0,s.__generator)(this,(function(f){switch(f.label){case 0:r=e.payment,i=r.token,o=r.billingContact,a=r.shippingContact,c=this._paymentIntegrationService.getState(),u=c.getCartOrThrow(),d=u.lineItems.physicalItems.length>0,l={methodId:n.id,paymentData:{formattedPayload:{apple_pay_token:{payment_data:i.paymentData,payment_method:i.paymentMethod,transaction_id:i.transactionIdentifier}}}},p=this._transformContactToAddress(o),h=this._transformContactToAddress(a),m=null==a?void 0:a.emailAddress,_=(null==a?void 0:a.phoneNumber)||"",f.label=1;case 1:return f.trys.push([1,7,,8]),[4,this._paymentIntegrationService.updateBillingAddress((0,s.__assign)((0,s.__assign)({},p),{email:m,phone:_}))];case 2:return f.sent(),d?[4,this._paymentIntegrationService.updateShippingAddress(h)]:[3,4];case 3:f.sent(),f.label=4;case 4:return[4,this._paymentIntegrationService.submitOrder({useStoreCredit:!1})];case 5:return f.sent(),[4,this._paymentIntegrationService.submitPayment(l)];case 6:return f.sent(),t.completePayment(ApplePaySession.STATUS_SUCCESS),[2,this._onAuthorizeCallback()];case 7:return y=f.sent(),t.completePayment(ApplePaySession.STATUS_FAILURE),[2,this._onError(y)];case 8:return[2]}}))}))},e.prototype._transformContactToAddress=function(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:[]}},e}();const Se=Ce,Ie=le((function(e){var t=e.getState().getHost;return new Se((0,o.createRequestSender)({host:t()}),e,new ve)}),[{id:"applepay"}]),be=function(e){function t(t){var n=e.call(this,t||"Unable to proceed because the client library of a payment method has thrown an unexpected error.")||this;return n.name="PaymentMethodFailedError",n.type="payment_method_client_invalid",n}return(0,s.__extends)(t,e),t}(pe);var Pe;!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"}(Pe||(Pe={}));const Ee=function(e){function t(t){var n=e.call(this,function(e){switch(e){case Pe.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case Pe.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case Pe.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case Pe.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."}}(t))||this;return n.subtype=t,n.name="NotInitializedError",n.type="not_initialized",n}return(0,s.__extends)(t,e),t}(pe);var Ae={body:{},headers:{},status:0},Oe=function(e){function t(t,n){var r=void 0===n?{}:n,i=r.message,o=r.errors,a=this,s=t||Ae,c=s.body,u=s.headers,d=s.status;return(a=e.call(this,i||"An unexpected error has occurred.")||this).name="RequestError",a.type="request",a.body=c,a.headers=u,a.status=d,a.errors=o||[],a}return(0,s.__extends)(t,e),t}(pe);const ke=Oe,Te=function(e){function t(t){var n=e.call(this,t,{message:"There is a problem processing your payment. Please try again later."})||this;return n.name="PaymentMethodInvalidError",n.type="payment_method_invalid",n}return(0,s.__extends)(t,e),t}(ke);var Me=function(){function e(e,t){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.boltHostWindow=window}return e.prototype.initialize=function(e){var t;return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d,l;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(n=e.methodId,r=e.bolt,i=(r||{}).onInit,!n)throw new ye('Unable to proceed because "methodId" argument is not provided.');return[4,this.paymentIntegrationService.loadPaymentMethod(n)];case 1:if(s.sent(),o=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(n),!(null===(t=o.initializationData)||void 0===t?void 0:t.publishableKey))throw new me(he.MissingPaymentMethod);return a=o.initializationData,c=a.developerConfig,u=a.publishableKey,[4,this.boltScriptLoader.loadBoltClient(u,o.config.testMode,c)];case 2:return s.sent(),i&&"function"==typeof i?(d=this.getCustomerEmail(),[4,this.hasBoltAccount(d)]):[3,4];case 3:l=s.sent(),i(l,d),s.label=4;case 4:return[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.signIn=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return[4,this.paymentIntegrationService.signInCustomer(e,t)];case 1:return n.sent(),[2,Promise.resolve()]}}))}))},e.prototype.signOut=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this.paymentIntegrationService.signOutCustomer(e)];case 1:return t.sent(),[2,Promise.resolve()]}}))}))},e.prototype.executePaymentMethodCheckout=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a;return(0,s.__generator)(this,(function(s){if(n=(t=e||{}).continueWithCheckoutCallback,r=void 0===n?u.noop:n,i=t.checkoutPaymentMethodExecuted,o=t.methodId,a=this.getCustomerEmail(),!o)throw new ye('Unable to proceed because "methodId" argument is not provided.');if("function"!=typeof r)throw new ye('Unable to proceed because "continueWithCheckoutCallback" argument is not provided and it must be a function.');return a?[2,this.openBoltCheckoutModalOrThrow(a,o,r,i)]:(r(),[2])}))}))},e.prototype.openBoltCheckoutModalOrThrow=function(e,t,n,r){var i;return(0,s.__awaiter)(this,void 0,void 0,(function(){var o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:o=this.getBoltClientOrThrow(),a=this.paymentIntegrationService.getState().getPaymentMethod(t),s.label=1;case 1:return s.trys.push([1,8,,9]),(null===(i=null==a?void 0:a.initializationData)||void 0===i?void 0:i.embeddedOneClickEnabled)?[4,this.hasBoltAccount(e)]:[3,6];case 2:return(c=s.sent())?(u={close:function(){n()}},[4,o.openCheckout(e,u)]):[3,4];case 3:return s.sent(),[3,5];case 4:n(),s.label=5;case 5:return"function"==typeof r&&r({hasBoltAccount:c}),[3,7];case 6:n(),s.label=7;case 7:return[3,9];case 8:if("string"==typeof(l=d=s.sent()).message&&"string"==typeof l.type&&("string"==typeof l.subtype||!l.subtype)&&l instanceof Error&&"MissingDataError"!==d.name&&"NotInitializedError"!==d.name)throw new be(d.message);throw d;case 9:return[2]}var l}))}))},e.prototype.getBoltClientOrThrow=function(){var e=this.boltHostWindow.BoltCheckout;if(!e)throw new Ee(Pe.PaymentNotInitialized);return e},e.prototype.hasBoltAccount=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:t=this.getBoltClientOrThrow(),n.label=1;case 1:return n.trys.push([1,3,,4]),[4,t.hasBoltAccount(e)];case 2:return[2,n.sent()];case 3:throw n.sent(),new Te;case 4:return[2]}}))}))},e.prototype.getCustomerEmail=function(){var e=this.paymentIntegrationService.getState(),t=e.getCustomer(),n=e.getBillingAddress();return(null==t?void 0:t.email)||(null==n?void 0:n.email)||""},e}();const De=Me,Re=function(e){function t(t){var n=e.call(this,t||"Unable to proceed because the client library of a payment method is not loaded or ready to be used.")||this;return n.name="PaymentMethodClientUnavailableError",n.type="payment_method_client_unavailable",n}return(0,s.__extends)(t,e),t}(pe);var ze,Ne,Le;!function(e){e.SandboxMode="bolt_sandbox",e.StagingMode="bolt_staging",e.DevelopmentMode="bolt_development"}(ze||(ze={})),function(e){e.Small="small",e.Medium="medium",e.Large="large"}(Ne||(Ne={})),function(e){e.Pill="pill",e.Rect="rect"}(Le||(Le={}));var Fe=function(){function e(e,t){void 0===t&&(t=window),this.scriptLoader=e,this.boltHostWindow=t}return e.prototype.loadBoltClient=function(e,t,n,r,i){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(this.boltHostWindow.BoltCheckout)return[2,this.boltHostWindow.BoltCheckout];if(!e)throw new ye('Unable to initialize payment because "publishableKey" argument is not provided.');return[4,this.scriptLoader.loadScript("//"+this.getDomainURL(!!t,n)+"/connect-bigcommerce.js",this.getScriptOptions("bolt-connect",e,r,i))];case 1:return o.sent(),[4,this.scriptLoader.loadScript("//"+this.getDomainURL(!!t,n)+"/track.js",this.getScriptOptions("bolt-track",e))];case 2:if(o.sent(),!this.boltHostWindow.BoltCheckout)throw new Re;return[2,this.boltHostWindow.BoltCheckout]}}))}))},e.prototype.loadBoltEmbedded=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return r={async:!0,attributes:{id:"bolt-embedded"}},[4,this.scriptLoader.loadScript("//"+this.getDomainURL(!!t,n)+"/embed.js",r)];case 1:if(i.sent(),!this.boltHostWindow.Bolt)throw new Re;return[2,this.boltHostWindow.Bolt(e)]}}))}))},e.prototype.getDomainURL=function(e,t){if(!e)return"connect.bolt.com";if(t)switch(t.developerMode){case ze.StagingMode:return"connect-staging.bolt.com";case ze.DevelopmentMode:return"connect."+t.developerDomain}return"connect-sandbox.bolt.com"},e.prototype.getScriptOptions=function(e,t,n,r){return{async:!0,attributes:(0,s.__assign)((0,s.__assign)({id:e,"data-publishable-key":t},n&&{"data-shopping-cart-id":n}),r&&{"data-storefront-api-token":r})}},e}();const Be=Fe,Ue=le((function(e){return new De(e,new Be((0,a.getScriptLoader)()))}),[{id:"bolt"}]),xe=require("@bigcommerce/form-poster");var qe;function Ve(e){return Boolean("object"==typeof e&&null!==e&&("type"in e||"message"in e||"code"in e))}!function(e){e.Sandbox="sandbox",e.Production="production"}(qe||(qe={}));var Ge,He,Ye,je,We,Ke=["buttons","messages"];!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(Ge||(Ge={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(He||(He={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black"}(Ye||(Ye={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(je||(je={})),function(e){e.PILL="pill",e.RECT="rect"}(We||(We={}));var Je=function(){function e(e,t){this.braintreeScriptLoader=e,this.braintreeHostWindow=t,this.dataCollectors={}}return e.prototype.initialize=function(e){this.clientToken=e},e.prototype.getClient=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){var e;return(0,s.__generator)(this,(function(t){switch(t.label){case 0:if(!this.clientToken)throw new Ee(Pe.PaymentNotInitialized);return this.client?[3,2]:[4,this.braintreeScriptLoader.loadClient()];case 1:e=t.sent(),this.client=e.create({authorization:this.clientToken}),t.label=2;case 2:return[2,this.client]}}))}))},e.prototype.getPaypalCheckout=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u=this;return(0,s.__generator)(this,(function(d){switch(d.label){case 0:return[4,this.getClient()];case 1:return r=d.sent(),[4,this.braintreeScriptLoader.loadPaypalCheckout()];case 2:return i=d.sent(),o={client:r},a=function(r,i){if(r)return n(r);var o=(0,s.__assign)((0,s.__assign)({currency:e.currency},e.isCreditEnabled&&{"enable-funding":"paylater"}),{components:Ke.toString(),intent:e.intent});u.braintreeHostWindow.paypal?t(i):i.loadPayPalSDK(o,(function(){return t(i)}))},c=this,[4,i.create(o,a)];case 3:return c.paypalCheckout=d.sent(),[2,this.paypalCheckout]}}))}))},e.prototype.loadBraintreeLocalMethods=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return[4,this.getClient()];case 1:return n=i.sent(),[4,this.braintreeScriptLoader.loadBraintreeLocalMethods()];case 2:return r=i.sent(),this.braintreeLocalMethods||(this.braintreeLocalMethods=r.create({client:n,merchantAccountId:t},(function(t,n){if(t)throw new Error(t);e(n)}))),[2,this.braintreeLocalMethods]}}))}))},e.prototype.getUsBankAccount=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){var e,t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return this.usBankAccount?[3,3]:[4,this.getClient()];case 1:return e=n.sent(),[4,this.braintreeScriptLoader.loadUsBankAccount()];case 2:t=n.sent(),this.usBankAccount=t.create({client:e}),n.label=3;case 3:return[2,this.usBankAccount]}}))}))},e.prototype.getDataCollector=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(t=(null==e?void 0:e.paypal)?"paypal":"default",n=this.dataCollectors[t])return[3,7];o.label=1;case 1:return o.trys.push([1,5,,6]),[4,this.getClient()];case 2:return r=o.sent(),[4,this.braintreeScriptLoader.loadDataCollector()];case 3:return[4,o.sent().create((0,s.__assign)({client:r,kount:!0},e))];case 4:return n=o.sent(),[3,6];case 5:if(!Ve(i=o.sent())||"DATA_COLLECTOR_KOUNT_NOT_ENABLED"!==i.code)throw i;return n={deviceData:void 0,teardown:function(){return Promise.resolve()}},[3,6];case 6:this.dataCollectors[t]=n,o.label=7;case 7:return[2,n]}}))}))},e.prototype.getBraintreeEnv=function(e){return void 0===e&&(e=!1),e?qe.Sandbox:qe.Production},e.prototype.mapToBraintreeShippingAddressOverride=function(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}},e.prototype.mapToLegacyShippingAddress=function(e){var t=e.email,n=e.phone,r=e.shippingAddress,i=((null==r?void 0:r.recipientName)||"").split(" ");return{email:t,first_name:i[0]||"",last_name:i[1]||"",phone_number:n,address_line_1:null==r?void 0:r.line1,address_line_2:null==r?void 0:r.line2,city:null==r?void 0:r.city,state:null==r?void 0:r.state,country_code:null==r?void 0:r.countryCode,postal_code:null==r?void 0:r.postalCode}},e.prototype.mapToLegacyBillingAddress=function(e){var t=e.billingAddress,n=e.email,r=e.firstName,i=e.lastName,o=e.phone,a=e.shippingAddress,s=t||a;return{email:n,first_name:r,last_name:i,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}},e.prototype.removeElement=function(e){var t=e&&document.getElementById(e);t&&t.remove()},e.prototype.getSessionId=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){switch(e.label){case 0:return[4,this.getDataCollector()];case 1:return[2,e.sent().deviceData]}}))}))},e.prototype.teardown=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){switch(e.label){case 0:return[4,this.teardownModule(this.dataCollectors.default)];case 1:return e.sent(),[4,this.teardownModule(this.dataCollectors.paypal)];case 2:return e.sent(),this.dataCollectors={},[4,this.teardownModule(this.paypalCheckout)];case 3:return e.sent(),this.paypalCheckout=void 0,[2]}}))}))},e.prototype.teardownModule=function(e){return e?e.teardown():Promise.resolve()},e}();const Ze=Je;var Qe="3.81.0",Xe=function(){function e(e,t){this.scriptLoader=e,this.braintreeHostWindow=t}return e.prototype.loadClient=function(){var e;return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this.scriptLoader.loadScript("//js.braintreegateway.com/web/"+Qe+"/js/client.min.js")];case 1:if(t.sent(),!(null===(e=this.braintreeHostWindow.braintree)||void 0===e?void 0:e.client))throw new Re;return[2,this.braintreeHostWindow.braintree.client]}}))}))},e.prototype.loadPaypalCheckout=function(){var e;return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this.scriptLoader.loadScript("//js.braintreegateway.com/web/"+Qe+"/js/paypal-checkout.min.js")];case 1:if(t.sent(),!(null===(e=this.braintreeHostWindow.braintree)||void 0===e?void 0:e.paypalCheckout))throw new Re;return[2,this.braintreeHostWindow.braintree.paypalCheckout]}}))}))},e.prototype.loadBraintreeLocalMethods=function(){var e;return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this.scriptLoader.loadScript("//js.braintreegateway.com/web/"+Qe+"/js/local-payment.min.js")];case 1:if(t.sent(),!(null===(e=this.braintreeHostWindow.braintree)||void 0===e?void 0:e.localPayment))throw new Re;return[2,this.braintreeHostWindow.braintree.localPayment]}}))}))},e.prototype.loadDataCollector=function(){var e;return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this.scriptLoader.loadScript("//js.braintreegateway.com/web/"+Qe+"/js/data-collector.min.js")];case 1:if(t.sent(),!(null===(e=this.braintreeHostWindow.braintree)||void 0===e?void 0:e.dataCollector))throw new Re;return[2,this.braintreeHostWindow.braintree.dataCollector]}}))}))},e.prototype.loadUsBankAccount=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){switch(e.label){case 0:return[4,this.scriptLoader.loadScript("//js.braintreegateway.com/web/"+Qe+"/js/us-bank-account.min.js")];case 1:if(e.sent(),!this.braintreeHostWindow.braintree||!this.braintreeHostWindow.braintree.usBankAccount)throw new Re;return[2,this.braintreeHostWindow.braintree.usBankAccount]}}))}))},e}();const $e=Xe;var et=function(){function e(e,t,n,r){this.paymentIntegrationService=e,this.formPoster=t,this.braintreeIntegrationService=n,this.braintreeHostWindow=r}return e.prototype.initialize=function(e){var t,n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d,l,p,h,m,_,y=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(r=e.braintreepaypal,i=e.methodId,a=(o=r||{}).container,c=o.buttonHeight,u=o.onError,!i)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new ye('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');if(!a)throw new ye('Unable to initialize payment because "options.braintreepaypal.container" argument is not provided.');return[4,this.paymentIntegrationService.loadPaymentMethod(i)];case 1:if(s.sent(),d=this.paymentIntegrationService.getState(),!(l=d.getPaymentMethodOrThrow(i)).clientToken)throw new me(he.MissingPaymentMethod);return p=d.getCartOrThrow().currency.code,h={currency:p,intent:null===(t=l.initializationData)||void 0===t?void 0:t.intent,isCreditEnabled:null===(n=l.initializationData)||void 0===n?void 0:n.isCreditEnabled},m=function(e){y.renderPayPalButton(e,r,a,i,Boolean(l.config.testMode),c)},_=function(e){return y.handleError(e,a,u)},this.braintreeIntegrationService.initialize(l.clientToken),[4,this.braintreeIntegrationService.getPaypalCheckout(h,m,_)];case 2:return s.sent(),[2]}}))}))},e.prototype.deinitialize=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){switch(e.label){case 0:return[4,this.braintreeIntegrationService.teardown()];case 1:return e.sent(),[2]}}))}))},e.prototype.signIn=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return[4,this.paymentIntegrationService.signInCustomer(e,t)];case 1:return n.sent(),[2]}}))}))},e.prototype.signOut=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this.paymentIntegrationService.signOutCustomer(e)];case 1:return t.sent(),[2]}}))}))},e.prototype.executePaymentMethodCheckout=function(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()},e.prototype.renderPayPalButton=function(e,t,n,r,i,o){var a=this;void 0===o&&(o=40);var s=this.braintreeHostWindow.paypal,c=null==s?void 0:s.FUNDING.PAYPAL;if(s&&c){var u=s.Buttons({env:this.braintreeIntegrationService.getBraintreeEnv(i),commit:!1,fundingSource:c,style:{height:o},createOrder:function(){return a.setupPayment(e,t,r)},onApprove:function(n){return a.tokenizePayment(n,e,r,t)}});u.isEligible()&&u.render("#"+n)}else this.braintreeIntegrationService.removeElement(n)},e.prototype.setupPayment=function(e,t,n){var r;return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u,d,l,p,h,m;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return s.trys.push([0,3,,4]),[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:return s.sent(),i=this.paymentIntegrationService.getState(),o=i.getCheckoutOrThrow().outstandingBalance,a=i.getCartOrThrow().currency.code,c=i.getCustomer(),u=i.getPaymentMethodOrThrow(n),d=null==c?void 0:c.addresses[0],l=d?this.braintreeIntegrationService.mapToBraintreeShippingAddressOverride(d):void 0,[4,e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:l,amount:o,currency:a,offerCredit:!1,intent:null===(r=u.initializationData)||void 0===r?void 0:r.intent})];case 2:return[2,s.sent()];case 3:return p=s.sent(),h=t.container,m=t.onError,this.handleError(p,h,m),[3,4];case 4:return[2]}}))}))},e.prototype.tokenizePayment=function(e,t,n,r){return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u,d,l,p,h;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return s.trys.push([0,3,,4]),[4,this.braintreeIntegrationService.getDataCollector({paypal:!0})];case 1:return i=s.sent().deviceData,[4,t.tokenizePayment(e)];case 2:return o=s.sent(),a=o.details,c=o.nonce,u=this.braintreeIntegrationService.mapToLegacyBillingAddress(a),d=this.braintreeIntegrationService.mapToLegacyShippingAddress(a),this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:n,action:"set_external_checkout",nonce:c,device_data:i,billing_address:JSON.stringify(u),shipping_address:JSON.stringify(d)}),[2,o];case 3:return l=s.sent(),p=r.container,h=r.onError,this.handleError(l,p,h),[3,4];case 4:return[2]}}))}))},e.prototype.handleError=function(e,t,n){if(this.braintreeIntegrationService.removeElement(t),!n||!Ve(e))throw e;n(e)},e}();const tt=et,nt=le((function(e){var t=window,n=new Ze(new $e((0,a.getScriptLoader)(),t),t);return new tt(e,(0,xe.createFormPoster)(),n,t)}),[{id:"braintreepaypal"}]),rt=function(e){function t(t){var n=e.call(this,t||"An unexpected error has occurred during buy now cart creation process. Please try again later.")||this;return n.name="BuyNowCartCreationError",n.type="buy_now_cart_creation_error",n}return(0,s.__extends)(t,e),t}(pe);var it,ot,at,st,ct,ut,dt;!function(e){e.BuyNow="BUY_NOW"}(it||(it={})),function(e){e.AUTHORIZE="authorize",e.CAPTURE="capture"}(ot||(ot={})),function(e){e.paypal="paypal",e.checkout="checkout",e.buynow="buynow",e.pay="pay",e.installment="installment"}(at||(at={})),function(e){e.gold="gold",e.blue="blue",e.silver="silver",e.black="black",e.white="white"}(st||(st={})),function(e){e.pill="pill",e.rect="rect"}(ct||(ct={})),function(e){e.OXXO="oxxo"}(ut||(ut={})),function(e){e.Approved="APPROVED",e.Created="CREATED",e.PayerActionRequired="PAYER_ACTION_REQUIRED"}(dt||(dt={}));var lt=function(){function e(e,t,n,r){this.formPoster=e,this.paymentIntegrationService=t,this.paypalCommerceRequestSender=n,this.paypalCommerceScriptLoader=r}return e.prototype.loadPayPalSdk=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return r=this.paymentIntegrationService.getState(),i=t||r.getCartOrThrow().currency.code,o=r.getPaymentMethodOrThrow(e),a=this,[4,this.paypalCommerceScriptLoader.getPayPalSDK(o,i,n)];case 1:return a.paypalSdk=s.sent(),[2,this.paypalSdk]}}))}))},e.prototype.getPayPalSdkOrThrow=function(){if(!this.paypalSdk)throw new Re;return this.paypalSdk},e.prototype.createBuyNowCartOrThrow=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:if(!(t=e.getBuyNowCartRequestBody()))throw new me(he.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.paymentIntegrationService.createBuyNowCart(t)];case 2:return[2,n.sent()];case 3:throw n.sent(),new rt;case 4:return[2]}}))}))},e.prototype.createOrder=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return n=this.paymentIntegrationService.getState().getCartOrThrow().id,[4,this.paypalCommerceRequestSender.createOrder(e,(0,s.__assign)({cartId:n},t))];case 1:return[2,r.sent().orderId]}}))}))},e.prototype.updateOrder=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){var e,t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:e=this.paymentIntegrationService.getState(),t=e.getCartOrThrow(),n=e.getConsignmentsOrThrow()[0],r.label=1;case 1:return r.trys.push([1,3,,4]),[4,this.paypalCommerceRequestSender.updateOrder({availableShippingOptions:n.availableShippingOptions,cartId:t.id,selectedShippingOption:n.selectedShippingOption})];case 2:return r.sent(),[3,4];case 3:throw r.sent(),new ke;case 4:return[2]}}))}))},e.prototype.getOrderStatus=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,this.paypalCommerceRequestSender.getOrderStatus()];case 1:return[2,e.sent().status];case 2:throw e.sent(),new ke;case 3:return[2]}}))}))},e.prototype.tokenizePayment=function(e,t){var n=this.paymentIntegrationService.getState().getCartOrThrow();if(!t)throw new me(he.MissingOrderId);return this.formPoster.postForm("/checkout.php",(0,s.__assign)({payment_type:"paypal",action:"set_external_checkout",provider:e,order_id:t},n.source===it.BuyNow&&{cart_id:n.id}))},e.prototype.submitPayment=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return n={formattedPayload:{vault_payment_instrument:null,set_as_default_stored_instrument:null,device_info:null,method_id:e,paypal_account:{order_id:t}}},[4,this.paymentIntegrationService.submitPayment({methodId:e,paymentData:n})];case 1:return r.sent(),[2]}}))}))},e.prototype.getShippingOptionOrThrow=function(e){var t=this.paymentIntegrationService.getState().getConsignmentsOrThrow()[0],n=t.availableShippingOptions||[],r=n.find((function(e){return e.isRecommended})),i=e?n.find((function(t){return t.id===e})):n.find((function(e){var n;return e.id===(null===(n=t.selectedShippingOption)||void 0===n?void 0:n.id)})),o=i||r||n[0];if(!o)throw new Error("Your order can't be shipped to this address");return o},e.prototype.getAddress=function(e){return{firstName:(null==e?void 0:e.firstName)||"",lastName:(null==e?void 0:e.lastName)||"",email:(null==e?void 0:e.email)||"",phone:"",company:"",address1:(null==e?void 0:e.address1)||"",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:[]}},e.prototype.getBillingAddressFromOrderDetails=function(e){var t=e.payer;return this.getAddress({firstName:t.name.given_name,lastName:t.name.surname,email:t.email_address,address1:t.address.address_line_1,city:t.address.admin_area_2,countryCode:t.address.country_code,postalCode:t.address.postal_code,stateOrProvinceCode:t.address.admin_area_1})},e.prototype.getShippingAddressFromOrderDetails=function(e){var t,n,r=e.payer,i=(null===(n=null===(t=e.purchase_units[0])||void 0===t?void 0:t.shipping)||void 0===n?void 0:n.address)||{};return this.getAddress({firstName:r.name.given_name,lastName:r.name.surname,email:r.email_address,address1:i.address_line_1,city:i.admin_area_2,countryCode:i.country_code,postalCode:i.postal_code,stateOrProvinceCode:i.admin_area_1})},e.prototype.getValidButtonStyle=function(e){var t=e||{},n=t.color,r=t.height,i=t.label,o=t.shape,a={color:n&&st[n]?n:void 0,height:this.getValidHeight(r),label:i&&at[i]?i:void 0,shape:o&&ct[o]?o:void 0};return(0,Z.omitBy)(a,Z.isNil)},e.prototype.getValidHeight=function(e){return e&&"number"==typeof e?e>55?55:e<25?25:e:40},e.prototype.removeElement=function(e){var t=e&&document.getElementById(e);t&&t.remove()},e}();const pt=lt;var ht,mt="This API endpoint is for internal use only and may change in the future";!function(e){e.Json="application/json",e.JsonV1="application/vnd.bc.v1+json"}(ht||(ht={}));const _t=ht;var yt={"X-Checkout-SDK-Version":"1.398.2"},ft=function(){function e(e){this.requestSender=e}return e.prototype.createOrder=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:return n="/api/storefront/payment/"+e,r=t,i=(0,s.__assign)({"X-API-INTERNAL":mt,"Content-Type":_t.Json},yt),[4,this.requestSender.post(n,{headers:i,body:r})];case 1:return[2,o.sent().body]}}))}))},e.prototype.updateOrder=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return t=e,n=(0,s.__assign)({"X-API-INTERNAL":mt,"Content-Type":_t.Json},yt),[4,this.requestSender.put("/api/storefront/initialization/paypalcommerce",{headers:n,body:t})];case 1:return[2,r.sent().body]}}))}))},e.prototype.getOrderStatus=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){var e;return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return e=(0,s.__assign)({"X-API-INTERNAL":mt,"Content-Type":_t.Json},yt),[4,this.requestSender.get("/api/storefront/initialization/paypalcommerce",{headers:e})];case 1:return[2,t.sent().body]}}))}))},e}();const gt=ft;var vt=function(){function e(e){this.scriptLoader=e,this.window=window}return e.prototype.getPayPalSDK=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return this.paypalSdk?[3,2]:(r=this,[4,this.loadPayPalSDK(this.getPayPalSdkScriptConfigOrThrow(e,t,n))]);case 1:r.paypalSdk=i.sent(),i.label=2;case 2:return[2,this.paypalSdk]}}))}))},e.prototype.loadPayPalSDK=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return this.window.paypalLoadScript?[3,2]:[4,this.scriptLoader.loadScript("https://unpkg.com/@paypal/paypal-js@5.0.5/dist/iife/paypal-js.min.js",{async:!0,attributes:{}})];case 1:if(t.sent(),!this.window.paypalLoadScript)throw new Re;t.label=2;case 2:return[4,this.window.paypalLoadScript(e)];case 3:if(t.sent(),!this.window.paypal)throw new Re;return[2,this.window.paypal]}}))}))},e.prototype.getPayPalSdkScriptConfigOrThrow=function(e,t,n){void 0===n&&(n=!0);var r=e.id,i=e.clientToken,o=e.initializationData;if(!(null==o?void 0:o.clientId))throw new me(he.MissingPaymentMethod);var a=o.intent,c=o.clientId,u=o.merchantId,d=o.buyerCountry,l=o.attributionId,p=o.isVenmoEnabled,h=o.isHostedCheckoutEnabled,m=o.isPayPalCreditAvailable,_=o.isDeveloperModeApplicable,y=o.availableAlternativePaymentMethods,f=void 0===y?[]:y,g=o.enabledAlternativePaymentMethods,v=void 0===g?[]:g,w=h||n,C="paypalcommercecreditcards"===r,S=C?["card"]:[],I=C?[]:["card"],b=m?["credit","paylater"]:[],P=m?[]:["credit","paylater"],E=n||!w,A=E&&p?["venmo"]:[],O=E&&p?[]:["venmo"],k=E?v:[],T=E?f.filter((function(e){return!v.includes(e)})):f,M=(0,s.__spreadArrays)(I,P,O,T),D=(0,s.__spreadArrays)(S,b,A,k);return(0,s.__assign)({"client-id":c,"data-partner-attribution-id":l,"data-client-token":i,"merchant-id":u,"enable-funding":D.length>0?D:void 0,"disable-funding":M.length>0?M:void 0,commit:w,components:["buttons","hosted-fields","messages","payment-fields"],currency:t,intent:a},_&&{"buyer-country":d})},e}();const wt=vt,Ct=function(e){var t=e.getState().getHost;return new pt((0,xe.createFormPoster)(),e,new gt((0,o.createRequestSender)({host:t()})),new wt((0,a.getScriptLoader)()))};var St=function(){function e(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.onError=Z.noop}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:if(t=e.paypalcommerce,!(n=e.methodId))throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new ye('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');if(!t.container)throw new ye('Unable to initialize payment because "options.paypalcommerce.container" argument is not provided.');return this.onError=t.onError||Z.noop,[4,this.paymentIntegrationService.loadPaymentMethod(n)];case 1:return r.sent(),[4,this.paypalCommerceIntegrationService.loadPayPalSdk(n)];case 2:return r.sent(),this.renderButton(n,t),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.signIn=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return[4,this.paymentIntegrationService.signInCustomer(e,t)];case 1:return n.sent(),[2,Promise.resolve()]}}))}))},e.prototype.signOut=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this.paymentIntegrationService.signOutCustomer(e)];case 1:return t.sent(),[2,Promise.resolve()]}}))}))},e.prototype.executePaymentMethodCheckout=function(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()},e.prototype.renderButton=function(e,t){var n=this,r=t.container,i=t.onComplete,o=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),a=(this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData||{}).isHostedCheckoutEnabled,c={createOrder:function(){return n.paypalCommerceIntegrationService.createOrder("paypalcommerce")},onApprove:function(t){var r=t.orderID;return n.paypalCommerceIntegrationService.tokenizePayment(e,r)}},u={onShippingAddressChange:function(e){return n.onShippingAddressChange(e)},onShippingOptionsChange:function(e){return n.onShippingOptionsChange(e)},onApprove:function(t,r){return n.onHostedCheckoutApprove(t,r,e,i)}},d=(0,s.__assign)((0,s.__assign)({fundingSource:o.FUNDING.PAYPAL,style:this.paypalCommerceIntegrationService.getValidButtonStyle()},c),a&&u),l=o.Buttons(d);l.isEligible()?l.render("#"+r):this.paypalCommerceIntegrationService.removeElement(r)},e.prototype.onHostedCheckoutApprove=function(e,t,n,r){return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!e.orderID)throw new me(he.MissingOrderId);return i=this.paymentIntegrationService.getState().getCartOrThrow(),[4,t.order.get()];case 1:o=s.sent(),s.label=2;case 2:return s.trys.push([2,9,,10]),a=this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(o),[4,this.paymentIntegrationService.updateBillingAddress(a)];case 3:return s.sent(),i.lineItems.physicalItems.length>0?(c=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(o),[4,this.paymentIntegrationService.updateShippingAddress(c)]):[3,6];case 4:return s.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:s.sent(),s.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return s.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,e.orderID)];case 8:return s.sent(),r&&"function"==typeof r&&r(),[3,10];case 9:return u=s.sent(),this.handleError(u),[3,10];case 10:return[2]}}))}))},e.prototype.onShippingAddressChange=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:t=this.paypalCommerceIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.country_code,postalCode:e.shippingAddress.postal_code,stateOrProvinceCode:e.shippingAddress.state}),i.label=1;case 1:return i.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(t)];case 2:return i.sent(),[4,this.paymentIntegrationService.updateShippingAddress(t)];case 3:return i.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return i.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return i.sent(),[3,7];case 6:return r=i.sent(),this.handleError(r),[3,7];case 7:return[2]}}))}))},e.prototype.onShippingOptionsChange=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:t=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(t.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:return n=r.sent(),this.handleError(n),[3,5];case 5:return[2]}}))}))},e.prototype.handleError=function(e){if("function"!=typeof this.onError)throw e;this.onError(e)},e}();const It=St,bt=le((function(e){return new It(e,Ct(e))}),[{id:"paypalcommerce"}]);var Pt=function(){function e(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.onError=Z.noop}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:if(t=e.paypalcommercecredit,!(n=e.methodId))throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new ye('Unable to initialize payment because "paypalcommercecredit" argument is not provided.');if(!t.container)throw new ye('Unable to initialize payment because "paypalcommercecredit.container" argument is not provided.');return this.onError=t.onError||Z.noop,[4,this.paymentIntegrationService.loadPaymentMethod(n)];case 1:return r.sent(),[4,this.paypalCommerceIntegrationService.loadPayPalSdk(n)];case 2:return r.sent(),this.renderButton(n,t),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.signIn=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return[4,this.paymentIntegrationService.signInCustomer(e,t)];case 1:return n.sent(),[2]}}))}))},e.prototype.signOut=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this.paymentIntegrationService.signOutCustomer(e)];case 1:return t.sent(),[2]}}))}))},e.prototype.executePaymentMethodCheckout=function(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()},e.prototype.renderButton=function(e,t){var n=this,r=t.container,i=t.onComplete,o=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),a=(this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData||{}).isHostedCheckoutEnabled,c={createOrder:function(){return n.paypalCommerceIntegrationService.createOrder("paypalcommercecredit")},onApprove:function(t){var r=t.orderID;return n.paypalCommerceIntegrationService.tokenizePayment(e,r)}},u={onShippingAddressChange:function(e){return n.onShippingAddressChange(e)},onShippingOptionsChange:function(e){return n.onShippingOptionsChange(e)},onApprove:function(t,r){return n.onHostedCheckoutApprove(t,r,e,i)}},d=[o.FUNDING.PAYLATER,o.FUNDING.CREDIT],l=!1;d.forEach((function(e){if(!l){var t=(0,s.__assign)((0,s.__assign)({fundingSource:e,style:n.paypalCommerceIntegrationService.getValidButtonStyle({color:st.gold})},c),a&&u),i=o.Buttons(t);i.isEligible()&&(i.render("#"+r),l=!0)}})),l||this.paypalCommerceIntegrationService.removeElement(r)},e.prototype.onHostedCheckoutApprove=function(e,t,n,r){return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!e.orderID)throw new me(he.MissingOrderId);return i=this.paymentIntegrationService.getState().getCartOrThrow(),[4,t.order.get()];case 1:o=s.sent(),s.label=2;case 2:return s.trys.push([2,9,,10]),a=this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(o),[4,this.paymentIntegrationService.updateBillingAddress(a)];case 3:return s.sent(),i.lineItems.physicalItems.length>0?(c=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(o),[4,this.paymentIntegrationService.updateShippingAddress(c)]):[3,6];case 4:return s.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:s.sent(),s.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return s.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,e.orderID)];case 8:return s.sent(),r&&"function"==typeof r&&r(),[3,10];case 9:return u=s.sent(),this.handleError(u),[3,10];case 10:return[2]}}))}))},e.prototype.onShippingAddressChange=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:t=this.paypalCommerceIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.country_code,postalCode:e.shippingAddress.postal_code,stateOrProvinceCode:e.shippingAddress.state}),i.label=1;case 1:return i.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(t)];case 2:return i.sent(),[4,this.paymentIntegrationService.updateShippingAddress(t)];case 3:return i.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return i.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return i.sent(),[3,7];case 6:return r=i.sent(),this.handleError(r),[3,7];case 7:return[2]}}))}))},e.prototype.onShippingOptionsChange=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:t=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(t.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:return n=r.sent(),this.handleError(n),[3,5];case 5:return[2]}}))}))},e.prototype.handleError=function(e){if("function"!=typeof this.onError)throw e;this.onError(e)},e}();const Et=Pt,At=le((function(e){return new Et(e,Ct(e))}),[{id:"paypalcommercecredit"}]);var Ot=function(){function e(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:if(t=e.paypalcommercevenmo,!(n=e.methodId))throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new ye('Unable to initialize payment because "paypalcommercevenmo" argument is not provided.');if(!t.container)throw new ye('Unable to initialize payment because "paypalcommercevenmo.container" argument is not provided.');return[4,this.paymentIntegrationService.loadPaymentMethod(n)];case 1:return r.sent(),[4,this.paypalCommerceIntegrationService.loadPayPalSdk(n)];case 2:return r.sent(),this.renderButton(n,t.container),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.signIn=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return[4,this.paymentIntegrationService.signInCustomer(e,t)];case 1:return n.sent(),[2]}}))}))},e.prototype.signOut=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this.paymentIntegrationService.signOutCustomer(e)];case 1:return t.sent(),[2]}}))}))},e.prototype.executePaymentMethodCheckout=function(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve()},e.prototype.renderButton=function(e,t){var n=this,r=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),i={fundingSource:r.FUNDING.VENMO,style:this.paypalCommerceIntegrationService.getValidButtonStyle(),createOrder:function(){return n.paypalCommerceIntegrationService.createOrder("paypalcommercevenmo")},onApprove:function(t){var r=t.orderID;return n.paypalCommerceIntegrationService.tokenizePayment(e,r)}},o=r.Buttons(i);o.isEligible()?o.render("#"+t):this.paypalCommerceIntegrationService.removeElement(t)},e}();const kt=Ot,Tt=le((function(e){return new kt(e,Ct(e))}),[{id:"paypalcommercevenmo"}]);function Mt(t,n){void 0===n&&(n=e);for(var r=new de,i=function(e){if(!oe(e))return"continue";for(var n=0,i=e.resolveIds;n=400&&e.status<500)throw new q(e);throw e}))},e.prototype.updateCheckout=function(e,t,n){var r=void 0===n?{}:n,i=r.params,o=(void 0===i?{}:i).include,a=r.timeout,c="/api/storefront/checkout/"+e,u=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.put(c,{params:{include:xt(K,o)},body:t,headers:u,timeout:a})},e}();const Vt=qt;var Gt;!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"}(Gt||(Gt={}));var Ht=function(){function e(e,t,n){this._checkoutRequestSender=e,this._configActionCreator=t,this._formFieldsActionCreator=n}return e.prototype.loadCheckout=function(e,t){var n=this;return(0,u.concat)((0,u.of)((0,c.createAction)(Gt.LoadCheckoutRequested)),(0,u.merge)(this._configActionCreator.loadConfig((0,s.__assign)((0,s.__assign)({},t),{useCache:!0,params:(0,s.__assign)((0,s.__assign)({},null==t?void 0:t.params),{checkoutId:e})})),this._formFieldsActionCreator.loadFormFields((0,s.__assign)((0,s.__assign)({},t),{useCache:!0})),(0,u.defer)((function(){return n._checkoutRequestSender.loadCheckout(e,t).then((function(e){var t=e.body;return(0,c.createAction)(Gt.LoadCheckoutSucceeded,t)}))})))).pipe((0,d.catchError)((function(e){return l(Gt.LoadCheckoutFailed,e)})))},e.prototype.loadDefaultCheckout=function(e){var t=this;return function(n){return(0,u.concat)((0,u.of)((0,c.createAction)(Gt.LoadCheckoutRequested)),(0,u.merge)(t._configActionCreator.loadConfig(),t._formFieldsActionCreator.loadFormFields((0,s.__assign)((0,s.__assign)({},e),{useCache:!0}))),(0,u.defer)((function(){return(0,s.__awaiter)(t,void 0,void 0,(function(){var t,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(t=n.getState(),!(r=t.config.getContextConfig())||!r.checkoutId)throw new m(h.MissingCheckoutConfig);return[4,this._checkoutRequestSender.loadCheckout(r.checkoutId,e)];case 1:return i=o.sent().body,[2,(0,c.createAction)(Gt.LoadCheckoutSucceeded,i)]}}))}))}))).pipe((0,d.catchError)((function(e){return l(Gt.LoadCheckoutFailed,e)})))}},e.prototype.updateCheckout=function(e,t){var n=this;return function(r){return new u.Observable((function(i){var o=r.getState().checkout.getCheckout();if(!o)throw new m(h.MissingCheckout);i.next((0,c.createAction)(Gt.UpdateCheckoutRequested)),n._checkoutRequestSender.updateCheckout(o.id,e,t).then((function(e){var t=e.body;i.next((0,c.createAction)(Gt.UpdateCheckoutSucceeded,t)),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(Gt.UpdateCheckoutFailed,e))}))}))}},e.prototype.loadCurrentCheckout=function(e){var t=this;return function(n){var r=n.getState().checkout.getCheckout();if(!r)throw new m(h.MissingCheckout);return t.loadCheckout(r.id,e)}},e}();const Yt=Ht;var jt;!function(e){e.LoadFormFieldsRequested="LOAD_FORM_FIELDS_REQUESTED",e.LoadFormFieldsSucceeded="LOAD_FORM_FIELDS_SUCCEEDED",e.LoadFormFieldsFailed="LOAD_FORM_FIELDS_FAILED"}(jt||(jt={}));var Wt=function(){function e(e){this._formFieldsRequestSender=e}return e.prototype.loadFormFields=function(e){var t=this;return(0,u.concat)((0,u.of)((0,c.createAction)(jt.LoadFormFieldsRequested)),(0,u.defer)((function(){return(0,s.__awaiter)(t,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return[4,this._formFieldsRequestSender.loadFields(e)];case 1:return t=n.sent().body,[2,(0,c.createAction)(jt.LoadFormFieldsSucceeded,t)]}}))}))}))).pipe((0,d.catchError)((function(e){return l(jt.LoadFormFieldsFailed,e)})))},(0,s.__decorate)([N],e.prototype,"loadFormFields",null),e}();const Kt=Wt;var Jt=function(){function e(e){this._requestSender=e}return e.prototype.loadFields=function(e){var t=(void 0===e?{}:e).timeout;return this._requestSender.get("/api/storefront/form-fields",{timeout:t,headers:(0,s.__assign)({Accept:w.JsonV1,"X-API-INTERNAL":V},C)})},e}();const Zt=Jt;var Qt;!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"}(Qt||(Qt={}));var Xt=function(){function e(e){this._requestSender=e}return e.prototype.loadPaymentMethods=function(e){var t=this;return function(n){return u.Observable.create((function(r){var i=n.getState().cart.getCartOrThrow();r.next((0,c.createAction)(Qt.LoadPaymentMethodsRequested)),t._requestSender.loadPaymentMethods((0,s.__assign)((0,s.__assign)({},e),{params:(0,s.__assign)((0,s.__assign)({},null==e?void 0:e.params),{cartId:i.id})})).then((function(e){var n={deviceSessionId:e.headers["x-device-session-id"],sessionHash:e.headers["x-session-hash"]},i=e.body,o=Array.isArray(i)?t._filterApplePay(i):i;r.next((0,c.createAction)(Qt.LoadPaymentMethodsSucceeded,o,n)),r.complete()})).catch((function(e){r.error((0,c.createErrorAction)(Qt.LoadPaymentMethodsFailed,e))}))}))}},e.prototype.loadPaymentMethod=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o,a=null===(o=r.getState().cart.getCart())||void 0===o?void 0:o.id,u=a?(0,s.__assign)((0,s.__assign)({},null==t?void 0:t.params),{cartId:a}):(0,s.__assign)({},null==t?void 0:t.params);i.next((0,c.createAction)(Qt.LoadPaymentMethodRequested,void 0,{methodId:e})),n._requestSender.loadPaymentMethod(e,(0,s.__assign)((0,s.__assign)({},t),{params:u})).then((function(t){i.next((0,c.createAction)(Qt.LoadPaymentMethodSucceeded,t.body,{methodId:e})),i.complete()})).catch((function(t){i.error((0,c.createErrorAction)(Qt.LoadPaymentMethodFailed,t,{methodId:e}))}))}))}},e.prototype._filterApplePay=function(e){return(0,Z.filter)(e,(function(e){return!("applepay"===e.id&&!function(e){return"ApplePaySession"in e}(window))}))},(0,s.__decorate)([N],e.prototype,"loadPaymentMethod",null),e}();const $t=Xt;var en=function(){function e(e){this._requestSender=e}return e.prototype.loadPaymentMethods=function(e){var t=void 0===e?{}:e,n=t.timeout,r=t.params;return this._requestSender.get("/api/storefront/payments",{timeout:n,headers:(0,s.__assign)({Accept:w.JsonV1,"X-API-INTERNAL":V},C),params:r})},e.prototype.loadPaymentMethod=function(e,t){var n=void 0===t?{}:t,r=n.timeout,i=n.params,o="/api/storefront/payments/"+e;return this._requestSender.get(o,{timeout:r,headers:(0,s.__assign)({Accept:w.JsonV1,"X-API-INTERNAL":V},C),params:i})},e}();const tn=en;var nn=function(){function e(e){this._requestSender=e}return e.prototype.createBuyNowCart=function(e,t){var n=(void 0===t?{}:t).timeout,r=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.post("/api/storefront/carts",{body:e,headers:r,timeout:n})},e}();const rn=nn,on=function(){function e(){}return e.prototype.isEqual=function(e,t){return(0,Z.isEqual)(this._normalize(e),this._normalize(t))},e.prototype._normalize=function(e){return{cartAmount:e.cartAmount,currency:e.currency,id:e.id,lineItems:{digitalItems:e.lineItems.digitalItems.slice().sort((function(e,t){return(""+e.productId+e.variantId).localeCompare(""+t.productId+t.variantId)})).map((function(e){return{extendedSalePrice:e.extendedSalePrice,productId:e.productId,quantity:e.quantity,variantId:e.variantId}})),giftCertificates:e.lineItems.giftCertificates.slice().sort((function(e,t){return(""+e.id).localeCompare(""+t.id)})).map((function(e){return{amount:e.amount,recipient:e.recipient}})),physicalItems:e.lineItems.physicalItems.slice().sort((function(e,t){return(""+e.productId+e.variantId).localeCompare(""+t.productId+t.variantId)})).map((function(e){return{extendedSalePrice:e.extendedSalePrice,productId:e.productId,quantity:e.quantity,variantId:e.variantId,giftWrapping:e.giftWrapping}}))}}},e}(),an=function(e){function t(t,n){var r=e.call(this,"An update to your shopping cart has been detected and your available shipping costs have been updated.")||this;return r.name="CartChangedError",r.type="cart_changed",r.data={previous:t,updated:n},r}return(0,s.__extends)(t,e),t}(p),sn=function(){function e(e){this._checkoutRequestSender=e}return e.prototype.validate=function(e,t){var n=this;if(!e)throw new m(h.MissingCheckout);return this._checkoutRequestSender.loadCheckout(e.id,t).then((function(t){var r=new on;if(!(e.outstandingBalance===t.body.outstandingBalance&&n._compareCoupons(e.coupons,t.body.coupons)&&n._compareGiftCertificates(e.giftCertificates,t.body.giftCertificates)&&r.isEqual(e.cart,t.body.cart)))throw new an(n._getComparableCheckout(e),n._getComparableCheckout(t.body))}))},e.prototype._compareCoupons=function(e,t){return(0,Z.isEqual)((0,Z.map)(e,"code"),(0,Z.map)(t,"code"))},e.prototype._compareGiftCertificates=function(e,t){return(0,Z.isEqual)((0,Z.map)(e,"code"),(0,Z.map)(t,"code"))},e.prototype._getComparableCheckout=function(e){var t=e.cart,n=e.coupons,r=e.giftCertificates,i=e.outstandingBalance;return{cart:{cartAmount:t.cartAmount,currency:t.currency,lineItems:t.lineItems},coupons:n,giftCertificates:r,outstandingBalance:i}},e}(),cn=function(e){var t=this,n=new Promise((function(e,n){t.cancel=n}));this.promise=Promise.race([e,n])},un=function(e){function t(t){var n=e.call(this,t||"Unable to proceed because the required element is unexpectedly detached from the page.")||this;return n.name="UnexpectedDetachmentError",n.type="unexpected_detachment",n}return(0,s.__extends)(t,e),t}(p);var dn=function(){function e(e){this._mutationObserver=e}return e.prototype.ensurePresence=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:n=new cn(t),(r=this._mutationObserver.create((function(t){t.forEach((function(t){0!==Array.from(t.removedNodes).filter((function(t){return e.some((function(e){return t===e||t.contains(e)}))})).length&&n.cancel(new un)}))}))).observe(document.body,{childList:!0,subtree:!0}),a.label=1;case 1:return a.trys.push([1,3,,4]),[4,n.promise];case 2:return i=a.sent(),r.disconnect(),[2,i];case 3:throw o=a.sent(),r.disconnect(),o;case 4:return[2]}}))}))},e}();const ln=dn;var pn=function(){function e(e){void 0===e&&(e=window),this._window=e}return e.prototype.create=function(e){return new this._window.MutationObserver(e)},e}();function hn(e){if(!/^(https?:)?\/\//.test(e))throw new ae("The provided URL must be absolute.");var t=document.createElement("a");t.href=e;var n=t.port&&-1!==e.indexOf(t.hostname+":"+t.port)?t.port:"";return{hash:t.hash,hostname:t.hostname,href:t.href,origin:t.protocol+"//"+t.hostname+(n?":"+n:""),pathname:t.pathname,port:n,protocol:t.protocol,search:t.search}}function mn(e,t){return e.type===t}const _n=function(){function e(e,t){this._targetWindow=t,this._targetOrigin="*"===e?"*":hn(e).origin}return e.prototype.post=function(e,t){var n=this,r=this._targetWindow;if(window!==r){if(!r)throw new Error("Unable to post message because target window is not set.");var i=t&&(0,u.fromEvent)(window,"message").pipe((0,d.filter)((function(e){return e.origin===n._targetOrigin&&mn(e.data,e.data.type)&&-1!==[t.successType,t.errorType].indexOf(e.data.type)})),(0,d.map)((function(e){if(t.errorType===e.data.type)throw e.data;return e.data})),(0,d.take)(1)).toPromise();return r.postMessage(e,this._targetOrigin),i}},e.prototype.setTarget=function(e){this._targetWindow=e},e}();const yn=function(e,t,n){return t&&n?fn(0,t,n):function(e){var t=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return(0,s.__extends)(t,e),t}(e);return Object.getOwnPropertyNames(e.prototype).forEach((function(n){var r=Object.getOwnPropertyDescriptor(e.prototype,n);r&&"constructor"!==n&&Object.defineProperty(t.prototype,n,fn(e.prototype,n,r))})),t}(e)};function fn(e,t,n){if("function"!=typeof n.value)return n;var r=n.value;return{get:function(){var e=r.bind(this);return Object.defineProperty(this,t,(0,s.__assign)((0,s.__assign)({},n),{value:e})),e},set:function(e){r=e}}}const gn=function(){function e(e){var t;this._sourceOrigins=[hn(e).origin,(t=hn(e),hn(0===t.hostname.indexOf("www")?t.href:t.href.replace(t.hostname,"www."+t.hostname))).origin],this._isListening=!1,this._listeners={}}return e.prototype.listen=function(){this._isListening||(this._isListening=!0,window.addEventListener("message",this._handleMessage))},e.prototype.stopListen=function(){this._isListening&&(this._isListening=!1,window.removeEventListener("message",this._handleMessage))},e.prototype.addListener=function(e,t){var n=this._listeners[e];n||(this._listeners[e]=n=[]),-1===n.indexOf(t)&&n.push(t)},e.prototype.removeListener=function(e,t){var n=this._listeners[e];if(n){var r=n.indexOf(t);r>=0&&n.splice(r,1)}},e.prototype.trigger=function(e){var t=this._listeners[e.type];t&&t.forEach((function(t){return t(e)}))},e.prototype._handleMessage=function(e){-1!==this._sourceOrigins.indexOf(e.origin)&&mn(e.data,e.data.type)&&this.trigger(e.data)},(0,s.__decorate)([yn],e.prototype,"_handleMessage",null),e}(),vn=function(e){function t(){var t=e.call(this,"You haven't complete our spam protection challenge. Please try again.")||this;return t.name="SpamProtectionChallengeNotCompletedError",t.type="spam_protection_challenge_not_completed",t}return(0,s.__extends)(t,e),t}(p),wn=function(e){function t(){var t=e.call(this,"Please complete our human verification challenge and try again.")||this;return t.name="CardingProtectionChallengeNotCompletedError",t.type="carding_protection_challenge_not_completed",t}return(0,s.__extends)(t,e),t}(p),Cn=function(e){function t(){var t=e.call(this,"We were not able to verify that you are not a robot. Please try again.")||this;return t.name="CardingProtectionFailedError",t.type="carding_protection_failed",t}return(0,s.__extends)(t,e),t}(p);var Sn=function(){function e(e){this._googleRecaptcha=e}return e.prototype.handle=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){return"string"==typeof e?[2,this.handleWithRecaptchaSitekey(e,t)]:[2,this.handleWithPaymentHumanVerificationRequestError(e)]}))}))},e.prototype.handleWithPaymentHumanVerificationRequestError=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:if(!this._isPaymentHumanVerificationRequest(e))throw e;return[4,this._initialize(e.body.additional_action_required.data.key)];case 1:return t.sent(),[2,this._performRecaptcha()]}}))}))},e.prototype.handleWithRecaptchaSitekey=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){switch(n.label){case 0:if("recaptcha_v2"!==e)throw Error("Human verification method is not supported.");if(!t)throw Error("Recaptcha site key is missing.");return[4,this._initialize(t)];case 1:return n.sent(),[2,this._performRecaptcha()]}}))}))},e.prototype._performRecaptcha=function(){var e=this;return this._googleRecaptcha.execute().pipe((0,d.take)(1)).pipe((0,d.switchMap)((function(t){var n=t.error,r=t.token;return(0,s.__awaiter)(e,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){if(n instanceof vn)throw new wn;if(n||!r)throw new Cn;return[2,{type:"recaptcha_v2_verification",data:{human_verification_token:r}}]}))}))}))).toPromise()},e.prototype._initialize=function(e){var t="cardingProtectionContainer",n=document.getElementById(t);return n&&n.parentNode&&n.parentNode.removeChild(n),(n=document.createElement("div")).setAttribute("id",t),document.body.appendChild(n),this._googleRecaptcha.load(t,e)},e.prototype._isPaymentHumanVerificationRequest=function(e){var t=e.body||{},n=t.additional_action_required;return"additional_action_required"===t.status&&n&&"recaptcha_v2_verification"===n.type},e}();const In=Sn;var bn;!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"}(bn||(bn={}));const Pn=function(e){function t(t){var n=e.call(this,function(e){switch(e){case bn.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case bn.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case bn.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case bn.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."}}(t))||this;return n.subtype=t,n.name="NotInitializedError",n.type="not_initialized",n}return(0,s.__extends)(t,e),t}(p),En=function(e){function t(){var t=e.call(this,"We were not able to complete your spam protection verification. Please try again.")||this;return t.name="SpamProtectionFailedError",t.type="spam_protection_failed",t}return(0,s.__extends)(t,e),t}(p),An=function(e){function t(){var t=e.call(this,"Spam protection is not loaded. Please try again.")||this;return t.name="SpamProtectionNotLoadedError",t.type="spam_protection_failed",t}return(0,s.__extends)(t,e),t}(p),On=function(){function e(e,t){var n=this;this.googleRecaptchaScriptLoader=e,this.mutationObserverFactory=t,this._memoized=(0,z.memoize)((function(e,t,r){var i=new u.Subject;if(!r)throw new Error;return n._widgetId=e.render(r.id,{sitekey:t,size:"invisible",callback:function(){i.next({token:e.getResponse(n._widgetId)}),e.reset(n._widgetId)},"error-callback":function(){i.next({error:new En})}}),i}),{isEqual:function(e,t){return e===t}})}return e.prototype.load=function(e,t){var n=this;return this.googleRecaptchaScriptLoader.load().then((function(r){r&&(n._event$=n._memoized(r,t,document.getElementById(e)),n._recaptcha=r)}))},e.prototype.execute=function(){var e=this;return(0,u.defer)((function(){var t=e._event$,n=e._recaptcha;if(!t||!n)throw new Pn(bn.SpamProtectionNotInitialized);return(0,u.defer)((function(){var e=document.querySelector('iframe[src*="bframe"]');return e?(0,u.of)(e):(0,u.throwError)(new An)})).pipe((0,d.retryWhen)((function(e){return e.pipe((0,d.delay)(250),(0,d.switchMap)((function(e,t){return t<28?(0,u.of)(e):(0,u.throwError)(e)})))})),(0,d.switchMap)((function(r){return e._watchRecaptchaChallengeWindow(t,r),n.execute(e._widgetId),t})),(0,d.catchError)((function(e){return(0,u.of)({error:e})})))}))},e.prototype._watchRecaptchaChallengeWindow=function(e,t){var n=t.parentElement;if(!n)throw new An;var r=n.parentElement;if(!r)throw new An;this.mutationObserverFactory.create((function(){"hidden"===r.style.visibility&&e.next({error:new vn})})).observe(r,{attributes:!0,attributeFilter:["style"]})},e}(),kn=function(){function e(e,t){void 0===t&&(t=window),this._scriptLoader=e,this._window=t}return e.prototype.load=function(){return this._loadPromise||(this._loadPromise=this._loadScript()),this._loadPromise},e.prototype._loadScript=function(){var e=this,t="initRecaptcha",n=["onload="+t,"render=explicit"].join("&");return new Promise((function(r,i){e._window[t]=function(){return r(e._window.grecaptcha)},e._scriptLoader.loadScript("//www.google.com/recaptcha/api.js?"+n).catch((function(t){e._loadPromise=void 0,i(t)}))}))},e}();function Tn(e){return new On(new kn(e),new pn)}function Mn(e,t){var n=e.body.errors,r=void 0===n?[]:n;return new x(e,{message:Dn(r)||t,errors:r})}function Dn(e){if(Array.isArray(e))return e.reduce((function(e,t){return t&&t.message?(0,s.__spreadArrays)(e,[t.message]):e}),[]).join(" ")}const Rn=function(e){function t(t){var n=e.call(this,t||"Unable to proceed due to invalid configuration provided for the hosted payment form.")||this;return n.name="InvalidHostedFormConfigError",n.type="invalid_hosted_form_config",n}return(0,s.__extends)(t,e),t}(p),zn=function(e){function t(t){var n=e.call(this,t||"Unable to proceed due to an unknown error with the hosted payment form.")||this;return n.name="InvalidHostedFormError",n.type="invalid_hosted_form",n}return(0,s.__extends)(t,e),t}(p);var Nn=function(e){function t(t){var n=e.call(this,(0,s.__spreadArrays)(["Unable to proceed due to invalid user input values"],(0,Z.flatMap)((0,Z.values)(t),(function(e){return(0,Z.map)(e,(function(e){return e.message}))}))).join(". "))||this;return n.errors=t,n.name="InvalidHostedFormValueError",n.type="invalid_hosted_form_value",n}return(0,s.__extends)(t,e),t}(p);const Ln=Nn;var Fn,Bn;!function(e){e.AttachRequested="HOSTED_FIELD:ATTACH_REQUESTED",e.SubmitRequested="HOSTED_FIELD:SUBMITTED_REQUESTED",e.ValidateRequested="HOSTED_FIELD:VALIDATE_REQUESTED"}(Fn||(Fn={})),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"}(Bn||(Bn={}));var Un=function(){function e(e,t,n,r,i,o,a,s,c){this._type=e,this._containerId=t,this._placeholder=n,this._accessibilityLabel=r,this._styles=i,this._eventPoster=o,this._eventListener=a,this._detachmentObserver=s,this._cardInstrument=c,this._iframe=document.createElement("iframe"),this._iframe.src="/checkout/payment/hosted-field?version=1.398.2",this._iframe.style.border="none",this._iframe.style.height="100%",this._iframe.style.overflow="hidden",this._iframe.style.width="100%"}return e.prototype.getType=function(){return this._type},e.prototype.attach=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){var e,t,n=this;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:if(!(e=document.getElementById(this._containerId)))throw new Rn("Unable to proceed because the provided container ID is not valid.");return e.appendChild(this._iframe),this._eventListener.listen(),t=(0,u.fromEvent)(this._iframe,"load").pipe((0,d.switchMap)((function(e){var t=e.target;return(0,s.__awaiter)(n,void 0,void 0,(function(){var e;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:if(!(e=t&&t.contentWindow))throw new Error("The content window of the iframe cannot be accessed.");return this._eventPoster.setTarget(e),[4,this._eventPoster.post({type:Fn.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:Bn.AttachSucceeded,errorType:Bn.AttachFailed})];case 1:return n.sent(),[2]}}))}))})),(0,d.take)(1)).toPromise(),[4,this._detachmentObserver.ensurePresence([this._iframe],t)];case 1:return r.sent(),[2]}}))}))},e.prototype.detach=function(){this._iframe.parentElement&&(this._iframe.parentElement.removeChild(this._iframe),this._eventListener.stopListen())},e.prototype.submitForm=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),n=this._eventPoster.post({type:Fn.SubmitRequested,payload:{fields:e,data:t}},{successType:Bn.SubmitSucceeded,errorType:Bn.SubmitFailed}),[4,this._detachmentObserver.ensurePresence([this._iframe],n)];case 1:return[2,i.sent()];case 2:if(r=i.sent(),this._isSubmitErrorEvent(r)){if("hosted_form_error"===r.payload.error.code)throw new zn(r.payload.error.message);if(r.payload.response)throw Mn(r.payload.response);throw new Error(r.payload.error.message)}throw r;case 3:return[2]}}))}))},e.prototype.validateForm=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){var e,t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return e=this._eventPoster.post({type:Fn.ValidateRequested},{successType:Bn.Validated}),[4,this._detachmentObserver.ensurePresence([this._iframe],e)];case 1:if(!(t=n.sent().payload).isValid)throw new Ln(t.errors);return[2]}}))}))},e.prototype._getFontUrls=function(){var e=this,t="fonts.googleapis.com",n=document.querySelectorAll("link[href*='"+t+"'][rel='stylesheet']");return Array.prototype.slice.call(n).filter((function(e){return hn(e.href).hostname===t})).filter((function(t){return(0,Z.values)(e._styles).map((function(e){return e&&e.fontFamily})).filter((function(e){return"string"==typeof e})).some((function(e){return e.split(/,\s/).some((function(e){return-1!==t.href.indexOf(e.replace(" ","+"))}))}))})).map((function(e){return e.href}))},e.prototype._isSubmitErrorEvent=function(e){return e.type===Bn.SubmitFailed},e}();const xn=Un;var qn=function(){function e(e,t,n,r,i){var o=this;this._fields=e,this._eventListener=t,this._payloadTransformer=n,this._eventCallbacks=r,this._paymentHumanVerificationHandler=i,this._handleEnter=function(e){var t=e.payload;return(0,s.__awaiter)(o,void 0,void 0,(function(){var e,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,this.validate()];case 1:return r.sent(),[3,3];case 2:if("InvalidHostedFormValueError"!==(e=r.sent()).name)throw e;return[3,3];case 3:return(void 0===(n=this._eventCallbacks.onEnter)?Z.noop:n)(t),[2]}}))}))};var a=this._eventCallbacks,c=a.onBlur,u=void 0===c?Z.noop:c,d=a.onCardTypeChange,l=void 0===d?Z.noop:d,p=a.onFocus,h=void 0===p?Z.noop:p,m=a.onValidate,_=void 0===m?Z.noop:m;this._eventListener.addListener(Bn.Blurred,(function(e){var t=e.payload;return u(t)})),this._eventListener.addListener(Bn.CardTypeChanged,(function(e){var t=e.payload;return l(t)})),this._eventListener.addListener(Bn.Focused,(function(e){var t=e.payload;return h(t)})),this._eventListener.addListener(Bn.Validated,(function(e){var t=e.payload;return _(t)})),this._eventListener.addListener(Bn.Entered,this._handleEnter),this._eventListener.addListener(Bn.CardTypeChanged,(function(e){var t=e.payload;return o._cardType=t.cardType})),this._eventListener.addListener(Bn.BinChanged,(function(e){var t=e.payload;return o._bin=t.bin}))}return e.prototype.getBin=function(){return this._bin},e.prototype.getCardType=function(){return this._cardType},e.prototype.attach=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){var e,t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return this._eventListener.listen(),e=this._getFirstField(),t=(0,Z.without)(this._fields,e),[4,e.attach()];case 1:return n.sent(),[4,Promise.all(t.map((function(e){return e.attach()})))];case 2:return n.sent(),[2]}}))}))},e.prototype.detach=function(){this._eventListener.stopListen(),this._fields.forEach((function(e){e.detach()}))},e.prototype.submit=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,5]),[4,this._getFirstField().submitForm(this._fields.map((function(e){return e.getType()})),this._payloadTransformer.transform(e,t))];case 1:case 4:return[2,i.sent()];case 2:return n=i.sent(),[4,this._paymentHumanVerificationHandler.handle(n)];case 3:return r=i.sent(),[4,this._getFirstField().submitForm(this._fields.map((function(e){return e.getType()})),this._payloadTransformer.transform(e,r))];case 5:return[2]}}))}))},e.prototype.validate=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){return[2,this._getFirstField().validateForm()]}))}))},e.prototype._getFirstField=function(){var e=this._fields[0];if(!e)throw new Rn("Unable to proceed because the payment form has no field defined.");return e},e}();const Vn=qn;function Gn(e){return Boolean(e.instrumentId)}const Hn=function(){function e(e){this._store=e}return e.prototype.transform=function(e,t){var n=this._store.getState(),r=n.checkout.getCheckout(),i=n.config.getConfig(),o=n.instruments.getInstrumentsMeta(),a=n.order.getOrder(),s=n.order.getOrderMeta(),c=(0,Z.omit)(e.paymentData,"ccExpiry","ccName","ccNumber","ccCvv"),u=n.paymentMethods.getPaymentMethod(e.methodId,e.gatewayId),d=n.paymentMethods.getPaymentMethodsMeta(),l=o&&c&&Gn(c)?n.payment.getPaymentToken()+", "+o.vaultAccessToken:n.payment.getPaymentToken();if(!l)throw new m(h.MissingPaymentToken);return{additionalAction:t,authToken:l,checkout:r,config:i,order:a,orderMeta:s,payment:c,paymentMethod:u,paymentMethodMeta:d}},e}(),Yn=function(){function e(e){this._store=e}return e.prototype.create=function(e,t){var n=this,r=Object.keys(t.fields).reduce((function(r,i){var o=t.fields[i];return o?(0,s.__spreadArrays)(r,[new xn(i,o.containerId,o.placeholder||"",o.accessibilityLabel||"",t.styles||{},new _n(e),new gn(e),new ln(new pn),"instrumentId"in o?n._getCardInstrument(o.instrumentId):void 0)]):r}),[]);return new Vn(r,new gn(e),new Hn(this._store),(0,Z.pick)(t,"onBlur","onEnter","onFocus","onCardTypeChange","onValidate"),new In(Tn((0,a.createScriptLoader)())))},e.prototype._getCardInstrument=function(e){var t=(0,this._store.getState().instruments.getCardInstrument)(e);if(!t)throw new m(h.MissingPaymentInstrument);return t},e}(),jn=function(e){function t(){var t=e.call(this,"You haven't complete our spam check. Please try again.")||this;return t.name="SpamProtectionNotCompletedError",t.type="spam_protection_not_completed",t}return(0,s.__extends)(t,e),t}(p);var Wn;!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"}(Wn||(Wn={}));const Kn=function(){function e(e,t){this._orderRequestSender=e,this._checkoutValidator=t}return e.prototype.loadOrder=function(e,t){var n=this;return new u.Observable((function(r){r.next((0,c.createAction)(Wn.LoadOrderRequested)),n._orderRequestSender.loadOrder(e,t).then((function(e){r.next((0,c.createAction)(Wn.LoadOrderSucceeded,e.body)),r.complete()})).catch((function(e){r.error((0,c.createErrorAction)(Wn.LoadOrderFailed,e))}))}))},e.prototype.loadOrderPayments=function(e,t){var n=this;return new u.Observable((function(r){r.next((0,c.createAction)(Wn.LoadOrderPaymentsRequested)),n._orderRequestSender.loadOrder(e,t).then((function(e){r.next((0,c.createAction)(Wn.LoadOrderPaymentsSucceeded,e.body)),r.complete()})).catch((function(e){r.error((0,c.createErrorAction)(Wn.LoadOrderPaymentsFailed,e))}))}))},e.prototype.loadCurrentOrder=function(e){var t=this;return function(n){return(0,u.defer)((function(){var r=t._getCurrentOrderId(n.getState());if(!r)throw new m(h.MissingOrderId);return t.loadOrder(r,e)}))}},e.prototype.submitOrder=function(e,t){var n=this;return function(r){return(0,u.concat)((0,u.of)((0,c.createAction)(Wn.SubmitOrderRequested)),(0,u.defer)((function(){var i=r.getState(),o=i.config.getExternalSource(),a=i.config.getVariantIdentificationToken(),l=i.checkout.getCheckout();if(!l)throw new m(h.MissingCheckout);if(l.shouldExecuteSpamCheck)throw new jn;return(0,u.from)(n._checkoutValidator.validate(l,t).then((function(){return n._orderRequestSender.submitOrder(n._mapToOrderRequestBody(null!=e?e:{},l.id,l.customerMessage,o),(0,s.__assign)((0,s.__assign)({},t),{headers:{checkoutVariant:a}}))}))).pipe((0,d.switchMap)((function(e){return(0,u.concat)(n.loadOrder(e.body.data.order.orderId,t),(0,u.of)((0,c.createAction)(Wn.SubmitOrderSucceeded,e.body.data,(0,s.__assign)((0,s.__assign)({},e.body.meta),{token:e.headers.token}))))})))})).pipe((0,d.catchError)((function(e){return l(Wn.SubmitOrderFailed,e)}))))}},e.prototype.finalizeOrder=function(e,t){var n=this;return(0,u.concat)((0,u.of)((0,c.createAction)(Wn.FinalizeOrderRequested)),(0,u.from)(this._orderRequestSender.finalizeOrder(e,t)).pipe((0,d.switchMap)((function(r){return(0,u.concat)(n.loadOrder(e,t),(0,u.of)((0,c.createAction)(Wn.FinalizeOrderSucceeded,r.body.data)))})))).pipe((0,d.catchError)((function(e){return l(Wn.FinalizeOrderFailed,e)})))},e.prototype._getCurrentOrderId=function(e){var t=e.order.getOrder(),n=e.checkout.getCheckout();return t&&t.orderId||n&&n.orderId},e.prototype._mapToOrderRequestBody=function(e,t,n,r){var i=e.payment,o=(0,s.__rest)(e,["payment"]);return i?(0,s.__assign)((0,s.__assign)({},o),{cartId:t,customerMessage:n,externalSource:r,payment:{paymentData:i.paymentData,name:i.methodId,gateway:i.gatewayId}}):(0,s.__assign)((0,s.__assign)({},o),{cartId:t,customerMessage:n,externalSource:r})},e}(),Jn=function(e){function t(t){var n=e.call(this,t||"Your checkout could not be processed because some details have changed. Please review your order and try again.")||this;return n.name="CartConsistencyError",n.type="cart_consistency",n}return(0,s.__extends)(t,e),t}(p),Zn=function(e){function t(t){var n=e.call(this,t||"The tax provider is unavailable.")||this;return n.name="OrderTaxProviderUnavailableError",n.type="tax_provider_unavailable",n}return(0,s.__extends)(t,e),t}(p);var Qn=function(){function e(e){this._requestSender=e}return e.prototype.loadOrder=function(e,t){var n=(void 0===t?{}:t).timeout,r="/api/storefront/orders/"+e,i=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.get(r,{params:{include:Q(["payments","lineItems.physicalItems.socialMedia","lineItems.physicalItems.options","lineItems.physicalItems.categories","lineItems.digitalItems.socialMedia","lineItems.digitalItems.options","lineItems.digitalItems.categories"])},headers:i,timeout:n})},e.prototype.submitOrder=function(e,t){var n=void 0===t?{}:t,r=n.headers,i=n.timeout;return this._requestSender.post("/internalapi/v1/checkout/order",{body:e,headers:(0,Z.omitBy)((0,s.__assign)({"X-Checkout-Variant":r&&r.checkoutVariant},C),Z.isNil),timeout:i}).catch((function(e){if("tax_provider_unavailable"===e.body.type)throw new Zn;if("cart_has_changed"===e.body.type)throw new Jn;throw e}))},e.prototype.finalizeOrder=function(e,t){var n=(void 0===t?{}:t).timeout,r="/internalapi/v1/checkout/order/"+e;return this._requestSender.post(r,{timeout:n,headers:C})},e}();const Xn=Qn;var $n;!function(e){e.SubmitPaymentRequested="SUBMIT_PAYMENT_REQUESTED",e.SubmitPaymentSucceeded="SUBMIT_PAYMENT_SUCCEEDED",e.SubmitPaymentFailed="SUBMIT_PAYMENT_FAILED",e.InitializeOffsitePaymentRequested="INITIALIZE_OFFSITE_PAYMENT_REQUESTED",e.InitializeOffsitePaymentSucceeded="INITIALIZE_OFFSITE_PAYMENT_SUCCEEDED",e.InitializeOffsitePaymentFailed="INITIALIZE_OFFSITE_PAYMENT_FAILED"}($n||($n={}));var er=function(){function e(e,t,n,r){var i=this;this._paymentRequestSender=e,this._orderActionCreator=t,this._paymentRequestTransformer=n,this._paymentHumanVerificationHandler=r,this.initializeOffsitePayment=function(e){var t=e.methodId,n=e.gatewayId,r=e.instrumentId,o=e.target,a=e.promise,s=e.shouldSaveInstrument,p=e.shouldSetAsDefaultInstrument;return function(e){var h;r?h={formattedPayload:{bigpay_token:r}}:s&&(h={formattedPayload:{vault_payment_instrument:s,set_as_default_stored_instrument:p||null}});var m=i._paymentRequestTransformer.transform({gatewayId:n,methodId:t,paymentData:h},e.getState());return(0,u.concat)((0,u.of)((0,c.createAction)($n.InitializeOffsitePaymentRequested)),Promise.race([i._paymentRequestSender.initializeOffsitePayment(m,o),a].filter(Boolean)).then((function(){return(0,c.createAction)($n.InitializeOffsitePaymentSucceeded)}))).pipe((0,d.catchError)((function(e){return l($n.InitializeOffsitePaymentFailed,e)})))}}}return e.prototype.submitPayment=function(e){var t=this;return function(n){return(0,u.concat)((0,u.of)((0,c.createAction)($n.SubmitPaymentRequested)),(0,u.defer)((function(){return(0,s.__awaiter)(t,void 0,void 0,(function(){var t,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,5]),[4,this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform(e,n.getState()))];case 1:case 4:return[2,i.sent()];case 2:return t=i.sent(),[4,this._paymentHumanVerificationHandler.handle(t)];case 3:return r=i.sent(),[4,this._paymentRequestSender.submitPayment(this._paymentRequestTransformer.transform((0,s.__assign)((0,s.__assign)({},e),{additionalAction:r}),n.getState()))];case 5:return[2]}}))}))})).pipe((0,d.switchMap)((function(e){var r=e.body;return(0,u.concat)(t._orderActionCreator.loadCurrentOrder()(n),(0,u.of)((0,c.createAction)($n.SubmitPaymentSucceeded,r)))})))).pipe((0,d.catchError)((function(e){return l($n.SubmitPaymentFailed,e)})))}},e}();const tr=er,nr=function(){function e(e){this._client=e}return e.prototype.submitPayment=function(e){var t=this;return new Promise((function(n,r){t._client.submitPayment(e,(function(e,i){e?r(t._transformResponse(e)):n(t._transformResponse(i))}))}))},e.prototype.initializeOffsitePayment=function(e,t){var n=this;return new Promise((function(){n._client.initializeOffsitePayment(e,null,t)}))},e.prototype._transformResponse=function(e){return{headers:e.headers,body:e.data,status:e.status,statusText:e.statusText}},e}(),rr=require("@bigcommerce/bigpay-client");function ir(e){var t=(0,rr.createClient)();return e.subscribe((function(e){var n=e.config.getStoreConfig();n&&t.setHost(n.paymentSettings.bigpayBaseUrl)}),(function(e){return e.config.getStoreConfig()})),t}function or(e){return void 0!==e.id}function ar(e,t){var n;return or(e)?n=e.id:t&&t.length&&(n=t[0].id),{id:n,firstName:e.firstName,lastName:e.lastName,company:e.company,addressLine1:e.address1,addressLine2:e.address2,city:e.city,province:e.stateOrProvince,provinceCode:e.stateOrProvinceCode,postCode:e.postalCode,country:e.country,countryCode:e.countryCode,phone:e.phone,customFields:e.customFields}}const sr=function(){function e(e){this._decimalPlaces=e}return e.prototype.toInteger=function(e){return Math.round(e*Math.pow(10,this._decimalPlaces))},e}();var cr,ur=["per_item_discount","percentage_discount","per_total_discount","shipping_discount","free_shipping"];function dr(e){return{code:e.code,discount:e.displayName,discountType:ur.indexOf(e.couponType)}}function lr(e){return{code:e.code,discountedAmount:e.used,remainingBalance:e.remaining,giftCertificate:{balance:e.balance,code:e.code,purchaseDate:e.purchaseDate}}}function pr(e,t,n){return void 0===n&&(n="id"),Object.keys(e).reduce((function(r,i){return(0,s.__spreadArrays)(r,e[i].map((function(e){return"giftCertificates"===i?function(e,t){var n=new sr(t);return{id:e.id,imageUrl:"",name:e.name,amount:e.amount,amountAfterDiscount:e.amount,discount:0,integerAmount:n.toInteger(e.amount),integerAmountAfterDiscount:n.toInteger(e.amount),integerUnitPrice:n.toInteger(e.amount),integerUnitPriceAfterDiscount:n.toInteger(e.amount),integerDiscount:0,quantity:1,sender:e.sender,recipient:e.recipient,type:"ItemGiftCertificateEntity",attributes:[],variantId:null}}(e,t):function(e,t,n,r){void 0===r&&(r="id");var i=new sr(n);return{id:e[r],imageUrl:e.imageUrl,amount:e.extendedListPrice,amountAfterDiscount:e.extendedSalePrice,discount:e.discountAmount,integerAmount:i.toInteger(e.extendedListPrice),integerAmountAfterDiscount:i.toInteger(e.extendedSalePrice),integerDiscount:i.toInteger(e.discountAmount),integerUnitPrice:i.toInteger(e.listPrice),integerUnitPriceAfterDiscount:i.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((function(e){return{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""}}(i),t,n)})))}),[])}function hr(e){var t,n,r=e.cart.currency.decimalPlaces,i=new sr(r);return{id:e.cart.id,items:pr(e.cart.lineItems,r),currency:e.cart.currency.code,coupon:{discountedAmount:(0,Z.reduce)(e.cart.coupons,(function(e,t){return e+t.discountedAmount}),0),coupons:e.cart.coupons.map(dr)},discount:{amount:e.cart.discountAmount,integerAmount:i.toInteger(e.cart.discountAmount)},discountNotifications:(t=e.promotions,n=[],(t||[]).forEach((function(e){(e.banners||[]).forEach((function(e){n.push({placeholders:[],discountType:null,message:"",messageHtml:e.text})}))})),n),giftCertificate:{totalDiscountedAmount:(0,Z.reduce)(e.giftCertificates,(function(e,t){return e+t.used}),0),appliedGiftCertificates:(0,Z.keyBy)(e.giftCertificates.map(lr),"code")},shipping:{amount:e.shippingCostTotal,integerAmount:i.toInteger(e.shippingCostTotal),amountBeforeDiscount:e.shippingCostBeforeDiscount,integerAmountBeforeDiscount:i.toInteger(e.shippingCostBeforeDiscount),required:(0,Z.some)(e.cart.lineItems.physicalItems,(function(e){return 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)}}}!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.MASTERPASS="masterpass",e.PAYPALEXPRESS="paypalexpress"}(cr||(cr={}));const mr=cr;function _r(e,t){var n=e.firstName||t.firstName||"",r=e.lastName||t.lastName||"";return{addresses:(e.addresses||[]).map((function(e){return ar(e)})),customerId:e.id,isGuest:e.isGuest,storeCredit:e.storeCredit,email:e.email||t.email||"",firstName:n,lastName:r,name:e.fullName||[n,r].join(" "),customerGroupName:e.customerGroup&&e.customerGroup.name}}var yr=function(){function e(){}return e.prototype.format=function(e){var t=e.split(new RegExp("\\s*/\\s*")),n=t[0],r=void 0===n?"":n,i=t[1],o=void 0===i?"":i,a=r.slice(0,2),s=4===o.length?o.slice(-2):o?o.slice(0,2):r.slice(2);return e.length<2?r:e.length>3&&!s?a:a+" / "+s},e.prototype.toObject=function(e){var t=e.split(new RegExp("\\s*/\\s*")),n=t[0],r=void 0===n?"":n,i=t[1],o=void 0===i?"":i;return/^\d+$/.test(r)&&/^\d+$/.test(o)?{month:1===r.length?"0"+r:r.slice(0,2),year:2===o.length?"20"+o:o.slice(0,4)}:{month:"",year:""}},e}();const fr=yr,gr=require("card-validator"),vr=function(){function e(){}return e.prototype.format=function(e){var t=(0,gr.number)(e).card;if(!t)return e;var n=(0,Z.max)((0,gr.creditCardType)(e).map((function(e){return(0,Z.max)(e.lengths)}))),r=this.unformat(e).slice(0,n);return t.gaps.filter((function(e){return r.length>e})).reduce((function(e,t,n){return[e.slice(0,t+n),e.slice(t+n)].join(" ")}),r)},e.prototype.unformat=function(e){return(0,gr.number)(e).card?e.replace(new RegExp(" ","g"),""):e},e}();function wr(e,t){void 0===t&&(t={});var n,r,i=e.currency.decimalPlaces,o=new sr(i);return{id:e.orderId,items:pr(e.lineItems,e.currency.decimalPlaces,"productId"),orderId:e.orderId,currency:e.currency.code,customerCanBeCreated:e.customerCanBeCreated,payment:Sr(e.payments,t.payment),subtotal:{amount:e.baseAmount,integerAmount:o.toInteger(e.baseAmount)},coupon:{discountedAmount:(0,Z.reduce)(e.coupons,(function(e,t){return e+t.discountedAmount}),0),coupons:e.coupons.map(dr)},discount:{amount:e.discountAmount,integerAmount:o.toInteger(e.discountAmount)},token:t.orderToken,callbackUrl:t.callbackUrl,discountNotifications:[],giftCertificate:(n=e.payments,r=(0,Z.filter)(n,{providerId:"giftcertificate"}),{totalDiscountedAmount:(0,Z.reduce)(r,(function(e,t){return t.amount+e}),0),appliedGiftCertificates:(0,Z.keyBy)(r.map((function(e){return{code:e.detail.code,discountedAmount:e.amount,remainingBalance:e.detail.remaining,giftCertificate:{balance:e.amount+e.detail.remaining,code:e.detail.code,purchaseDate:""}}})),"code")}),socialData:br(e),status:e.status,hasDigitalItems:e.hasDigitalItems,isDownloadable:e.isDownloadable,isComplete:e.isComplete,shipping:{amount:e.shippingCostTotal,integerAmount:o.toInteger(e.shippingCostTotal),amountBeforeDiscount:e.shippingCostBeforeDiscount,integerAmountBeforeDiscount:o.toInteger(e.shippingCostBeforeDiscount)},storeCredit:{amount:Cr(e.payments)},taxes:e.taxes,taxTotal:{amount:e.taxTotal,integerAmount:o.toInteger(e.taxTotal)},handling:{amount:e.handlingCostTotal,integerAmount:o.toInteger(e.handlingCostTotal)},grandTotal:{amount:e.orderAmount,integerAmount:e.orderAmountAsInteger}}}function Cr(e){var t=(0,Z.find)(e,{providerId:"storecredit"});return t?t.amount:0}function Sr(e,t){void 0===t&&(t={});var n,r=(0,Z.find)(e,Ir);return r?{id:r.providerId,status:(n=r.detail.step,"PAYMENT_STATUS_"+n),helpText:r.detail.instructions,returnUrl:t.returnUrl}:{}}function Ir(e){return"giftcertificate"!==e.providerId&&"storecredit"!==e.providerId}function br(e){var t={};return(0,s.__spreadArrays)(e.lineItems.physicalItems,e.lineItems.digitalItems).forEach((function(e){var n;t[e.id]=(n=e,["fb","tw","gp"].reduce((function(e,t){var r=n.socialMedia&&(0,Z.find)(n.socialMedia,(function(e){return e.code===t}));return r?(e[t]={name:n.name,description:n.name,image:n.imageUrl,url:r.link,shareText:r.text,sharingLink:r.link,channelName:r.channel,channelCode:r.code},e):e}),{}))})),t}function Pr(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}}var Er=function(){function e(){this._cardExpiryFormatter=new fr,this._cardNumberFormatter=new vr}return e.prototype.transform=function(e,t){var n,r=t.billingAddress.getBillingAddress(),i=t.checkout.getCheckout(),o=t.customer.getCustomer(),a=t.order.getOrder(),c=t.paymentMethods.getPaymentMethod(e.methodId,e.gatewayId),u=this._mapShippingAddress(t,c),d=t.consignments.getConsignments(),l=t.consignments.getShippingOption(),p=t.config.getStoreConfig(),_=t.config.getContextConfig(),y=t.instruments.getInstrumentsMeta(),f=t.paymentMethods.getPaymentMethodsMeta(),g=t.order.getOrderMeta(),v=o&&r&&_r(o,r),w=y&&e.paymentData&&(Gn(e.paymentData)||(n=e.paymentData.formattedPayload)&&("string"==typeof n.bigpay_token||Boolean(n.bigpay_token&&n.bigpay_token.token)))?t.payment.getPaymentToken()+", "+y.vaultAccessToken:t.payment.getPaymentToken();if(!w)throw new m(h.MissingPaymentToken);return{additionalAction:e.additionalAction,authToken:w,customer:v,billingAddress:r&&ar(r),shippingAddress:u&&ar(u,d),shippingOption:l&&Pr(l,!0),cart:i&&hr(i),order:a&&wr(a,g),orderMeta:g,payment:e.paymentData,paymentMethod:c&&this._transformPaymentMethod(c),quoteMeta:{request:(0,s.__assign)((0,s.__assign)({},f),{geoCountryCode:_&&_.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:(0,Z.pick)(p&&p.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}},e.prototype.transformWithHostedFormData=function(e,t,n){var r=t.additionalAction,i=t.authToken,o=t.checkout,a=t.config,c=t.order,u=t.orderMeta,d=t.payment,l=void 0===d?{}:d,p=t.paymentMethod,h=t.paymentMethodMeta,m=o&&o.consignments[0],_=m&&m.shippingAddress,y=m&&m.selectedShippingOption;return{additionalAction:r,authToken:i,paymentMethod:p&&this._transformPaymentMethod(p),customer:c&&c.billingAddress&&o&&_r(o.customer,c.billingAddress),billingAddress:c&&c.billingAddress&&ar(c.billingAddress),shippingAddress:_&&o&&ar(_,o.consignments),shippingOption:y&&Pr(y,!0),cart:o&&hr(o),order:c&&wr(c,u),orderMeta:u,payment:this._transformHostedInputValues(e,l,n),quoteMeta:{request:(0,s.__assign)((0,s.__assign)({},h),{geoCountryCode:a&&a.context.geoCountryCode})},source:"bigcommerce-checkout-js-sdk",store:a&&(0,Z.pick)(a.storeConfig.storeProfile,["storeHash","storeId","storeLanguage","storeName"])}},e.prototype._transformPaymentMethod=function(e){return"multi-option"!==e.method||e.gateway?e.initializationData&&e.initializationData.gateway?(0,s.__assign)((0,s.__assign)({},e),{id:e.initializationData.gateway}):e.id===mr.BRAINTREE_VENMO?(0,s.__assign)((0,s.__assign)({},e),{id:mr.BRAINTREE_PAYPAL}):e:(0,s.__assign)((0,s.__assign)({},e),{gateway:e.id})},e.prototype._transformHostedInputValues=function(e,t,n){return"instrumentId"in t?(0,s.__assign)((0,s.__assign)({},t),{ccCvv:e.cardCodeVerification,ccNumber:e.cardNumberVerification&&this._cardNumberFormatter.unformat(e.cardNumberVerification),hostedFormNonce:n}):(0,s.__assign)((0,s.__assign)({},t),{ccCvv:e.cardCode,ccExpiry:this._cardExpiryFormatter.toObject(e.cardExpiry||""),ccName:e.cardName||"",ccNumber:this._cardNumberFormatter.unformat(e.cardNumber||""),hostedFormNonce:n})},e.prototype._mapShippingAddress=function(e,t){var n,r,i,o;if(t){var a=null===(r=null===(n=t.initializationData)||void 0===n?void 0:n.bopis)||void 0===r?void 0:r.enabled,s=null===(o=null===(i=t.initializationData)||void 0===i?void 0:i.bopis)||void 0===o?void 0:o.requiredAddress,c=e.consignments.getConsignments(),u=null==c?void 0:c.every((function(e){return e.selectedPickupOption}));if(a&&u&&"none"===s)return}return e.shippingAddress.getShippingAddress()},e}();const Ar=Er;var Or;!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"}(Or||(Or={}));var kr=function(){function e(e,t){this._consignmentRequestSender=e,this._checkoutRequestSender=t}return e.prototype.unassignItemsByAddress=function(e,t){var n=this;return function(r){var i=r.getState();if(!i.checkout.getCheckout())throw new m(h.MissingCheckout);var o=n._consignmentHasAddress(e)?e.address:e.shippingAddress,a=i.consignments.getConsignmentByAddress(o);if(!a)throw new ae("No consignment found for the specified address");var s=n._removeLineItems(e.lineItems,a,i.cart.getCart());return s.length?n.updateConsignment({id:a.id,address:o,lineItems:s},t)(r):n.deleteConsignment(a.id,t)(r)}},e.prototype.assignItemsByAddress=function(e,t){var n=this;return function(r){var i=r.getState(),o=n._consignmentHasAddress(e)?e.address:e.shippingAddress,a=i.consignments.getConsignmentByAddress(o);return n._createOrUpdateConsignment({id:a&&a.id,address:o,lineItems:n._addLineItems(e.lineItems,a,i.cart.getCart())},t)(r)}},e.prototype.selectShippingOption=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o=r.getState(),a=o.checkout.getCheckout(),s=o.consignments.getConsignments();if(!a)throw new m(h.MissingCheckout);if(!s||!s.length)throw new m(h.MissingConsignments);var u={id:s[0].id,shippingOptionId:e},d={id:s[0].id};i.next((0,c.createAction)(Or.UpdateShippingOptionRequested,void 0,d)),n._consignmentRequestSender.updateConsignment(a.id,u,t).then((function(e){var t=e.body;i.next((0,c.createAction)(Or.UpdateShippingOptionSucceeded,t,d)),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(Or.UpdateShippingOptionFailed,e,d))}))}))}},e.prototype.loadShippingOptions=function(e){var t=this;return function(n){return u.Observable.create((function(r){var i=n.getState().checkout.getCheckout();if(!i)throw new m(h.MissingCheckout);r.next((0,c.createAction)(Or.LoadShippingOptionsRequested)),t._checkoutRequestSender.loadCheckout(i.id,(0,s.__assign)((0,s.__assign)({},e),{params:{include:[J.AvailableShippingOptions]}})).then((function(e){var t=e.body;r.next((0,c.createAction)(Or.LoadShippingOptionsSucceeded,t)),r.complete()})).catch((function(e){r.error((0,c.createErrorAction)(Or.LoadShippingOptionsFailed,e))}))}))}},e.prototype.updateAddress=function(e,t){var n=this;return function(r){var i=n._getUpdateAddressRequestBody(e,r),o=r.getState().consignments.getConsignments();return o&&o.length&&(i.id=o[0].id),n._createOrUpdateConsignment(i,t)(r)}},e.prototype.createConsignments=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o=r.getState().checkout.getCheckout();if(!o||!o.id)throw new m(h.MissingCheckout);i.next((0,c.createAction)(Or.CreateConsignmentsRequested)),n._consignmentRequestSender.createConsignments(o.id,e,t).then((function(e){var t=e.body;i.next((0,c.createAction)(Or.CreateConsignmentsSucceeded,t)),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(Or.CreateConsignmentsFailed,e))}))}))}},e.prototype.updateConsignment=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o=r.getState().checkout.getCheckout();if(!o||!o.id)throw new m(h.MissingCheckout);var a={id:e.id};i.next((0,c.createAction)(Or.UpdateConsignmentRequested,void 0,a)),n._consignmentRequestSender.updateConsignment(o.id,e,t).then((function(e){var t=e.body;i.next((0,c.createAction)(Or.UpdateConsignmentSucceeded,t,a)),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(Or.UpdateConsignmentFailed,e,a))}))}))}},e.prototype.deleteConsignment=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o=r.getState().checkout.getCheckout(),a={id:e};if(!o||!o.id)throw new m(h.MissingCheckout);i.next((0,c.createAction)(Or.DeleteConsignmentRequested,void 0,a)),n._consignmentRequestSender.deleteConsignment(o.id,e,t).then((function(e){var t=e.body;i.next((0,c.createAction)(Or.DeleteConsignmentSucceeded,t,a)),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(Or.DeleteConsignmentFailed,e,a))}))}))}},e.prototype.updateShippingOption=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o=r.getState().checkout.getCheckout();if(!o||!o.id)throw new m(h.MissingCheckout);var a={id:e.id};i.next((0,c.createAction)(Or.UpdateShippingOptionRequested,void 0,a)),n._consignmentRequestSender.updateConsignment(o.id,e,t).then((function(e){var t=e.body;i.next((0,c.createAction)(Or.UpdateShippingOptionSucceeded,t,a)),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(Or.UpdateShippingOptionFailed,e,a))}))}))}},e.prototype._createOrUpdateConsignment=function(e,t){var n=this;return function(r){var i=r.getState().checkout.getCheckout();if(!i||!i.id)throw new m(h.MissingCheckout);return n._isUpdateConsignmentRequest(e)?n.updateConsignment(e,t)(r):n.createConsignments([e],t)(r)}},e.prototype._getUpdateAddressRequestBody=function(e,t){var n=t.getState().cart.getCart();if(!n)throw new m(h.MissingCart);var r=n.lineItems,i=r.physicalItems,o=r.customItems,a=void 0===o?[]:o;return{address:e,lineItems:(0,s.__spreadArrays)(i,a).map((function(e){return{itemId:e.id,quantity:e.quantity}}))}},e.prototype._removeLineItems=function(e,t,n){if(!n)throw new m(h.MissingCart);return this._hydrateLineItems(t.lineItemIds,n).map((function(t){var n=(0,Z.find)(e,(function(e){return e.itemId===t.itemId}));return(0,s.__assign)((0,s.__assign)({},t),{quantity:n?t.quantity-n.quantity:t.quantity})})).filter((function(e){return e.quantity>0}))},e.prototype._addLineItems=function(e,t,n){if(!t)return e;if(!n)throw new m(h.MissingCart);return e.concat(this._hydrateLineItems(t.lineItemIds,n)).filter((function(e){return e.quantity>0}))},e.prototype._hydrateLineItems=function(e,t){return e.map((function(e){var n=(0,Z.find)(t.lineItems.physicalItems,(function(t){return t.id===e}));return{itemId:e,quantity:n?n.quantity:0}}))},e.prototype._isUpdateConsignmentRequest=function(e){return!!e.id},e.prototype._consignmentHasAddress=function(e){return"object"==typeof e&&"address"in e},e}();const Tr=kr;var Mr=["consignments.availableShippingOptions","cart.lineItems.physicalItems.options","cart.lineItems.digitalItems.options","customer","promotions.banners"],Dr=function(){function e(e){this._requestSender=e}return e.prototype.createConsignments=function(e,t,n){var r=void 0===n?{}:n,i=r.timeout,o=r.params,a=(void 0===o?{}:o).include,c="/api/storefront/checkouts/"+e+"/consignments",u=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.post(c,{body:t,params:{include:xt(Mr,a)},headers:u,timeout:i})},e.prototype.updateConsignment=function(e,t,n){var r=void 0===n?{}:n,i=r.timeout,o=r.params,a=(void 0===o?{}:o).include,c=t.id,u=(0,s.__rest)(t,["id"]),d="/api/storefront/checkouts/"+e+"/consignments/"+c,l=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.put(d,{body:u,params:{include:xt(Mr,a)},headers:l,timeout:i})},e.prototype.deleteConsignment=function(e,t,n){var r=(void 0===n?{}:n).timeout,i="/api/storefront/checkouts/"+e+"/consignments/"+t,o=(0,s.__assign)({Accept:w.JsonV1},C),a=Q(Mr);return this._requestSender.delete(i,{params:{include:a},headers:o,timeout:r})},e}();const Rr=Dr;var zr;!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"}(zr||(zr={}));var Nr=function(){function e(e,t){this._googleRecaptcha=e,this._requestSender=t}return e.prototype.initialize=function(e){var t=this;return function(n){return(0,u.concat)((0,u.of)((0,c.createAction)(zr.InitializeRequested,void 0)),(0,u.defer)((function(){return(0,s.__awaiter)(t,void 0,void 0,(function(){var t,r,i,o,a;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return t=e?e.containerId:"spamProtectionContainer",e||document.getElementById(t)||((r=document.createElement("div")).setAttribute("id",t),document.body.appendChild(r)),i=n.getState(),o=i.config.getStoreConfigOrThrow(),a=o.checkoutSettings.googleRecaptchaSitekey,[4,this._googleRecaptcha.load(t,a)];case 1:return s.sent(),[2,(0,c.createAction)(zr.InitializeSucceeded)]}}))}))}))).pipe((0,d.catchError)((function(e){return l(zr.InitializeFailed,e)})))}},e.prototype.verifyCheckoutSpamProtection=function(){var e=this;return function(t){return(0,u.defer)((function(){var n=t.getState().checkout.getCheckout();if(!n)throw new m(h.MissingCheckout);return(0,u.concat)((0,u.of)((0,c.createAction)(zr.VerifyCheckoutRequested)),(0,u.from)(e.execute()(t)).pipe((0,d.switchMap)((function(t){return Dt(t)&&t.payload?(0,u.from)(e._requestSender.validate(n.id,t.payload.token)).pipe((0,d.switchMap)((function(e){var n=e.body;return(0,u.concat)((0,u.of)(t),(0,u.of)((0,c.createAction)(zr.VerifyCheckoutSucceeded,n)))}))):(0,u.of)(t)})))).pipe((0,d.catchError)((function(e){return l(zr.VerifyCheckoutFailed,e)})))}))}},e.prototype.execute=function(){var e=this;return function(t){return(0,u.concat)((0,u.of)((0,c.createAction)(zr.ExecuteRequested)),e.initialize()(t),e._googleRecaptcha.execute().pipe((0,d.take)(1)).pipe((0,d.switchMap)((function(t){var n=t.error,r=t.token;return(0,s.__awaiter)(e,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){if(n instanceof vn)throw n;if(n||!r)throw new En;return[2,(0,c.createAction)(zr.ExecuteSucceeded,{token:r})]}))}))})))).pipe((0,d.catchError)((function(e){return l(zr.ExecuteFailed,e)})))}},e}();const Lr=Nr;var Fr=function(){function e(e){this._requestSender=e}return e.prototype.validate=function(e,t,n){var r=(void 0===n?{}:n).timeout,i="/api/storefront/checkouts/"+e+"/spam-protection",o=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.post(i,{body:{token:t},headers:o,timeout:r})},e}();const Br=Fr;var Ur;!function(e){e.ApplyStoreCreditRequested="APPLY_STORE_CREDIT_REQUESTED",e.ApplyStoreCreditSucceeded="APPLY_STORE_CREDIT_SUCCEEDED",e.ApplyStoreCreditFailed="APPLY_STORE_CREDIT_FAILED"}(Ur||(Ur={}));var xr=function(){function e(e){this._storeCreditRequestSender=e}return e.prototype.applyStoreCredit=function(e,t){var n=this;return function(r){return(0,u.concat)((0,u.of)((0,c.createAction)(Ur.ApplyStoreCreditRequested)),(0,u.defer)((function(){return(0,s.__awaiter)(n,void 0,void 0,(function(){var n,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:if(n=r.getState(),!(i=n.checkout.getCheckout()))throw new m(h.MissingCheckout);return[4,e?this._storeCreditRequestSender.applyStoreCredit(i.id,t):this._storeCreditRequestSender.removeStoreCredit(i.id,t)];case 1:return o=a.sent().body,[2,(0,c.createAction)(Ur.ApplyStoreCreditSucceeded,o)]}}))}))}))).pipe((0,d.catchError)((function(e){return l(Ur.ApplyStoreCreditFailed,e)})))}},e}();const qr=xr;var Vr=function(){function e(e){this._requestSender=e}return e.prototype.applyStoreCredit=function(e,t){var n=(void 0===t?{}:t).timeout,r="/api/storefront/checkouts/"+e+"/store-credit",i=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.post(r,{headers:i,timeout:n,params:{include:Q(K)}})},e.prototype.removeStoreCredit=function(e,t){var n=(void 0===t?{}:t).timeout,r="/api/storefront/checkouts/"+e+"/store-credit",i=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.delete(r,{headers:i,timeout:n,params:{include:Q(K)}})},e}();const Gr=Vr;var Hr;!function(e){e.UpdateSubscriptionsRequested="UPDATE_SUBSCRIPTIONS_REQUESTED",e.UpdateSubscriptionsSucceeded="UPDATE_SUBSCRIPTIONS_SUCCEEDED",e.UpdateSubscriptionsFailed="UPDATE_SUBSCRIPTIONS_FAILED"}(Hr||(Hr={}));const Yr=function(e){function t(t){var n=e.call(this,t)||this;return n.name="UpdateSubscriptionsError",n.type="update_subscriptions",n}return(0,s.__extends)(t,e),t}(x);var jr=function(){function e(e){this._subscriptionsRequestSender=e}return e.prototype.updateSubscriptions=function(e,t){var n=this;return(0,u.concat)((0,u.of)((0,c.createAction)(Hr.UpdateSubscriptionsRequested)),(0,u.defer)((function(){return(0,s.__awaiter)(n,void 0,void 0,(function(){var n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._subscriptionsRequestSender.updateSubscriptions(e,t)];case 1:return n=r.sent().body,[2,(0,c.createAction)(Hr.UpdateSubscriptionsSucceeded,n)]}}))}))}))).pipe((0,d.catchError)((function(e){return l(Hr.UpdateSubscriptionsFailed,new Yr(e))})))},e}();const Wr=jr;var Kr=function(){function e(e){this._requestSender=e}return e.prototype.updateSubscriptions=function(e,t){var n=(void 0===t?{}:t).timeout,r=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.post("/api/storefront/subscriptions",{body:e,headers:r,timeout:n})},e}();const Jr=Kr;function Zr(e){return(0,Z.isPlainObject)(e)}var Qr=(0,Z.memoize)((function(e){return Array.isArray(e)?e.map((function(e){return Xr(e)})):Zr(e)?Object.keys(e).reduce((function(t,n){var r;return(0,s.__assign)((0,s.__assign)({},t),((r={})[n]=Xr(e[n]),r))}),{}):e}));Qr.cache=new WeakMap;var Xr=function(e){return"object"==typeof e&&null!==e?Qr(e):e};function $r(e){return function(){for(var t=[],n=0;n\n Tell Me More',e.appendChild(n),n},e}();const Oo=Ao;function ko(e){var t=e.billingAddress,n=e.email,r=e.firstName,i=e.lastName,o=e.phone,a=e.shippingAddress,s=t||a;return{email:n,first_name:r,last_name:i,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 To(e){var t=e.email,n=e.phone,r=e.shippingAddress,i=((null==r?void 0:r.recipientName)||"").split(" ");return{email:t,first_name:i[0]||"",last_name:i[1]||"",phone_number:n,address_line_1:null==r?void 0:r.line1,address_line_2:null==r?void 0:r.line2,city:null==r?void 0:r.city,state:null==r?void 0:r.state,country_code:null==r?void 0:r.countryCode,postal_code:null==r?void 0:r.postalCode}}function Mo(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 Do,Ro,zo,No,Lo;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(Do||(Do={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(Ro||(Ro={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black"}(zo||(zo={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(No||(No={})),function(e){e.PILL="pill",e.RECT="rect"}(Lo||(Lo={}));var Fo=function(){function e(e,t,n,r,i,o,a){this._store=e,this._checkoutActionCreator=t,this._customerActionCreator=n,this._paymentMethodActionCreator=r,this._braintreeSDKCreator=i,this._formPoster=o,this._window=a}return e.prototype.initialize=function(e){var t,n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d,l,p,_,y,f,g=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(r=e.braintreepaypalcredit,i=e.methodId,a=(o=r||{}).container,c=o.buttonHeight,u=void 0===c?40:c,!i)throw new ae('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new ae('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');if(!a)throw new ae('Unable to initialize payment because "braintreepaypalcredit.container" argument is not provided.');return[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(i))];case 1:if(d=s.sent(),!(l=d.paymentMethods.getPaymentMethodOrThrow(i)).clientToken)throw new m(h.MissingPaymentMethod);return p=d.cart.getCartOrThrow().currency.code,_={currency:p,intent:null===(t=l.initializationData)||void 0===t?void 0:t.intent,isCreditEnabled:null===(n=l.initializationData)||void 0===n?void 0:n.isCreditEnabled},y=function(e){return g._renderPayPalButton(e,r,i,Boolean(l.config.testMode),u)},f=function(e){return g._handleError(e,r)},this._braintreeSDKCreator.initialize(l.clientToken),[4,this._braintreeSDKCreator.getPaypalCheckout(_,y,f)];case 2:return s.sent(),[2,this._store.getState()]}}))}))},e.prototype.deinitialize=function(){return this._braintreeSDKCreator.teardown(),Promise.resolve(this._store.getState())},e.prototype.signIn=function(e,t){return this._store.dispatch(this._customerActionCreator.signInCustomer(e,t))},e.prototype.signOut=function(e){return this._store.dispatch(this._customerActionCreator.signOutCustomer(e))},e.prototype.executePaymentMethodCheckout=function(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve(this._store.getState())},e.prototype._renderPayPalButton=function(e,t,n,r,i){var o=this,a=t.container,c=this._window.paypal,u=!1;if(c){var d=[c.FUNDING.PAYLATER,c.FUNDING.CREDIT],l={height:i,color:zo.GOLD};d.forEach((function(i){var d=i===c.FUNDING.CREDIT?(0,s.__assign)({label:No.CREDIT},l):l;if(!u){var p=c.Buttons({env:r?"sandbox":"production",commit:!1,fundingSource:i,style:d,createOrder:function(){return o._setupPayment(e,t,n)},onApprove:function(r){return o._tokenizePayment(r,e,t,n)}});p.isEligible()&&(p.render("#"+a),u=!0)}}))}c&&u||this._removeElement(a)},e.prototype._setupPayment=function(e,t,n){var r;return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u,d,l,p;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return s.trys.push([0,3,,4]),[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 1:return i=s.sent(),o=i.customer.getCustomer(),a=i.checkout.getCheckoutOrThrow().outstandingBalance,c=i.cart.getCartOrThrow().currency.code,u=i.paymentMethods.getPaymentMethodOrThrow(n),d=null==o?void 0:o.addresses[0],l=d?Mo(d):void 0,[4,e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:l,amount:a,currency:c,offerCredit:!0,intent:null===(r=u.initializationData)||void 0===r?void 0:r.intent})];case 2:return[2,s.sent()];case 3:return p=s.sent(),this._handleError(p,t),[3,4];case 4:return[2]}}))}))},e.prototype._tokenizePayment=function(e,t,n,r){return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return s.trys.push([0,3,,4]),[4,this._braintreeSDKCreator.getDataCollector({paypal:!0})];case 1:return i=s.sent().deviceData,[4,t.tokenizePayment(e)];case 2:return o=s.sent(),a=o.details,c=o.nonce,this._formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:r,action:"set_external_checkout",nonce:c,device_data:i,billing_address:JSON.stringify(ko(a)),shipping_address:JSON.stringify(To(a))}),[2,o];case 3:return u=s.sent(),this._handleError(u,n),[3,4];case 4:return[2]}}))}))},e.prototype._handleError=function(e,t){var n=t.container,r=t.onError;if(this._removeElement(n),!r)throw e;r(e)},e.prototype._removeElement=function(e){var t=e&&document.getElementById(e);t&&t.remove()},e}();const Bo=Fo;var Uo=function(){function e(e,t,n,r,i,o){this._store=e,this._paymentMethodActionCreator=t,this._remoteCheckoutActionCreator=n,this._chasePayScriptLoader=r,this._requestSender=i,this._formPoster=o}return e.prototype.initialize=function(e){var t=this,n=e.chasepay,r=e.methodId;if(!n||!r)throw new ae('Unable to proceed because "options.chasepay" argument is not provided.');return this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(r)).then((function(e){t._paymentMethod=e.paymentMethods.getPaymentMethod(r);var i=e.cart.getCart(),o=e.config.getStoreConfig();if(!i)throw new m(h.MissingCart);if(!o)throw new m(h.MissingCheckoutConfig);if(!t._paymentMethod||!t._paymentMethod.initializationData.digitalSessionId)throw new Pn(bn.PaymentNotInitialized);var a=n.container;return t._chasePayScriptLoader.load(t._paymentMethod.config.testMode).then((function(e){var n=e.ChasePay;n.configure({language:o.storeProfile.storeLanguage}),n.isChasePayUp&&n.insertButtons({containers:[a]}),n.on(n.EventType.START_CHECKOUT,(function(){t._store.dispatch(t._paymentMethodActionCreator.loadPaymentMethod(r)).then((function(){var e=t._store.getState().paymentMethods.getPaymentMethod(r),i=e&&e.initializationData&&e.initializationData.digitalSessionId;i&&n.startCheckout(i)}))})),n.on(n.EventType.COMPLETE_CHECKOUT,(function(e){var n=t._store.getState().paymentMethods.getPaymentMethod(r),i=n&&n.initializationData&&n.initializationData.merchantRequestId;i&&t._setExternalCheckoutData(e,i).then((function(){t._reloadPage()}))}))}))})).then((function(){return t._store.getState()}))},e.prototype.deinitialize=function(){return Promise.resolve(this._store.getState())},e.prototype.signIn=function(){throw new bo('In order to sign in via Chase Pay®, the shopper must click on "Chase Pay®" button.')},e.prototype.signOut=function(e){var t=this._store.getState().payment.getPaymentId();return t?this._store.dispatch(this._remoteCheckoutActionCreator.signOut(t.providerId,e)):Promise.resolve(this._store.getState())},e.prototype.executePaymentMethodCheckout=function(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve(this._store.getState())},e.prototype._setExternalCheckoutData=function(e,t){var n={headers:(0,s.__assign)({Accept:"text/html","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},C),body:{sessionToken:e.sessionToken,merchantRequestId:t},method:"post"};return this._requestSender.sendRequest("checkout.php?provider=chasepay&action=set_external_checkout",n)},e.prototype._reloadPage=function(){this._formPoster.postForm("/checkout.php",{headers:(0,s.__assign)({Accept:"text/html","Content-Type":"application/x-www-form-urlencoded"},C),params:{fromChasePay:!0}})},e}();const xo=Uo;var qo=function(){function e(e,t){this._store=e,this._customerActionCreator=t}return e.prototype.signIn=function(e,t){return this._store.dispatch(this._customerActionCreator.signInCustomer(e,t))},e.prototype.signOut=function(e){return this._store.dispatch(this._customerActionCreator.signOutCustomer(e))},e.prototype.executePaymentMethodCheckout=function(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve(this._store.getState())},e.prototype.initialize=function(){return Promise.resolve(this._store.getState())},e.prototype.deinitialize=function(){return Promise.resolve(this._store.getState())},e}();const Vo=qo;var Go;!function(e){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"}(Go||(Go={}));const Ho=Go;var Yo=function(){function e(e,t,n,r){this._store=e,this._remoteCheckoutActionCreator=t,this._googlePayPaymentProcessor=n,this._formPoster=r}return e.prototype.initialize=function(e){var t=this,n=e.methodId,r=this._getGooglePayOptions(e);if(!n)throw new m(h.MissingPaymentMethod);return this._googlePayPaymentProcessor.initialize(n).then((function(){t._walletButton=t._createSignInButton(r.container,r)})).then((function(){return t._store.getState()}))},e.prototype.deinitialize=function(){var e=this;return this._walletButton&&this._walletButton.parentNode&&(this._walletButton.parentNode.removeChild(this._walletButton),this._walletButton=void 0),this._googlePayPaymentProcessor.deinitialize().then((function(){return e._store.getState()}))},e.prototype.signIn=function(){throw new bo('In order to sign in via Google Pay, the shopper must click on "Google Pay" button.')},e.prototype.signOut=function(e){var t=this._store.getState().payment.getPaymentId();return t?this._store.dispatch(this._remoteCheckoutActionCreator.forgetCheckout(t.providerId,e)):Promise.resolve(this._store.getState())},e.prototype.executePaymentMethodCheckout=function(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve(this._store.getState())},e.prototype._createSignInButton=function(e,t){var n=document.querySelector("#"+e),r=t.buttonType,i=t.buttonColor;if(!n)throw new ae("Unable to create sign-in button without valid container ID.");var o=this._googlePayPaymentProcessor.createButton(this._handleWalletButtonClick,r,i);return n.appendChild(o),o},e.prototype._getGooglePayOptions=function(e){if(e.methodId===Ho.GOOGLEPAY_ADYENV2&&e.googlepayadyenv2)return e.googlepayadyenv2;if(e.methodId===Ho.GOOGLEPAY_ADYENV3&&e.googlepayadyenv3)return e.googlepayadyenv3;if(e.methodId===Ho.GOOGLEPAY_AUTHORIZENET&&e.googlepayauthorizenet)return e.googlepayauthorizenet;if(e.methodId===Ho.GOOGLEPAY_BNZ&&e.googlepaybnz)return e.googlepaybnz;if(e.methodId===Ho.GOOGLEPAY_BRAINTREE&&e.googlepaybraintree)return e.googlepaybraintree;if(e.methodId===Ho.GOOGLEPAY_CHECKOUTCOM&&e.googlepaycheckoutcom)return e.googlepaycheckoutcom;if(e.methodId===Ho.GOOGLEPAY_CYBERSOURCEV2&&e.googlepaycybersourcev2)return e.googlepaycybersourcev2;if(e.methodId===Ho.GOOGLEPAY_ORBITAL&&e.googlepayorbital)return e.googlepayorbital;if(e.methodId===Ho.GOOGLEPAY_STRIPE&&e.googlepaystripe)return e.googlepaystripe;if(e.methodId===Ho.GOOGLEPAY_STRIPEUPE&&e.googlepaystripeupe)return e.googlepaystripeupe;if(e.methodId===Ho.GOOGLEPAY_WORLDPAYACCESS&&e.googlepayworldpayaccess)return e.googlepayworldpayaccess;throw new ae},e.prototype._handleWalletButtonClick=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:e.preventDefault(),t=this._store.getState().cart.getCartOrThrow(),n=si(t)>0,r={transactionInfo:{currencyCode:t.currency.code,totalPrice:String(t.cartAmount)}},this._googlePayPaymentProcessor.updatePaymentDataRequest(r),a.label=1;case 1:return a.trys.push([1,7,,8]),[4,this._googlePayPaymentProcessor.displayWallet()];case 2:return i=a.sent(),[4,this._googlePayPaymentProcessor.handleSuccess(i)];case 3:return a.sent(),n&&i.shippingAddress?[4,this._googlePayPaymentProcessor.updateShippingAddress(i.shippingAddress)]:[3,5];case 4:a.sent(),a.label=5;case 5:return[4,this._onPaymentSelectComplete()];case 6:return a.sent(),[3,8];case 7:if((o=a.sent())&&"CANCELED"!==o.message)throw o;return[3,8];case 8:return[2]}}))}))},e.prototype._onPaymentSelectComplete=function(){var e=this._store.getState().config.getStoreConfigOrThrow().links.siteLink;this._formPoster.postForm("/embedded-checkout"===window.location.pathname?e+"/checkout":"/checkout.php",{headers:(0,s.__assign)({Accept:"text/html","Content-Type":"application/x-www-form-urlencoded"},C)})},(0,s.__decorate)([yn],e.prototype,"_handleWalletButtonClick",null),e}();const jo=Yo;function Wo(e){return window.location.origin+"/checkout.php?action=set_external_checkout&provider=masterpass&gateway=stripe&origin="+e}var Ko={es:["es_es","es_mx","es_pe","es_co","es_ar","es_cl"],en:["en_us","en_gb","en_ca","en_es","en_fr","en_ie","en_sg","en_au","en_nz","en_my","en_hk","en_th","en_ae","en_sa","en_qa","en_kw","en_za"],pt:["pt_br"],zu:["zu_za"],ar:["ar_sa","ar_ae","ar_qa","ar_kw"],zh:["zh_sg","zh_hk"],ms:["ms_my"],uk:["uk_ua"],sv:["sv_se"],hr:["hr_hr"],pl:["pl_pl"],nl:["nl_be"],it:["it_it"],de:["de_de"],fr:["fr_fr","fr_ca"]};function Jo(e){var t=e.replace("-","_").toLowerCase().split("_"),n=t[0],r=n+"_"+t[1],i=Ko[n];return i?i.indexOf(r)>-1?r:i[0]:"en_us"}var Zo=function(){function e(e,t,n,r,i){this._store=e,this._paymentMethodActionCreator=t,this._remoteCheckoutActionCreator=n,this._masterpassScriptLoader=r,this._locale=i}return e.prototype.initialize=function(e){var t=this,n=e.masterpass,r=e.methodId;if(!n||!r)throw new ae('Unable to proceed because "options.masterpass" argument is not provided.');return this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(r)).then((function(e){if(t._paymentMethod=e.paymentMethods.getPaymentMethod(r),!t._paymentMethod||!t._paymentMethod.initializationData.checkoutId)throw new m(h.MissingPaymentMethod);var i=e.cart.getCart();if(!i)throw new m(h.MissingCart);var o=n.container,a={checkoutId:t._paymentMethod.initializationData.checkoutId,allowedCardTypes:t._paymentMethod.initializationData.allowedCardTypes,amount:i.cartAmount.toString(),currency:i.currency.code,cartId:i.id,suppressShippingAddress:!1,callbackUrl:Wo("checkout")},s={useMasterpassSrc:t._paymentMethod.initializationData.isMasterpassSrcEnabled,language:Jo(t._locale),testMode:t._paymentMethod.config.testMode,checkoutId:t._paymentMethod.initializationData.checkoutId};return t._masterpassScriptLoader.load(s).then((function(e){t._signInButton=t._createSignInButton(o),t._signInButton.addEventListener("click",(function(){e.checkout(a)}))}))})).then((function(){return t._store.getState()}))},e.prototype.deinitialize=function(){return this._paymentMethod=void 0,this._signInButton&&this._signInButton.parentNode&&(this._signInButton.parentNode.removeChild(this._signInButton),this._signInButton=void 0),Promise.resolve(this._store.getState())},e.prototype.signIn=function(){throw new bo('In order to sign in via Masterpass, the shopper must click on "Masterpass" button.')},e.prototype.signOut=function(e){var t=this._store.getState().payment.getPaymentId();return t?this._store.dispatch(this._remoteCheckoutActionCreator.signOut(t.providerId,e)):Promise.resolve(this._store.getState())},e.prototype.executePaymentMethodCheckout=function(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve(this._store.getState())},e.prototype._createSignInButton=function(e){var t=document.querySelector("#"+e);if(!this._paymentMethod||!this._paymentMethod.initializationData.checkoutId)throw new m(h.MissingPaymentMethod);if(!t)throw new ae("Unable to create sign-in button without valid container ID.");var n=document.createElement("input");if(n.type="image",this._paymentMethod.initializationData.isMasterpassSrcEnabled){var r=this._paymentMethod.config.testMode?"sandbox.":"",i=this._paymentMethod.initializationData.checkoutId,o=["locale="+Jo(this._locale),"paymentmethod=master,visa,amex,discover","checkoutid="+i];n.src=["https://"+r+"src.mastercard.com/assets/img/btn/src_chk_btn_126x030px.svg",o.join("&")].join("?")}else n.src="https://static.masterpass.com/dyn/img/btn/global/mp_chk_btn_160x037px.svg";return t.appendChild(n),n},e}();const Qo=Zo;var Xo=function(){function e(e,t){this._store=e,this._remoteCheckoutActionCreator=t}return e.prototype.signIn=function(){throw new bo('In order to sign in via Masterpass, the shopper must click on "Masterpass" button.')},e.prototype.signOut=function(e){var t=this._store.getState().payment.getPaymentId();return t?this._store.dispatch(this._remoteCheckoutActionCreator.signOut(t.providerId,e)):Promise.resolve(this._store.getState())},e.prototype.initialize=function(){return Promise.resolve(this._store.getState())},e.prototype.deinitialize=function(){return Promise.resolve(this._store.getState())},e.prototype.executePaymentMethodCheckout=function(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve(this._store.getState())},e}();const $o=Xo;var ea,ta,na,ra,ia;!function(e){e.SHIPPING="shipping",e.BILLING="billing"}(ea||(ea={})),function(e){e.SPLIT="split",e.FULL="full",e.ORGANIZATION="organization"}(ta||(ta={})),function(e){e.CreditCard="card",e.SOFORT="sofort",e.EPS="eps",e.GRABPAY="grabpay",e.BANCONTACT="bancontact",e.IDEAL="ideal",e.GIROPAY="giropay",e.ALIPAY="alipay",e.KLARNA="klarna"}(na||(na={})),function(e){e.NEVER="never",e.AUTO="auto",e.ALWAYS="always",e.PAYMENT="payment",e.IF_REQUIRED="if_required"}(ra||(ra={})),function(e){e.PAYMENT="payment",e.AUTHENTICATION="linkAuthentication",e.SHIPPING="address"}(ia||(ia={}));var oa=function(){function e(e,t,n,r,i){this._store=e,this._stripeUPEScriptLoader=t,this._customerActionCreator=n,this._paymentMethodActionCreator=r,this._consignmentActionCreator=i}return e.prototype.initialize=function(e){var t;return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,u,d,l,p,_,y,f,g,v,w,C,S,I,b,P,E,A,O,k,T,M,D,R,z,N,L=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!e.stripeupe)throw new ae('Unable to proceed because "options" argument is not provided.');return r=e.stripeupe,i=r.container,o=r.gatewayId,a=r.methodId,u=r.onEmailChange,d=r.getStyles,l=r.isLoading,Object.entries(e.stripeupe).forEach((function(e){var t=e[0];if(!e[1])throw new ae('Unable to proceed because "'+t+'" argument is not provided.')})),[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(o,{params:{method:a}}))];case 1:if(p=s.sent(),_=p.paymentMethods.getPaymentMethodOrThrow,y=p.customer.getCustomerOrThrow,f=_(a,o),g=f.clientToken,v=f.initializationData,C=(w=void 0===v?{}:v).stripePublishableKey,S=w.stripeConnectedAccount,I=y(),b=I.email,P=I.isStripeLinkAuthenticated,b)return[3,3];if(!C||!g)throw new m(h.MissingPaymentToken);return E=void 0,A="function"==typeof d&&d(),E=A?{variables:{colorPrimary:A.fieldInnerShadow,colorBackground:A.fieldBackground,colorText:A.labelText,colorDanger:A.fieldErrorText,colorTextSecondary:A.labelText,colorTextPlaceholder:A.fieldPlaceholderText},rules:{".Input":{borderColor:A.fieldBorder,color:A.fieldText,boxShadow:A.fieldInnerShadow}}}:{},[4,this._stripeUPEScriptLoader.getStripeClient(C,S)];case 2:n=s.sent(),this._stripeElements=this._stripeUPEScriptLoader.getElements(n,{clientSecret:g,appearance:E}),O=this._store.getState(),k=O.billingAddress.getBillingAddress,T=O.consignments.getConsignments,M=T(),D=null===(t=null==M?void 0:M[0])||void 0===t?void 0:t.id,R=(k()||{}).email,z=R?{defaultValues:{mode:ea.SHIPPING,email:R}}:{},(N=this._stripeElements.getElement(ia.AUTHENTICATION)||this._stripeElements.create(ia.AUTHENTICATION,z)).on("change",(function(e){if(!("authenticated"in e))throw new m(h.MissingCustomer);L._store.dispatch((0,c.createAction)(Rt.StripeLinkAuthenticated,e.authenticated)),e.complete?u(e.authenticated,e.value.email):u(!1,""),l&&l(!1),void 0===P&&e.authenticated&&D&&L._store.dispatch(L._consignmentActionCreator.deleteConsignment(D))})),N.mount("#"+i),s.label=3;case 3:return[2,this._store.getState()]}}))}))},e.prototype.deinitialize=function(){var e,t;return null===(t=null===(e=this._stripeElements)||void 0===e?void 0:e.getElement(ia.AUTHENTICATION))||void 0===t||t.unmount(),Promise.resolve(this._store.getState())},e.prototype.signIn=function(e,t){return this._store.dispatch(this._customerActionCreator.signInCustomer(e,t))},e.prototype.signOut=function(e){return this._store.dispatch(this._customerActionCreator.signOutCustomer(e))},e.prototype.executePaymentMethodCheckout=function(e){var t;return null===(t=null==e?void 0:e.continueWithCheckoutCallback)||void 0===t||t.call(e),Promise.resolve(this._store.getState())},e}();const aa=oa;var sa,ca=function(e){function t(t){var n=e.call(this,t||"Unable to proceed due to no extension configured for this region.")||this;return n.name="ExtensionNotFoundError",n.type="extension_not_found",n}return(0,s.__extends)(t,e),t}(p);!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"}(sa||(sa={}));var ua=function(e){function t(t){var n=e.call(this,t||"Unable to proceed due to invalid configuration provided for the extension.")||this;return n.name="InvalidExtensionConfigError",n.type="invalid_extension_config",n}return(0,s.__extends)(t,e),t}(p),da=function(){function e(e,t,n){this._containerId=e,this._extension=t,this._cartId=n;var r=new URL(this._extension.url);r.searchParams.set("extensionId",this._extension.id),r.searchParams.set("cartId",this._cartId),this._iframe=document.createElement("iframe"),this._iframe.src=r.toString(),this._iframe.style.border="none",this._iframe.style.height="100%",this._iframe.style.overflow="hidden",this._iframe.style.width="100%"}return e.prototype.attach=function(){var e=document.getElementById(this._containerId);if(!e)throw new ua("Unable to proceed because the provided container ID is invalid.");e.appendChild(this._iframe)},e.prototype.detach=function(){this._iframe.parentElement&&this._iframe.parentElement.removeChild(this._iframe)},e}(),la=function(){function e(e){this._requestSender=e}return e.prototype.loadExtensions=function(e){var t=this;return function(){return u.Observable.create((function(n){n.next((0,c.createAction)(sa.LoadExtensionsRequested)),t._requestSender.loadExtensions(e).then((function(e){var t=e.body;n.next((0,c.createAction)(sa.LoadExtensionsSucceeded,t)),n.complete()})).catch((function(e){n.error((0,c.createErrorAction)(sa.LoadExtensionsFailed,e))}))}))}},e.prototype.renderExtension=function(e,t){return function(n){return u.Observable.create((function(r){var i=n.getState(),o=i.cart.getCartOrThrow().id,a=i.extensions.getExtensionByRegion(t);if(!a)throw new ca("Unable to proceed due to no extension configured for "+t+".");r.next((0,c.createAction)(sa.RenderExtensionRequested));try{new da(e,a,o).attach(),r.next((0,c.createAction)(sa.RenderExtensionSucceeded)),r.complete()}catch(e){r.error((0,c.createErrorAction)(sa.RenderExtensionFailed,e))}}))}},e}(),pa=function(){function e(e){this._requestSender=e}return e.prototype.loadExtensions=function(e){var t=void 0===e?{}:e,n=t.timeout,r=t.params;return this._requestSender.get("/api/storefront/checkout-extensions",{timeout:n,headers:(0,s.__assign)({Accept:w.JsonV1},C),params:r})},e}();const ha=function(e){function t(t){var n=this,r="Unable to submit payment for the order because the payload is invalid.";return t&&(r=r+" Make sure the following fields are provided correctly: "+t.join(", ")+"."),(n=e.call(this,r)||this).name="PaymentArgumentInvalidError",n}return(0,s.__extends)(t,e),t}(ye);function ma(e){return Boolean(e.instrumentId)}function _a(){var e,t=window.navigator;return e=t.language?t.language:t.userLanguage,{color_depth:window.screen.colorDepth||24,java_enabled:"function"==typeof t.javaEnabled&&t.javaEnabled(),language:e,screen_height:window.screen.height,screen_width:window.screen.width,time_zone_offset:(new Date).getTimezoneOffset().toString()}}const ya=function(e){function t(){var t=e.call(this,"The current order does not need to be finalized at this stage.")||this;return t.name="OrderFinalizationNotRequiredError",t.type="order_finalization_not_required",t}return(0,s.__extends)(t,e),t}(pe),fa=function(e){return"object"==typeof e&&null!==e&&"body"in e},ga=function(e){function t(t,n){var r=e.call(this,n||"Unable to proceed because the payment form contains invalid data.")||this;return r.details=t,r.name="PaymentInvalidFormError",r.type="payment_invalid_form",r}return(0,s.__extends)(t,e),t}(pe);var va,wa,Ca,Sa,Ia,ba;function Pa(e){return e&&"string"==typeof e.data.paymentMethod.encryptedSecurityCode||"string"==typeof e.data.paymentMethod.encryptedExpiryMonth}!function(e){e.ThreeDS2Fingerprint="threeDS2Fingerprint",e.ThreeDS2Challenge="threeDS2Challenge",e.Redirect="redirect",e.QRCode="qrCode",e.Voucher="voucher"}(va||(va={})),function(e){e.SecuredFields="securedfields"}(wa||(wa={})),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"}(Ca||(Ca={})),function(e){e.POST="POST"}(Sa||(Sa={})),function(e){e.ChallengeShopper="ChallengeShopper",e.Error="Error",e.IdentifyShopper="IdentifyShopper"}(Ia||(Ia={})),function(e){e.CardNumber="encryptedCardNumber",e.SecurityCode="encryptedSecurityCode",e.ExpiryDate="encryptedExpiryDate"}(ba||(ba={}));var Ea=function(){function e(e,t){this._paymentIntegrationService=e,this._scriptLoader=t}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d,l,p,h;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!(t=e.adyenv2))throw new ye('Unable to initialize payment because "options.adyenv2" argument is not provided.');return this._paymentInitializeOptions=t,n=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),r=n.initializationData||{},i=r.originKey,o=r.clientKey,a=r.environment,c=r.paymentMethodsResponse,u={key:"",value:""},i?(u.key="originKey",u.value=i):(u.key="clientKey",u.value=o||""),d=this,[4,this._scriptLoader.load((h={environment:a,locale:this._paymentIntegrationService.getState().getLocale()},h[u.key]=u.value,h.paymentMethodsResponse=c,h.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"}},h))];case 1:return d._adyenClient=s.sent(),l=this,[4,this._mountPaymentComponent(n)];case 2:return l._paymentComponent=s.sent(),n.method!==Ca.CreditCard&&n.method!==Ca.Bancontact?[3,4]:(p=this,[4,this._mountCardVerificationComponent()]);case 3:p._cardVerificationComponent=s.sent(),s.label=4;case 4:return[2,Promise.resolve()]}}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d,l,p,h,m,_,y;return(0,s.__generator)(this,(function(f){switch(f.label){case 0:return n=e.payment,r=(0,s.__rest)(e,["payment"]),i=n&&n.paymentData,o=i&&i.shouldSaveInstrument,a=i&&i.shouldSetAsDefaultInstrument,n?(this._validateCardData(),[4,this._paymentIntegrationService.submitOrder(r,t)]):[2,Promise.reject(new ha(["payment"]))];case 1:if(f.sent(),!(c=this._componentState))throw new Ee(Pe.PaymentNotInitialized);if(!i||!ma(i))return[3,6];if(u={},Pa(c)&&(d=c.data.paymentMethod,l=d.encryptedCardNumber,p=d.encryptedSecurityCode,h=d.encryptedExpiryMonth,m=d.encryptedExpiryYear,u={credit_card_number_confirmation:l,expiry_month:h,expiry_year:m,verification_value:p}),!Pa(c)&&-1===["ideal","sepadirectdebit","directEbanking","giropay"].indexOf(c.data.paymentMethod.type))return[3,6];f.label=2;case 2:return f.trys.push([2,4,,6]),[4,this._paymentIntegrationService.submitPayment((0,s.__assign)((0,s.__assign)({},n),{paymentData:{formattedPayload:{bigpay_token:(0,s.__assign)((0,s.__assign)({},u),{token:i.instrumentId}),origin:window.location.origin,browser_info:_a(),set_as_default_stored_instrument:a||null}}}))];case 3:return f.sent(),[2];case 4:return _=f.sent(),[4,this._processAdditionalAction(_,o,a)];case 5:return f.sent(),[2];case 6:return f.trys.push([6,8,,10]),[4,this._paymentIntegrationService.submitPayment({methodId:n.methodId,paymentData:{formattedPayload:{credit_card_token:{token:JSON.stringify((0,s.__assign)((0,s.__assign)({},c.data.paymentMethod),{origin:window.location.origin}))},browser_info:_a(),vault_payment_instrument:o||null,set_as_default_stored_instrument:a||null}}})];case 7:return f.sent(),[3,10];case 8:return y=f.sent(),[4,this._processAdditionalAction(y,o,a)];case 9:return f.sent(),[3,10];case 10:return[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.deinitialize=function(){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()},e.prototype._getAdyenClient=function(){if(!this._adyenClient)throw new Ee(Pe.PaymentNotInitialized);return this._adyenClient},e.prototype._getPaymentInitializeOptions=function(){if(!this._paymentInitializeOptions)throw new ye('"options.adyenv2" argument was not provided during initialization.');return this._paymentInitializeOptions},e.prototype._getThreeDS2ChallengeWidgetSize=function(){var e=this._getPaymentInitializeOptions(),t=e.additionalActionOptions,n=e.threeDS2Options;return t.widgetSize||(null==n?void 0:n.widgetSize)||"05"},e.prototype._handleAction=function(e){var t=this;return new Promise((function(n,r){var i=t._getPaymentInitializeOptions(),o=i.threeDS2ContainerId,a=i.additionalActionOptions,s=a.onBeforeLoad,c=a.containerId,u=a.onLoad,d=a.onComplete,l=JSON.parse(e.action),p=t._getAdyenClient().createFromAction(l,{onAdditionalDetails:function(e){var t={methodId:l.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};d&&d(),n(t)},size:t._getThreeDS2ChallengeWidgetSize(),onError:function(e){return r(e)}});s&&s(l.type===va.ThreeDS2Challenge||l.type===va.QRCode),p.mount("#"+(c||o)),u&&u((function(){r(new fe),p.unmount()}))}))},e.prototype._mapAdyenPlaceholderData=function(e,t){if(!e)return{};var n=e.firstName,r=e.lastName;return{holderName:t?n+" "+r:"",billingAddress:{street:e.address1,houseNumberOrName:e.address2,postalCode:e.postalCode,city:e.city,stateOrProvince:e.stateOrProvinceCode,country:e.countryCode}}},e.prototype._mountCardVerificationComponent=function(){var e,t=this,n=this._getPaymentInitializeOptions(),r=this._getAdyenClient();return new Promise((function(i,o){var a,c,u;if(n.cardVerificationContainerId){e=r.create(wa.SecuredFields,(0,s.__assign)((0,s.__assign)({},n.options),{styles:(0,s.__assign)((0,s.__assign)({},null===(a=n.options)||void 0===a?void 0:a.styles),{placeholder:(0,s.__assign)({color:"transparent",caretColor:"#000"},null===(u=null===(c=n.options)||void 0===c?void 0:c.styles)||void 0===u?void 0:u.placeholder)}),onChange:function(e){return t._updateComponentState(e)},onError:function(e){return n.validateCardFields(e)},onFieldValid:function(e){return n.validateCardFields(e)}}));try{e.mount("#"+n.cardVerificationContainerId)}catch(e){o(new Ee(Pe.PaymentNotInitialized))}}i(e)}))},e.prototype._mountPaymentComponent=function(e){var t,n=this,r=this._getPaymentInitializeOptions(),i=this._getAdyenClient();return new Promise((function(o,a){switch(e.method){case Ca.CreditCard:case Ca.ACH:case Ca.Bancontact:var c=n._paymentIntegrationService.getState().getBillingAddress(),u=e.initializationData.prefillCardHolderName;t=i.create(e.method,(0,s.__assign)((0,s.__assign)({},r.options),{onChange:function(e){return n._updateComponentState(e)},data:n._mapAdyenPlaceholderData(c,u)}));try{t.mount("#"+r.containerId)}catch(e){a(new Ee(Pe.PaymentNotInitialized))}break;case Ca.IDEAL:case Ca.SEPA:if(r.hasVaultedInstruments)n._updateComponentState({data:{paymentMethod:{type:e.method}}});else{t=i.create(e.method,(0,s.__assign)((0,s.__assign)({},r.options),{onChange:function(e){return n._updateComponentState(e)}}));try{t.mount("#"+r.containerId)}catch(e){a(new Ee(Pe.PaymentNotInitialized))}}break;case Ca.AliPay:case Ca.GiroPay:case Ca.Sofort:case Ca.Klarna:case Ca.KlarnaPayNow:case Ca.KlarnaAccount:case Ca.Vipps:case Ca.WeChatPayQR:n._updateComponentState({data:{paymentMethod:{type:e.method}}})}o(t)}))},e.prototype._processAdditionalAction=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(!fa(e)||!(0,Z.some)(e.body.errors,{code:"additional_action_required"}))throw e;return[4,this._handleAction(e.body.provider_data)];case 1:r=o.sent(),o.label=2;case 2:return o.trys.push([2,4,,5]),[4,this._paymentIntegrationService.submitPayment((0,s.__assign)((0,s.__assign)({},r),{paymentData:(0,s.__assign)((0,s.__assign)({},r.paymentData),{shouldSaveInstrument:t,shouldSetAsDefaultInstrument:n})}))];case 3:return o.sent(),[3,5];case 4:return i=o.sent(),[2,this._processAdditionalAction(i,t,n)];case 5:return[2]}}))}))},e.prototype._updateComponentState=function(e){this._componentState=e},e.prototype._validateCardData=function(){var e,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&&!t.state.issuer))throw new ga(this._mapCardErrors(t.state.errors))},e.prototype._mapCardErrors=function(e){void 0===e&&(e={});var t={};return Object.keys(e).forEach((function(n){t[n]=[{message:e[n],type:n}]})),t},e}();const Aa=Ea;var Oa=function(){function e(e,t,n){void 0===n&&(n=window),this._scriptLoader=e,this._stylesheetLoader=t,this._window=n}return e.prototype.load=function(e){var t,n;return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return[4,Promise.all([this._stylesheetLoader.loadStylesheet("https://checkoutshopper-"+(null!==(t=e.environment)&&void 0!==t?t:"")+".adyen.com/checkoutshopper/sdk/3.10.1/adyen.css"),this._scriptLoader.loadScript("https://checkoutshopper-"+(null!==(n=e.environment)&&void 0!==n?n:"")+".adyen.com/checkoutshopper/sdk/3.10.1/adyen.js")])];case 1:if(r.sent(),!this._window.AdyenCheckout)throw new Re;return[2,new this._window.AdyenCheckout(e)]}}))}))},e}();const ka=Oa,Ta=le((function(e){return new Aa(e,new ka((0,a.getScriptLoader)(),(0,a.getStylesheetLoader)()))}),[{gateway:"adyenv2"}]);function Ma(e){return!("object"!=typeof e||null===e||void 0!==e.shouldSaveInstrument&&"boolean"!=typeof e.shouldSaveInstrument||void 0!==e.shouldSetAsDefaultInstrument&&"boolean"!=typeof e.shouldSetAsDefaultInstrument)}var Da,Ra,za,Na,La,Fa;!function(e){e.ThreeDS2Fingerprint="threeDS2Fingerprint",e.ThreeDS2="threeDS2",e.Redirect="redirect",e.QRCode="qrCode",e.Voucher="voucher",e.Sdk="sdk"}(Da||(Da={})),function(e){e.SecuredFields="securedfields"}(Ra||(Ra={})),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"}(za||(za={})),function(e){e.POST="POST"}(Na||(Na={})),function(e){e.ChallengeShopper="ChallengeShopper",e.Error="Error",e.IdentifyShopper="IdentifyShopper"}(La||(La={})),function(e){e.CardNumber="encryptedCardNumber",e.SecurityCode="encryptedSecurityCode",e.ExpiryDate="encryptedExpiryDate"}(Fa||(Fa={}));var Ba=function(){function e(e,t){this._paymentIntegrationService=e,this._scriptLoader=t}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!(t=e.adyenv3))throw new ye('Unable to initialize payment because "options.adyenv3" argument is not provided.');return this._paymentInitializeOptions=t,n=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),r=n.initializationData||{},i=r.environment,o=r.clientKey,a=r.paymentMethodsResponse,c=this,[4,this._scriptLoader.load({paymentMethodsConfiguration:{klarna:{useKlarnaWidget:!0},klarna_account:{useKlarnaWidget:!0},klarna_paynow:{useKlarnaWidget:!0}},environment:i,locale:this._paymentIntegrationService.getState().getLocale(),clientKey:o,paymentMethodsResponse:a,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"}}})];case 1:return c._adyenClient=s.sent(),u=this,[4,this._mountPaymentComponent(n)];case 2:return u._paymentComponent=s.sent(),n.method!==za.CreditCard&&n.method!==za.Bancontact?[3,4]:(d=this,[4,this._mountCardVerificationComponent()]);case 3:d._cardVerificationComponent=s.sent(),s.label=4;case 4:return[2,Promise.resolve()]}}))}))},e.prototype.execute=function(e,t){var n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d,l,p,h,m,_,y,f,g;return(0,s.__generator)(this,(function(v){switch(v.label){case 0:if(r=e.payment,i=(0,s.__rest)(e,["payment"]),!r)throw new ha(["payment"]);return o=r.paymentData,a=Ma(o)?o:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1},c=a.shouldSaveInstrument,u=a.shouldSetAsDefaultInstrument,this._validateCardData(),d=this._componentState||{data:{paymentMethod:{type:r.methodId}}},"klarna"!==r.methodId&&"klarna_account"!==r.methodId&&"klarna_paynow"!==r.methodId||null===(n=this._paymentComponent)||void 0===n||n.submit(),[4,this._paymentIntegrationService.submitOrder(i,t)];case 1:if(v.sent(),!o||!ma(o))return[3,6];l={},("object"==typeof(w=d)&&w&&"string"==typeof w.data.paymentMethod.encryptedSecurityCode||"string"==typeof w.data.paymentMethod.encryptedExpiryMonth)&&(p=d.data.paymentMethod,h=p.encryptedCardNumber,m=p.encryptedSecurityCode,_=p.encryptedExpiryMonth,y=p.encryptedExpiryYear,l={credit_card_number_confirmation:h,expiry_month:_,expiry_year:y,verification_value:m}),v.label=2;case 2:return v.trys.push([2,4,,6]),[4,this._paymentIntegrationService.submitPayment((0,s.__assign)((0,s.__assign)({},r),{paymentData:{formattedPayload:{bigpay_token:(0,s.__assign)((0,s.__assign)({},l),{token:o.instrumentId}),origin:window.location.origin,browser_info:_a(),set_as_default_stored_instrument:u||null}}}))];case 3:return v.sent(),[2];case 4:return f=v.sent(),[4,this._processAdditionalAction(f,c,u)];case 5:return v.sent(),[2];case 6:return v.trys.push([6,8,,10]),[4,this._paymentIntegrationService.submitPayment({methodId:r.methodId,paymentData:{formattedPayload:{credit_card_token:{token:JSON.stringify((0,s.__assign)((0,s.__assign)({},d.data.paymentMethod),{type:r.methodId,origin:window.location.origin}))},browser_info:_a(),vault_payment_instrument:c||null,set_as_default_stored_instrument:u||null}}})];case 7:return v.sent(),[3,10];case 8:return g=v.sent(),[4,this._processAdditionalAction(g,c,u)];case 9:return v.sent(),[3,10];case 10:return[2]}var w}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.deinitialize=function(){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()},e.prototype._updateComponentState=function(e){this._componentState=e},e.prototype._getAdyenClient=function(){if(!this._adyenClient)throw new Ee(Pe.PaymentNotInitialized);return this._adyenClient},e.prototype._getPaymentInitializeOptions=function(){if(!this._paymentInitializeOptions)throw new ye('"options.adyenv3" argument was not provided during initialization.');return this._paymentInitializeOptions},e.prototype._handleAction=function(e){var t=this;return new Promise((function(n,r){var i=t._getPaymentInitializeOptions().additionalActionOptions,o=i.onBeforeLoad,a=i.containerId,s=i.onLoad,c=i.onComplete,u=i.widgetSize,d=JSON.parse(e.action),l=t._getAdyenClient().createFromAction(d,{onAdditionalDetails:function(e){var t={methodId:d.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};c&&c(),n(t)},challengeWindowSize:u||"05",onError:function(e){return r(e)}});o&&o(d.type===Da.ThreeDS2||d.type===Da.QRCode||d.type===Da.Sdk),l.mount("#"+a),s&&s((function(){r(new fe),l.unmount()}))}))},e.prototype._mapAdyenPlaceholderData=function(e,t){if(!e)return{};var n=e.firstName,r=e.lastName;return{holderName:t?n+" "+r:"",billingAddress:{street:e.address1,houseNumberOrName:e.address2,postalCode:e.postalCode,city:e.city,stateOrProvince:e.stateOrProvinceCode,country:e.countryCode}}},e.prototype._mountCardVerificationComponent=function(){var e,t=this,n=this._getPaymentInitializeOptions(),r=this._getAdyenClient();return new Promise((function(i,o){var a,c,u;if(n.cardVerificationContainerId){e=r.create(Ra.SecuredFields,(0,s.__assign)((0,s.__assign)({},n.options),{styles:(0,s.__assign)((0,s.__assign)({},null===(a=n.options)||void 0===a?void 0:a.styles),{placeholder:(0,s.__assign)({color:"transparent",caretColor:"#000"},null===(u=null===(c=n.options)||void 0===c?void 0:c.styles)||void 0===u?void 0:u.placeholder)}),onChange:function(e){return t._updateComponentState(e)},onError:function(e){return n.validateCardFields(e)},onFieldValid:function(e){return n.validateCardFields(e)}}));try{e.mount("#"+n.cardVerificationContainerId)}catch(e){o(new Ee(Pe.PaymentNotInitialized))}}i(e)}))},e.prototype._mountPaymentComponent=function(e){var t,n=this,r=this._getPaymentInitializeOptions(),i=this._getAdyenClient();return new Promise((function(o,a){var c=n._paymentIntegrationService.getState().getBillingAddress(),u=e.initializationData.prefillCardHolderName;t=i.create(e.method,(0,s.__assign)((0,s.__assign)((0,s.__assign)({},r.options),{showBrandsUnderCardNumber:!1,onChange:function(e){return n._updateComponentState(e)},onSubmit:function(e){return n._updateComponentState(e)}}),c?{data:n._mapAdyenPlaceholderData(c,u)}:{}));try{t.mount("#"+r.containerId)}catch(e){a(new Ee(Pe.PaymentNotInitialized))}o(t)}))},e.prototype._processAdditionalAction=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(!fa(e)||!(0,Z.some)(e.body.errors,{code:"additional_action_required"}))throw e;return[4,this._handleAction(e.body.provider_data)];case 1:r=o.sent(),o.label=2;case 2:return o.trys.push([2,4,,5]),[4,this._paymentIntegrationService.submitPayment((0,s.__assign)((0,s.__assign)({},r),{paymentData:(0,s.__assign)((0,s.__assign)({},r.paymentData),{shouldSaveInstrument:t,shouldSetAsDefaultInstrument:n})}))];case 3:return o.sent(),[3,5];case 4:return i=o.sent(),[2,this._processAdditionalAction(i,t,n)];case 5:return[2]}}))}))},e.prototype._validateCardData=function(){var e,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 ga(this._mapCardErrors(t.state.errors))},e.prototype._mapCardErrors=function(e){void 0===e&&(e={});var t={};return Object.keys(e).forEach((function(n){t[n]=[{message:e[n],type:n}]})),t},e}();const Ua=Ba;var xa=function(){function e(e,t,n){void 0===n&&(n=window),this._scriptLoader=e,this._stylesheetLoader=t,this._window=n}return e.prototype.load=function(e){var t,n;return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return[4,Promise.all([this._stylesheetLoader.loadStylesheet("https://checkoutshopper-"+(null!==(t=e.environment)&&void 0!==t?t:"")+".adyen.com/checkoutshopper/sdk/5.24.0/adyen.css"),this._scriptLoader.loadScript("https://checkoutshopper-"+(null!==(n=e.environment)&&void 0!==n?n:"")+".adyen.com/checkoutshopper/sdk/5.24.0/adyen.js")])];case 1:if(r.sent(),!this._window.AdyenCheckout)throw new Re;return[4,this._window.AdyenCheckout(e)];case 2:return[2,r.sent()]}}))}))},e}();const qa=xa,Va=le((function(e){return new Ua(e,new qa((0,a.getScriptLoader)(),(0,a.getStylesheetLoader)()))}),[{gateway:"adyenv3"}]);var Ga;!function(e){e.Shipping="Shipping",e.Subtotal="Subtotal"}(Ga||(Ga={}));var Ha=function(){function e(e,t,n){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=n,this._shippingLabel=Ga.Shipping,this._subTotalLabel=Ga.Subtotal}return e.prototype.initialize=function(e){var t,n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:if(!(null==e?void 0:e.methodId))throw new ye('Unable to submit payment because "options.methodId" argument is not provided.');return r=e.methodId,this._shippingLabel=(null===(t=e.applepay)||void 0===t?void 0:t.shippingLabel)||Ga.Shipping,this._subTotalLabel=(null===(n=e.applepay)||void 0===n?void 0:n.subtotalLabel)||Ga.Subtotal,[4,this._paymentIntegrationService.loadPaymentMethod(r)];case 1:return i.sent(),[2]}}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d,l,p=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(n=e.payment,r=this._paymentIntegrationService.getState(),i=r.getCheckoutOrThrow(),o=r.getCartOrThrow(),a=r.getStoreConfigOrThrow(),!n)throw new ha(["payment"]);return c=n.methodId,u=r.getPaymentMethodOrThrow(c),d=this._getBaseRequest(o,i,a,u),l=this._sessionFactory.create(d),[4,this._paymentIntegrationService.submitOrder({useStoreCredit:e.useStoreCredit},t)];case 1:return s.sent(),l.begin(),[2,new Promise((function(e,t){p._handleApplePayEvents(l,u,{resolve:e,reject:t})}))]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype._getBaseRequest=function(e,t,n,r){var i=n.storeProfile,o=i.storeCountryCode,a=i.storeName,s=e.currency.decimalPlaces,c=r.initializationData,u=c.merchantCapabilities,d=c.supportedNetworks,l=[{label:this._subTotalLabel,amount:""+t.subtotal.toFixed(s)}];return t.taxes.forEach((function(e){return l.push({label:e.name,amount:""+e.amount.toFixed()})})),l.push({label:this._shippingLabel,amount:""+t.shippingCostTotal.toFixed(s)}),{countryCode:o,currencyCode:e.currency.code,merchantCapabilities:u,supportedNetworks:d,lineItems:l,total:{label:a,amount:""+t.grandTotal.toFixed(e.currency.decimalPlaces),type:"final"}}},e.prototype._handleApplePayEvents=function(e,t,n){var r=this;e.onvalidatemerchant=function(n){return(0,s.__awaiter)(r,void 0,void 0,(function(){var r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this._onValidateMerchant(t,n)];case 1:return r=i.sent().body,e.completeMerchantValidation(r),[3,3];case 2:throw i.sent(),new Error("Merchant validation failed");case 3:return[2]}}))}))},e.oncancel=function(){return(0,s.__awaiter)(r,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){return[2,n.reject(new fe("Continue with applepay"))]}))}))},e.onpaymentauthorized=function(i){return r._onPaymentAuthorized(i,e,t,n)}},e.prototype._onValidateMerchant=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n;return(0,s.__generator)(this,(function(r){return n=["validationUrl="+t.validationURL,"merchantIdentifier="+e.initializationData.merchantId,"displayName="+e.initializationData.storeName,"domainName="+window.location.hostname].join("&"),[2,this._requestSender.post((i=e.initializationData.paymentsUrl,i+"/api/public/v1/payments/applepay/validate_merchant"),{credentials:!1,headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","X-XSRF-TOKEN":null},body:n})];var i}))}))},e.prototype._onPaymentAuthorized=function(e,t,n,r){return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:i=e.payment.token,o={methodId:n.id,paymentData:{formattedPayload:{apple_pay_token:{payment_data:i.paymentData,payment_method:i.paymentMethod,transaction_id:i.transactionIdentifier}}}},a.label=1;case 1:return a.trys.push([1,3,,4]),[4,this._paymentIntegrationService.submitPayment(o)];case 2:return a.sent(),t.completePayment(ApplePaySession.STATUS_SUCCESS),[2,r.resolve()];case 3:return a.sent(),t.completePayment(ApplePaySession.STATUS_FAILURE),[2,r.reject(new Ee(Pe.PaymentNotInitialized))];case 4:return[2]}}))}))},e}();const Ya=Ha,ja=le((function(e){var t=e.getState().getHost;return new Ya((0,o.createRequestSender)({host:t()}),e,new ve)}),[{id:"applepay"}]);function Wa(e,t){if(null==e)throw t?t():new Error("An unexpected error has occurred.");return e}var Ka;!function(e){e.CardCode="cardCode",e.CardCodeVerification="cardCodeVerification",e.CardExpiry="cardExpiry",e.CardName="cardName",e.CardNumber="cardNumber",e.CardNumberVerification="cardNumberVerification"}(Ka||(Ka={}));const Ja=Ka;function Za(e){return Ja.CardNumber in e}function Qa(e){return Ja.CardCodeVerification in e||Ja.CardNumberVerification in e}var Xa=function(){function e(e,t){this._paymentIntegrationService=e,this._blueSnapDirectHostedForm=t}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.methodId,n=e.gatewayId,r=e.creditCard,!n||!r)throw new ye;return[4,this._paymentIntegrationService.loadPaymentMethod(n,{params:{method:t}})];case 1:return i=s.sent(),o=i.getPaymentMethodOrThrow(t,n),a=o.config,c=a.testMode,u=a.is3dsEnabled,d=o.clientToken,this._paymentFieldsToken=d,this._shouldUseHostedFields=Za(r.form.fields)||Qa(r.form.fields)&&(!!r.form.fields.cardNumberVerification||!!r.form.fields.cardCodeVerification),this._shouldUseHostedFields?[4,this._blueSnapDirectHostedForm.initialize(c,r.form.fields)]:[3,4];case 2:return s.sent(),[4,this._blueSnapDirectHostedForm.attach(this._getPaymentFieldsToken(),r,u)];case 3:s.sent(),s.label=4;case 4:return[2]}}))}))},e.prototype.execute=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u;return(0,s.__generator)(this,(function(d){switch(d.label){case 0:if(!e.payment)throw new ha(["payment"]);return t=e.payment.paymentData,n=Ma(t)?t:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1},r=n.shouldSaveInstrument,i=n.shouldSetAsDefaultInstrument,o=this._getPaymentFieldsToken(),a=this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e.payment.methodId,e.payment.gatewayId).config.is3dsEnabled,this._shouldUseHostedFields?[4,this._blueSnapDirectHostedForm.validate().submit(a?this._getBlueSnapDirectThreeDSecureData():void 0,!(Ma(t)&&ma(t)))]:[3,2];case 1:return u=d.sent(),[3,3];case 2:u=void 0,d.label=3;case 3:return c=u,[4,this._paymentIntegrationService.submitOrder()];case 4:return d.sent(),Ma(t)&&ma(t)&&t.instrumentId?[4,this._paymentIntegrationService.submitPayment((0,s.__assign)((0,s.__assign)({},e.payment),{paymentData:(0,s.__assign)((0,s.__assign)({instrumentId:t.instrumentId},this._shouldUseHostedFields?{nonce:o}:{}),{shouldSetAsDefaultInstrument:!!i})}))]:[3,6];case 5:return d.sent(),[2];case 6:return[4,this._paymentIntegrationService.submitPayment((0,s.__assign)((0,s.__assign)({},e.payment),{paymentData:{formattedPayload:{credit_card_token:{token:JSON.stringify({pfToken:o,cardHolderName:c&&c.cardHolderName})},vault_payment_instrument:r,set_as_default_stored_instrument:i}}}))];case 7:return d.sent(),[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.deinitialize=function(){return this._shouldUseHostedFields&&this._blueSnapDirectHostedForm.detach(),Promise.resolve()},e.prototype._getBlueSnapDirectThreeDSecureData=function(){var e,t=this._paymentIntegrationService.getState(),n=t.getBillingAddress,r=t.getShippingAddress,i=t.getCustomer,o=t.getCheckoutOrThrow,a=t.getCartOrThrow,c=n(),u=r(),d=(null===(e=i())||void 0===e?void 0:e.email)||(null==c?void 0:c.email),l=(null==c?void 0:c.phone)||(null==u?void 0:u.phone);return(0,s.__assign)((0,s.__assign)((0,s.__assign)((0,s.__assign)({amount:o().outstandingBalance,currency:a().currency.code},d&&{email:d}),l&&{phone:l}),c&&{billingFirstName:c.firstName,billingLastName:c.lastName,billingCountry:c.countryCode,billingState:c.stateOrProvinceCode,billingCity:c.city,billingAddress:(c.address1+" "+c.address2).trim(),billingZip:c.postalCode}),u&&{shippingFirstName:u.firstName,shippingLastName:u.lastName,shippingCountry:u.countryCode,shippingState:u.stateOrProvinceCode,shippingCity:u.city,shippingAddress:(u.address1+" "+u.address2).trim(),shippingZip:u.postalCode})},e.prototype._getPaymentFieldsToken=function(){return Wa(this._paymentFieldsToken,(function(){return new me(he.MissingPaymentToken)}))},e}();const $a=Xa;var es,ts,ns,rs,is,os,as,ss;!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"}(es||(es={})),function(e){e.ON_BLUR="onBlur",e.ON_SUBMIT="onSubmit"}(ts||(ts={})),function(e){e.EMPTY="empty",e.INVALID="invalid",e.THREE_DS_NOT_ENABLED="3D Secure is not enabled"}(ns||(ns={})),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"}(rs||(rs={})),function(e){e.CardCode="cvv",e.CardExpiry="exp",e.CardName="noc",e.CardNumber="ccn"}(is||(is={}));var cs=((os={})[is.CardNumber]=Ja.CardNumber,os[is.CardExpiry]=Ja.CardExpiry,os[is.CardName]=Ja.CardName,os[is.CardCode]=Ja.CardCode,os),us={empty:(as={},as[Ja.CardNumber]={fieldType:"cardNumber",message:"Credit card number is required",type:"required"},as[Ja.CardNumberVerification]={fieldType:"cardNumber",message:"Credit card number is required",type:"required"},as[Ja.CardExpiry]={fieldType:"cardExpiry",message:"Expiration date is required",type:"required"},as[Ja.CardCode]={fieldType:"cardCode",message:"CVV is required",type:"required"},as[Ja.CardCodeVerification]={fieldType:"cardCode",message:"CVV is required",type:"required"},as[Ja.CardName]={fieldType:"cardName",message:"Full name is required",type:"required"},as),invalid:(ss={},ss[Ja.CardNumber]={fieldType:"cardNumber",message:"Credit card number must be valid",type:"invalid_card_number"},ss[Ja.CardNumberVerification]={fieldType:"cardNumber",message:"Credit card number must be valid",type:"invalid_card_number"},ss[Ja.CardExpiry]={fieldType:"cardExpiry",message:"Expiration date must be a valid future date in MM / YY format",type:"invalid_card_expiry"},ss[Ja.CardCode]={fieldType:"cardCode",message:"CVV must be valid",type:"invalid_card_code"},ss[Ja.CardCodeVerification]={fieldType:"cardCode",message:"CVV must be valid",type:"invalid_card_code"},ss[Ja.CardName]={fieldType:"cardName",message:"Full name is required",type:"required"},ss)},ds=function(){function e(e,t,n){this._scriptLoader=e,this._nameOnCardInput=t,this._hostedInputValidator=n}return e.prototype.initialize=function(e,t){return void 0===e&&(e=!1),(0,s.__awaiter)(this,void 0,void 0,(function(){var n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return n=this,[4,this._scriptLoader.load(e)];case 1:return n._blueSnapSdk=r.sent(),t?Za(t)?(this._hostedInputValidator.initialize(),[2]):Qa(t)&&t.cardNumberVerification&&t.cardCodeVerification?(this._hostedInputValidator.initializeValidationFields(),[2]):(Qa(t)&&t.cardCodeVerification&&this._hostedInputValidator.initializeValidationCVVFields(),[2]):[2]}}))}))},e.prototype.attach=function(e,t,n){void 0===n&&(n=!1);var r=t.form,i=r.fields,o=(0,s.__rest)(r,["fields"]);return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,r=this;return(0,s.__generator)(this,(function(a){if(t=this._getBlueSnapSdk(),!Za(i)&&!Qa(i))throw new ye("Field options must be of type HostedCardFieldOptionsMap");return this._onValidate=o.onValidate,Za(i)&&this._setCustomBlueSnapAttributes(i),Qa(i)&&this._setCustomStoredCardsBlueSnapAttributes(i),[2,new Promise((function(a){var s=r._getHostedPaymentFieldsOptions(e,i,o,a,n);t.hostedPaymentFieldsCreate(s),Za(i)&&r._nameOnCardInput.attach(s,i.cardName.accessibilityLabel,i.cardName.placeholder)}))]}))}))},e.prototype.validate=function(){var e,t=this._hostedInputValidator.validate();if(null===(e=this._onValidate)||void 0===e||e.call(this,t),!t.isValid){var n=Object.entries(t.errors).reduce((function(e,t){var n,r=t[0],i=t[1];return(0,s.__assign)((0,s.__assign)({},e),((n={})[r]=i.map((function(e){return{message:e.message,type:e.type}})),n))}),{});throw new ga(n)}return this},e.prototype.submit=function(e,t){var n=this;return void 0===t&&(t=!1),new Promise((function(r,i){return n._getBlueSnapSdk().hostedPaymentFieldsSubmitData((function(e){return n._isBlueSnapDirectCallbackError(e)?i(new be(e.statusCode===rs.THREE_DS_AUTH_FAILED?e.error[0].errorDescription:"Submission failed with status: "+e.statusCode+" and errors: "+JSON.stringify(e.error))):r((0,s.__assign)((0,s.__assign)({},e.cardData),t?{cardHolderName:n._nameOnCardInput.getValue()}:{}))}),e)}))},e.prototype.detach=function(){this._nameOnCardInput.detach()},e.prototype._isBlueSnapDirectCallbackError=function(e){return"error"in e},e.prototype._getHostedPaymentFieldsOptions=function(e,t,n,r,i){var o,a=this,c=n.onFocus,u=n.onBlur,d=n.onValidate,l=n.onCardTypeChange,p=n.onEnter,h=n.styles;return(0,s.__assign)((0,s.__assign)((0,s.__assign)({token:e,onFieldEventHandler:{setupComplete:function(){return r()},onFocus:this._usetUiEventCallback(c),onBlur:this._usetUiEventCallback(u),onError:this._handleError(d),onType:function(e,t){return null==l?void 0:l({cardType:es[t]})},onEnter:this._usetUiEventCallback(p),onValid:function(e){return null==d?void 0:d(a._hostedInputValidator.validate({tagId:e}))}}},Za(t)&&{ccnPlaceHolder:t.cardNumber.placeholder||"",cvvPlaceHolder:(null===(o=t.cardCode)||void 0===o?void 0:o.placeholder)||"",expPlaceHolder:t.cardExpiry.placeholder||"MM / YY"}),h&&{style:this._mapStyles(h)}),{"3DS":i})},e.prototype._mapStyles=function(e){var t=e.default,n=e.error,r=e.focus;return Object.entries((0,s.__assign)((0,s.__assign)((0,s.__assign)({},t&&{input:t}),n&&{".invalid":n}),r&&{":focus":r})).reduce((function(e,t){var n,r=t[0],i=t[1];return(0,s.__assign)((0,s.__assign)({},e),((n={})[r]=Object.entries(i).reduce((function(e,t){var n,r=t[0],i=t[1];return(0,s.__assign)((0,s.__assign)({},e),((n={})[(0,Z.kebabCase)(r)]=i,n))}),{}),n))}),{})},e.prototype._handleError=function(e){var t=this;return function(n,r,i,o){if(r===rs.INVALID_OR_EMPTY&&n&&function(e){return void 0!==e&&[ns.EMPTY,ns.INVALID].includes(e)}(i))return null==e?void 0:e(t._hostedInputValidator.validate({tagId:n,errorDescription:i}));throw new be("An unexpected error has occurred: "+JSON.stringify({tagId:n,errorCode:r,errorDescription:i,eventOrigin:o}))}},e.prototype._usetUiEventCallback=function(e){return function(t){e&&e({fieldType:cs[t]})}},e.prototype._getBlueSnapSdk=function(){return Wa(this._blueSnapSdk,(function(){return new Ee(Pe.PaymentNotInitialized)}))},e.prototype._setCustomBlueSnapAttributes=function(e){var t=e.cardNumber,n=e.cardExpiry,r=e.cardCode,i=e.cardName,o=document.getElementById(t.containerId),a=document.getElementById(n.containerId),s=r&&document.getElementById(r.containerId),c=document.getElementById(i.containerId);if(!(o&&a&&s&&c))throw new ye("Unable to create hosted payment fields to invalid HTML container elements.");o.dataset.bluesnap=is.CardNumber,a.dataset.bluesnap=is.CardExpiry,s.dataset.bluesnap=is.CardCode,c.dataset.bluesnap=is.CardName},e.prototype._setCustomStoredCardsBlueSnapAttributes=function(e){var t=e.cardNumberVerification,n=e.cardCodeVerification,r=t&&document.getElementById(t.containerId),i=n&&document.getElementById(n.containerId);(r||i)&&(r&&(r.dataset.bluesnap=is.CardNumber),i&&(i.dataset.bluesnap=is.CardCode))},e}();const ls=ds,ps=function(){function e(){this._errors={}}return e.prototype.initialize=function(){this._errors={cardNumber:[us.empty.cardNumber],cardExpiry:[us.empty.cardExpiry],cardCode:[us.empty.cardCode],cardName:[us.empty.cardName]}},e.prototype.initializeValidationFields=function(){this._errors={cardNumber:[us.empty.cardNumber],cardCode:[us.empty.cardCode]}},e.prototype.initializeValidationCVVFields=function(){this._errors={cardCode:[us.empty.cardCode]}},e.prototype.validate=function(e){return e&&this._updateErrors(e.tagId,e.errorDescription),{isValid:Object.values(this._errors).every((function(e){return 0===e.length})),errors:this._errors}},e.prototype._updateErrors=function(e,t){var n=cs[e];this._errors[n]=t?[us[t][n]]:[]},e}();var hs=function(){function e(){}return e.prototype.attach=function(e,t,n){var r,i=e.style,o=e.onFieldEventHandler,a=void 0===o?{}:o,s=a.onFocus,c=a.onBlur,u=a.onValid,d=a.onError,l=a.onEnter;this._style=i,this._create(),this._getInput().addEventListener("focus",this._handleFocus(s)),this._getInput().addEventListener("blur",this._handleBlur(c,u,d)),this._getInput().addEventListener("enter",this._handleEnter(l)),t&&this._getInput().setAttribute("aria-label",t),n&&(this._getInput().placeholder=n),null===(r=document.querySelector('[data-bluesnap="noc"]'))||void 0===r||r.appendChild(this._getInput())},e.prototype.getValue=function(){return this._getInput().value},e.prototype.detach=function(){this._input&&(this._input.remove(),this._input=void 0)},e.prototype._handleFocus=function(e){var t=this;return function(){var n;t._applyStyles(null===(n=t._style)||void 0===n?void 0:n[":focus"]),null==e||e(is.CardName)}},e.prototype._handleBlur=function(e,t,n){var r=this;return function(i){var o,a,s=i.target;null==e||e(is.CardName),s instanceof HTMLInputElement&&(/\w{1,200}/.test(s.value)?(r._applyStyles(null===(o=r._style)||void 0===o?void 0:o.input),null==t||t(is.CardName)):(r._applyStyles(null===(a=r._style)||void 0===a?void 0:a[".invalid"]),null==n||n(is.CardName,rs.INVALID_OR_EMPTY,ns.EMPTY,ts.ON_BLUR)))}},e.prototype._handleEnter=function(e){return function(){return null==e?void 0:e(is.CardName)}},e.prototype._applyStyles=function(e){var t=this;void 0===e&&(e={});var n={color:e.color,fontFamily:e["font-family"],fontSize:e["font-size"],fontWeight:e["font-weight"]},r=Object.keys(n);r.every((function(e){return["color","fontFamily","fontSize","fontWeight"].includes(e)}))&&r.forEach((function(e){n[e]&&(t._getInput().style[e]=n[e]||"")}))},e.prototype._configureInput=function(){this._getInput().autocomplete="cc-name",this._getInput().id=is.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"},e.prototype._getInput=function(){return Wa(this._input,(function(){return new Ee(Pe.PaymentNotInitialized)}))},e.prototype._create=function(){var e;this._input=document.createElement("input"),this._configureInput(),this._applyStyles(null===(e=this._style)||void 0===e?void 0:e.input)},e}();const ms=hs;var _s;!function(e){e.PRODUCTION="https://pay.bluesnap.com/web-sdk/5/bluesnap.js",e.SANDBOX="https://sandpay.bluesnap.com/web-sdk/5/bluesnap.js"}(_s||(_s={}));var ys=function(){function e(e,t){void 0===t&&(t=window),this._scriptLoader=e,this._window=t}return e.prototype.load=function(e){return void 0===e&&(e=!1),(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this._scriptLoader.loadScript(e?_s.SANDBOX:_s.PRODUCTION)];case 1:if(t.sent(),!this._window.bluesnap)throw new Re;return[2,this._window.bluesnap]}}))}))},e}();const fs=ys,gs=le((function(e){return new $a(e,new ls(new fs((0,a.getScriptLoader)()),new ms,new ps))}),[{id:"credit_card",gateway:"bluesnapdirect"}]);var vs=function(){function e(e){this._paymentIntegrationService=e}return e.prototype.initialize=function(){return Promise.resolve()},e.prototype.execute=function(e){var t=e.payment;return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){switch(e.label){case 0:return function(e){if(!function(e){return void 0!==e&&"accountNumber"in e&&"accountType"in e&&"shopperPermission"in e&&"routingNumber"in e}(e))throw new ha}(null==t?void 0:t.paymentData),[4,this._paymentIntegrationService.submitOrder()];case 1:return e.sent(),[4,this._paymentIntegrationService.submitPayment((0,s.__assign)((0,s.__assign)({},t),{paymentData:{formattedPayload:{ecp:{account_number:t.paymentData.accountNumber,account_type:t.paymentData.accountType,shopper_permission:t.paymentData.shopperPermission,routing_number:t.paymentData.routingNumber}}}}))];case 2:return e.sent(),[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.deinitialize=function(){return Promise.resolve()},e}();const ws=vs,Cs=le((function(e){return new ws(e)}),[{id:"ecp",gateway:"bluesnapdirect"}]);var Ss=function(){function e(e){this._paymentIntegrationService=e}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){if(!(t=e.bluesnapdirect))throw new ye('Unable to initialize payment because "options.bluesnapdirect" argument is not provided.');return this._initializeOptions=t,[2,Promise.resolve()]}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d,l,p,h;return(0,s.__generator)(this,(function(m){switch(m.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!n)throw new ha(["payment"]);if(!this._initializeOptions)throw new Ee(Pe.PaymentNotInitialized);return[4,this._paymentIntegrationService.submitOrder(r,t)];case 1:m.sent(),m.label=2;case 2:return m.trys.push([2,4,,5]),[4,this._paymentIntegrationService.submitPayment({methodId:n.methodId})];case 3:return m.sent(),[3,5];case 4:return i=m.sent(),this._isBlueSnapDirectRedirectResponse(i)&&function(e){if("object"!=typeof e||null===e)return!1;var t=e;return!!t.merchantid&&"string"==typeof t.merchantid}(o=JSON.parse(i.body.provider_data))?(a=new URLSearchParams(o).toString(),c=i.body.additional_action_required.data.redirect_url+"&"+a,u=this._initializeOptions,d=u.onLoad,l=u.style,p=function(e,t,n){var r=document.createElement("iframe");if(r.setAttribute("sandbox","allow-top-navigation allow-scripts allow-forms allow-same-origin"),r.src=t,r.name="bluesnap_direct_hosted_payment_page",n){var i=n.border,o=n.height,a=n.width;r.style.border=i||"",r.style.height=o||"",r.style.width=a||""}return r}(0,c,l),h=new cn(new Promise(Z.noop)),d(p,(function(){return h.cancel(new fe)})),[2,Promise.reject()]):[2,Promise.reject(i)];case 5:return[2]}}))}))},e.prototype.finalize=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){return[2,Promise.reject(new ya)]}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype._isBlueSnapDirectRedirectResponse=function(e){var t;if("object"!=typeof e||null===e)return!1;var n=e;if(!n.body)return!1;var r=n.body;return"additional_action_required"===r.status&&!!(null===(t=r.additional_action_required)||void 0===t?void 0:t.data.redirect_url)&&"string"==typeof r.provider_data},e}();const Is=Ss,bs=le((function(e){return new Is(e)}),[{gateway:"bluesnapdirect"}]),Ps=require("local-storage-fallback");var Es=n.n(Ps);const As=function(){function e(e){this.storage=e}return e.prototype.saveExtraItemsData=function(e,t){var n=(0,s.__spreadArrays)(t.physicalItems,t.digitalItems).reduce((function(e,t){return e[t.productId]={brand:t.brand?t.brand:"",category:t.categoryNames?t.categoryNames.join(", "):""},e}),{});try{return this.storage.setItem(this.getStorageKey(e),JSON.stringify(n)),n}catch(e){return{}}},e.prototype.readExtraItemsData=function(e){try{var t=this.storage.getItem(this.getStorageKey(e));if(!t)return null;var n=JSON.parse(t);return function(e){if(!(0,Z.isObject)(e))return!1;var t=Object.values(e).some((function(e){return!(0,Z.isObject)(e)||!("brand"in e)||!("category"in e)}));return Boolean(!t)}(n)?n:null}catch(e){return null}},e.prototype.clearExtraItemData=function(e){try{this.storage.removeItem(this.getStorageKey(e))}catch(e){}},e.prototype.getStorageKey=function(e){return e?"ORDER_ITEMS_"+e:""},e}();function Os(e){return Boolean(e.hasOwnProperty("analytics"))}function ks(e){return"object"==typeof e&&null!==e&&"shouldCreateAccount"in e}const Ts=function(e){function t(n){var r=e.call(this)||this;return r.errorCode=n,r.name="BoltPaymentsFieldError",r.type="bolt_payments_field_error",r.body={errors:[t.getError(n)]},r}return(0,s.__extends)(t,e),t.getError=function(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"}}},t}(pe);var Ms=function(){function e(e,t,n){this.paymentIntegrationService=e,this.boltScriptLoader=t,this.analyticsExtraItemsManager=n,this.useBoltClient=!1,this.useBoltEmbedded=!1}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d,l,p,h,m,_,y,f,g,v;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.bolt,n=e.methodId,i=(r=t||{}).containerId,o=r.onPaymentSelect,a=r.useBigCommerceCheckout,!n)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');return a?[3,2]:(c=this,[4,this.boltScriptLoader.loadBoltClient()]);case 1:return c.boltClient=s.sent(),[2];case 2:if(u=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId),d=u.initializationData,l=u.config,h=(p=d||{}).publishableKey,m=p.developerConfig,_=p.embeddedOneClickEnabled,y=l.testMode,!h)throw new me(he.MissingPaymentMethod);return f=this,[4,this.boltScriptLoader.loadBoltClient(h,y,m)];case 3:if(f.boltClient=s.sent(),this.useBoltClient=!_,this.useBoltEmbedded=!!_,!this.useBoltEmbedded)return[3,6];if(!i)throw new ye('Unable to initialize payment because "options.bolt.containerId" argument is not provided.');if(!o)throw new ye('Unable to initialize payment because "options.bolt.onPaymentSelect" argument is not provided.');return g=this,[4,this.boltScriptLoader.loadBoltEmbedded(h,y,m)];case 4:return g.boltEmbedded=s.sent(),this.mountBoltEmbeddedField(i),v=o,[4,this.hasBoltAccount()];case 5:v.apply(void 0,[s.sent()]),s.label=6;case 6:return[2]}}))}))},e.prototype.deinitialize=function(){var e;return null===(e=this.embeddedField)||void 0===e||e.unmount(),this.boltClient=void 0,this.boltEmbedded=void 0,Promise.resolve()},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c;return(0,s.__generator)(this,(function(u){switch(u.label){case 0:if(this.setExtraItemsForAnalytics(),n=e.payment,r=(0,s.__rest)(e,["payment"]),o=(i=n||{}).methodId,a=i.paymentData,!e.payment)throw new ha(["payment"]);if(!o)throw new me(he.MissingPaymentMethod);if(!a||!function(e){return Boolean((0,Z.isObject)(e)&&("shouldSaveInstrument"in e||"nonce"in e||ks(e)))}(a))throw new me(he.MissingPayment);return[4,this.paymentIntegrationService.submitOrder(r,t)];case 1:return u.sent(),this.useBoltClient?[4,this.getBoltClientPaymentPayload(o,a,t)]:[3,3];case 2:return c=u.sent(),[3,7];case 3:return this.useBoltEmbedded?[4,this.getBoltEmbeddedPaymentPayload(o,a)]:[3,5];case 4:return c=u.sent(),[3,7];case 5:return[4,this.getBoltFullCheckoutPaymentPayload(o,a)];case 6:c=u.sent(),u.label=7;case 7:return[4,this.paymentIntegrationService.submitPayment(c)];case 8:return u.sent(),[2]}}))}))},e.prototype.getBoltClientPaymentPayload=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return[4,this.paymentIntegrationService.loadPaymentMethod(e,n)];case 1:return s.sent(),r=this.paymentIntegrationService.getState(),i=r.getPaymentMethodOrThrow(e),o=i.clientToken,a=r.getCheckoutOrThrow().isStoreCreditApplied,c=t.shouldSaveInstrument,u=this.getBoltClientOrThrow(),[4,this.paymentIntegrationService.applyStoreCredit(a)];case 2:if(s.sent(),!o)throw new me(he.MissingPaymentMethod);return[4,new Promise((function(e,t){var n={success:function(n,r){n.reference?e(n):t(new be("Unable to proceed because transaction reference is unavailable. Please try again later.")),r()},close:function(){t(new fe)}};u.configure({orderToken:o},{},n).open()}))];case 3:return d=s.sent(),[2,{methodId:e,paymentData:{nonce:d.reference,shouldSaveInstrument:c}}]}}))}))},e.prototype.getBoltEmbeddedPaymentPayload=function(e,t){var n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(!ks(t))throw new me(he.MissingPayment);return i=this.validateTokenizeResultOrThrow,[4,null===(n=this.embeddedField)||void 0===n?void 0:n.tokenize()];case 1:return r=i.apply(this,[o.sent()]),[2,{methodId:e,paymentData:{formattedPayload:{credit_card_token:{token:r.token,last_four_digits:r.last4,iin:r.bin,expiration_month:+r.expiration.split("-")[1],expiration_year:+r.expiration.split("-")[0]},provider_data:{create_account:!!t.shouldCreateAccount,embedded_checkout:!0}}}}]}}))}))},e.prototype.getBoltFullCheckoutPaymentPayload=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return[4,this.setBoltOrderId()];case 1:return r.sent(),[4,this.getBoltClientOrThrow().getTransactionReference()];case 2:if(!(n=r.sent()))throw new Te;return[2,{methodId:e,paymentData:(0,s.__assign)((0,s.__assign)({},t),{nonce:n})}]}}))}))},e.prototype.getBoltClientOrThrow=function(){if(!this.boltClient)throw new Ee(Pe.PaymentNotInitialized);return this.boltClient},e.prototype.getBoltEmbeddedOrThrow=function(){if(!this.boltEmbedded)throw new Ee(Pe.PaymentNotInitialized);return this.boltEmbedded},e.prototype.hasBoltAccount=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){var e,t,n,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:e=this.paymentIntegrationService.getState(),t=e.getCustomer(),n=e.getBillingAddress(),r=(null==t?void 0:t.email)||(null==n?void 0:n.email)||"",i=this.getBoltClientOrThrow(),o.label=1;case 1:return o.trys.push([1,3,,4]),[4,i.hasBoltAccount(r)];case 2:return[2,o.sent()];case 3:throw o.sent(),new Te;case 4:return[2]}}))}))},e.prototype.setBoltOrderId=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){var e,t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:e=this.paymentIntegrationService.getState().getOrderOrThrow(),t=this.getBoltClientOrThrow(),n.label=1;case 1:return n.trys.push([1,3,,4]),[4,t.setOrderId(e.orderId)];case 2:return n.sent(),[3,4];case 3:throw n.sent(),new Te;case 4:return[2]}}))}))},e.prototype.mountBoltEmbeddedField=function(e){var t=this.getBoltEmbeddedOrThrow().create("payment_field",{styles:{backgroundColor:"#fff"},renderSeparateFields:!0});t.mount("#"+e),this.embeddedField=t},e.prototype.validateTokenizeResultOrThrow=function(e){if(!e)throw new Te;if(e instanceof Error)throw new Ts(e.message);var t=e.token,n=e.last4,r=e.bin,i=e.expiration,o=+n,a=+r,s=+(""+i).split("-")[1],c=+(""+i).split("-")[0];if(!t||Number.isNaN(o)||Number.isNaN(a)||Number.isNaN(s)||Number.isNaN(c))throw new ha;return e},e.prototype.setExtraItemsForAnalytics=function(){var e=this.paymentIntegrationService.getState(),t=e.getStoreConfigOrThrow(),n=e.getCartOrThrow();if(t.checkoutSettings.isAnalyticsEnabled&&Os(window)){var r=n.id,i=n.lineItems;this.analyticsExtraItemsManager.saveExtraItemsData(r,i)}},e}();const Ds=Ms,Rs=le((function(e){return new Ds(e,new Be((0,a.getScriptLoader)()),new As(Es()))}),[{id:"bolt"}]);function zs(e){return!!e&&"accountNumber"in e&&"routingNumber"in e&&"ownershipType"in e&&"accountType"in e}var Ns=function(){function e(e,t){this.paymentIntegrationService=e,this.braintreeIntegrationService=t}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:if(t=(e.braintreeach||{}).getMandateText,!e.methodId)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');return this.getMandateText=t,[4,this.paymentIntegrationService.loadPaymentMethod(e.methodId)];case 1:if(a.sent(),n=this.paymentIntegrationService.getState(),!(r=n.getPaymentMethodOrThrow(e.methodId)).clientToken)throw new me(he.MissingPaymentMethod);a.label=2;case 2:return a.trys.push([2,4,,5]),this.braintreeIntegrationService.initialize(r.clientToken),i=this,[4,this.braintreeIntegrationService.getUsBankAccount()];case 3:return i.usBankAccount=a.sent(),[3,5];case 4:return o=a.sent(),this.handleError(o),[3,5];case 5:return[2]}}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u;return(0,s.__generator)(this,(function(d){switch(d.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!n)throw new ha(["payment"]);return(i=ma(n.paymentData||{}))?[4,this.tokenizePaymentForVaultedInstrument(n)]:[3,2];case 1:return a=d.sent(),[3,4];case 2:return[4,this.tokenizePayment(n)];case 3:a=d.sent(),d.label=4;case 4:return o=a,i?[4,this.preparePaymentDataForVaultedInstrument(o,n)]:[3,6];case 5:return u=d.sent(),[3,8];case 6:return[4,this.preparePaymentData(o,n)];case 7:u=d.sent(),d.label=8;case 8:return c=u,[4,this.paymentIntegrationService.submitOrder(r,t)];case 9:return d.sent(),[4,this.paymentIntegrationService.submitPayment(c)];case 10:return d.sent(),[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.deinitialize=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){return this.getMandateText=void 0,[2,Promise.resolve()]}))}))},e.prototype.preparePaymentData=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(n=t.paymentData,!zs(r=void 0===n?{}:n))throw new ha(["payment.paymentData"]);return[4,this.braintreeIntegrationService.getSessionId()];case 1:return i=s.sent(),o=r.shouldSaveInstrument,a=r.shouldSetAsDefaultInstrument,c=r.routingNumber,u=r.accountNumber,d={formattedPayload:{vault_payment_instrument:o||null,set_as_default_stored_instrument:a||null,device_info:i||null,tokenized_bank_account:{issuer:c,masked_account_number:u.substr(-4),token:e}}},[2,{methodId:t.methodId,paymentData:d}]}}))}))},e.prototype.preparePaymentDataForVaultedInstrument=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(n=t.paymentData,!ma(r=void 0===n?{}:n)||!Ma(r))throw new ha(["payment.paymentData"]);return[4,this.braintreeIntegrationService.getSessionId()];case 1:return i=o.sent(),[2,{methodId:t.methodId,paymentData:(0,s.__assign)({deviceSessionId:i,instrumentId:r.instrumentId,shouldSetAsDefaultInstrument:r.shouldSetAsDefaultInstrument},e&&{nonce:e})}]}}))}))},e.prototype.tokenizePayment=function(e){var t=e.paymentData;return(0,s.__awaiter)(this,void 0,void 0,(function(){var e,n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:if(e=this.getUsBankAccountOrThrow(),!zs(t))throw new ha(["payment.paymentData"]);if(!(n=ma(t)?"The data are used for stored instrument verification":"function"==typeof this.getMandateText&&this.getMandateText()))throw new ye("Unable to proceed because getMandateText is not provided or returned undefined value.");i.label=1;case 1:return i.trys.push([1,3,,4]),[4,e.tokenize({bankDetails:this.getBankDetails(t),mandateText:n})];case 2:return[2,i.sent().nonce];case 3:return r=i.sent(),this.handleError(r),[3,4];case 4:return[2]}}))}))},e.prototype.tokenizePaymentForVaultedInstrument=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r;return(0,s.__generator)(this,(function(i){if(t=e.methodId,n=e.paymentData,r=void 0===n?{}:n,!this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t).config.isVaultingEnabled)throw new ye("Vaulting is disabled but a vaulted instrument was being used for this transaction");return[2,zs(r)?this.tokenizePayment(e):null]}))}))},e.prototype.getBankDetails=function(e){var t=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),n=e.ownershipType.toLowerCase(),r=e.accountType.toLowerCase();return(0,s.__assign)((0,s.__assign)({accountNumber:e.accountNumber,routingNumber:e.routingNumber,ownershipType:n},"personal"===n?{firstName:e.firstName,lastName:e.lastName}:{businessName:e.businessName}),{accountType:r,billingAddress:{streetAddress:t.address1,extendedAddress:t.address2,locality:t.city,region:t.stateOrProvinceCode,postalCode:t.postalCode}})},e.prototype.getUsBankAccountOrThrow=function(){if(!this.usBankAccount)throw new Ee(Pe.PaymentNotInitialized);return this.usBankAccount},e.prototype.handleError=function(e){if(!Ve(e))throw e;throw new be(e.message)},e}();const Ls=Ns,Fs=le((function(e){var t=window,n=new Ze(new $e((0,a.getScriptLoader)(),t),t);return new Ls(e,n)}),[{id:"braintreeach"}]);var Bs=function(){function e(e,t,n){this.paymentIntegrationService=e,this.braintreeIntegrationService=t,this.loadingIndicator=n}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.gatewayId,n=e.methodId,r=e.braintreelocalmethods,!n)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new ye('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!r)throw new ye('Unable to initialize payment because "options.braintreelocalmethods" argument is not provided.');return this.braintreeLocalMethods=r,this.loadingIndicatorContainer=r.container.split("#")[1],[4,this.paymentIntegrationService.loadPaymentMethod(t)];case 1:if(s.sent(),i=this.paymentIntegrationService.getState(),o=i.getPaymentMethodOrThrow(t),a=o.config.merchantId,!o.clientToken)throw new me(he.MissingPaymentMethod);s.label=2;case 2:return s.trys.push([2,4,,5]),this.braintreeIntegrationService.initialize(o.clientToken),[4,this.braintreeIntegrationService.loadBraintreeLocalMethods(this.getLocalPaymentInstance.bind(this),a||"")];case 3:return s.sent(),[3,5];case 4:return c=s.sent(),this.handleError(c),[3,5];case 5:return[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.deinitialize=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){return this.orderId=void 0,this.toggleLoadingIndicator(!1),[2,Promise.resolve()]}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d,l,p,h,m,_,y,f=this;return(0,s.__generator)(this,(function(g){switch(g.label){case 0:return n=e.payment,r=(0,s.__rest)(e,["payment"]),i=this.paymentIntegrationService.getState(),o=i.getCartOrThrow(),[4,this.braintreeIntegrationService.getSessionId()];case 1:if(a=g.sent(),c=i.getBillingAddressOrThrow(),u=c.firstName,d=c.lastName,l=c.countryCode,p=o.baseAmount,h=o.currency,m=o.email,_=o.lineItems,y=_.physicalItems.length>0,!n)throw new ha(["payment"]);if(this.toggleLoadingIndicator(!0),!this.localPaymentInstance)throw new Te;return[2,new Promise((function(e,i){var c;null===(c=f.localPaymentInstance)||void 0===c||c.startPayment({paymentType:n.methodId,amount:p,fallback:{url:"url-placeholder",buttonText:"button placeholder"},currencyCode:h.code,shippingAddressRequired:y,email:m,givenName:u,surname:d,address:{countryCode:l},onPaymentStart:function(e,t){f.orderId=e.paymentId,t()}},(function(c,u){return(0,s.__awaiter)(f,void 0,void 0,(function(){var d,l,p,h=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return c?("LOCAL_PAYMENT_WINDOW_CLOSED"!==c.code&&i((function(){return h.handleError(c)})),this.toggleLoadingIndicator(!1),i(),[3,6]):[3,1];case 1:if(!this.orderId)throw Te;d={formattedPayload:(p={device_info:a||null,method:n.methodId},p[n.methodId+"_account"]={email:o.email,token:u.nonce,order_id:this.orderId},p.vault_payment_instrument=null,p.set_as_default_stored_instrument=null,p)},s.label=2;case 2:return s.trys.push([2,5,,6]),[4,this.paymentIntegrationService.submitOrder(r,t)];case 3:return s.sent(),[4,this.paymentIntegrationService.submitPayment({methodId:n.methodId,paymentData:d})];case 4:return s.sent(),e(),[3,6];case 5:return l=s.sent(),i((function(){return h.handleError(l)})),[3,6];case 6:return[2]}}))}))}))}))]}}))}))},e.prototype.getLocalPaymentInstance=function(e){this.localPaymentInstance||(this.localPaymentInstance=e)},e.prototype.toggleLoadingIndicator=function(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()},e.prototype.handleError=function(e){var t=(this.braintreeLocalMethods||{}).onError;this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)},e}();const Us=Bs;var xs={size:70,color:"#d9d9d9",backgroundColor:"#ffffff"},qs="embedded-checkout-loading-indicator-rotation",Vs=function(){function e(e){this.styles=(0,s.__assign)((0,s.__assign)({},xs),e&&e.styles),this.defineAnimation(),this.container=this.buildContainer(),this.indicator=this.buildIndicator(),this.container.appendChild(this.indicator)}return e.prototype.show=function(e){if(e){var 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"},e.prototype.hide=function(){var e=this,t=function(){e.container.style.visibility="hidden",e.container.removeEventListener("transitionend",t)};this.container.addEventListener("transitionend",t),this.container.style.opacity="0"},e.prototype.buildContainer=function(){var 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",e},e.prototype.buildIndicator=function(){var 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=qs+" 500ms infinite cubic-bezier(0.69, 0.31, 0.56, 0.83)",e},e.prototype.defineAnimation=function(){var e;if(!document.getElementById(qs)){var t=document.createElement("style");t.id=qs,null===(e=document.head)||void 0===e||e.appendChild(t),t.sheet instanceof CSSStyleSheet&&t.sheet.insertRule("\n @keyframes "+qs+" {\n 0% { transform: translateY(-50%) rotate(0deg); }\n 100% { transform: translateY(-50%) rotate(360deg); }\n }\n ",0)}},e}();const Gs=Vs,Hs=le((function(e){var t=window,n=new Ze(new $e((0,a.getScriptLoader)(),t),t);return new Us(e,n,new Gs({styles:{backgroundColor:"black"}}))}),[{gateway:"braintreelocalmethods"}]);var Ys=function(){function e(e){this._paymentIntegrationService=e}return e.prototype.execute=function(e,t){var n,r;return this._isHostedPaymentFormEnabled(null===(n=e.payment)||void 0===n?void 0:n.methodId,null===(r=e.payment)||void 0===r?void 0:r.gatewayId)&&this._shouldRenderHostedForm?this._executeWithHostedForm(e,t):this._executeWithoutHostedForm(e,t)},e.prototype.initialize=function(e){var t=this;if(!this._isHostedPaymentFormEnabled(null==e?void 0:e.methodId,null==e?void 0:e.gatewayId)||!this._isHostedFieldAvailable(e))return this._shouldRenderHostedForm=!1,Promise.resolve();var n=e&&e.creditCard&&e.creditCard.form,r=this._paymentIntegrationService.getState().getStoreConfigOrThrow().paymentSettings,i=(void 0===r?{}:r).bigpayBaseUrl,o=void 0===i?"":i;if(!n)throw new ye;var a=this._paymentIntegrationService.createHostedForm(o,n);return a.attach().then((function(){return t._shouldRenderHostedForm=!0,t._hostedForm=a,Promise.resolve()}))},e.prototype.deinitialize=function(){return this._hostedForm&&this._hostedForm.detach(),Promise.resolve()},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype._executeWithoutHostedForm=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),i=n&&n.paymentData,!n||!i)throw new ha(["payment.paymentData"]);return[4,this._paymentIntegrationService.submitOrder(r,t)];case 1:return o.sent(),[4,this._paymentIntegrationService.submitPayment((0,s.__assign)((0,s.__assign)({},n),{paymentData:i}))];case 2:return o.sent(),[2]}}))}))},e.prototype._executeWithHostedForm=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!(i=this._hostedForm))throw new Ee(Pe.PaymentNotInitialized);if(!n||!n.methodId)throw new ha(["payment.methodId"]);return[4,this._paymentIntegrationService.submitOrder(r,t)];case 1:return o.sent(),[4,i.validate().then((function(){return i.submit(n)}))];case 2:return o.sent(),[2]}}))}))},e.prototype._isHostedPaymentFormEnabled=function(e,t){return!!e&&!0===this._paymentIntegrationService.getState().getPaymentMethodOrThrow(e,t).config.isHostedFormEnabled},e.prototype._isHostedFieldAvailable=function(e){return!(0,Z.values)(e&&e.creditCard&&e.creditCard.form.fields).every(Z.isNil)},e}();const js=Ys,Ws=le((function(e){return new js(e)}),[{default:!0}]);var Ks=function(){function e(e,t){this._formPoster=e,this._paymentIntegrationService=t}return e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c=this;return(0,s.__generator)(this,(function(u){switch(u.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),i=n&&n.paymentData,!n||!i)throw new ha(["payment.paymentData"]);return[4,this._paymentIntegrationService.submitOrder(r,t)];case 1:u.sent(),u.label=2;case 2:return u.trys.push([2,4,,5]),[4,this._paymentIntegrationService.submitPayment((0,s.__assign)((0,s.__assign)({},n),{paymentData:i}))];case 3:return u.sent(),[3,5];case 4:return o=u.sent(),fa(o)&&"object"==typeof(d=o.body)&&null!==d&&"additional_action_required"in d&&this._isAdditionalActionRequired(o.body)?(a=o.body.additional_action_required.data.redirect_url,[2,new Promise((function(){return c.redirectUrl(a)}))]):[2,Promise.reject(o)];case 5:return[2]}var d}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.initialize=function(){return Promise.resolve()},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.redirectUrl=function(e){return this._formPoster.postForm(e,{})},e.prototype._isAdditionalActionRequired=function(e){var t=e.additional_action_required;return"additional_action_required"===e.status&&t&&"offsite_redirect"===t.type},e}();const Js=Ks,Zs=le((function(e){return new Js((0,xe.createFormPoster)(),e)}),[{id:"laybuy"}]);var Qs=function(){function e(e){this._paymentIntegrationService=e}return e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return[4,this._paymentIntegrationService.submitOrder(e,t)];case 1:return n.sent(),[2,Promise.resolve()]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.initialize=function(){return Promise.resolve()},e.prototype.deinitialize=function(){return Promise.resolve()},e}();const Xs=Qs,$s=le((function(e){return new Xs(e)}),[{id:"testgateway"}]);var ec=function(){function e(e){this._paymentIntegrationService=e}return e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return[4,this._paymentIntegrationService.submitOrder((0,Z.omit)(e,"payment"),t)];case 1:return n.sent(),[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.initialize=function(){return Promise.resolve()},e.prototype.deinitialize=function(){return Promise.resolve()},e}();const tc=ec,nc=le((function(e){return new tc(e)}),[{id:"nopaymentdatarequired"}]);var rc=function(){function e(e){this._paymentIntegrationService=e}return e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return[4,this._paymentIntegrationService.submitOrder((0,s.__assign)((0,s.__assign)({},e),{payment:e.payment?{methodId:e.payment.methodId}:void 0}),t)];case 1:return n.sent(),[2,Promise.resolve()]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.initialize=function(){return Promise.resolve()},e.prototype.deinitialize=function(){return Promise.resolve()},e}();const ic=rc,oc=le((function(e){return new ic(e)}),[{type:"PAYMENT_TYPE_OFFLINE"}]);var ac;!function(e){e.ACKNOWLEDGE="ACKNOWLEDGE",e.FINALIZE="FINALIZE",e.INITIALIZE="INITIALIZE"}(ac||(ac={}));const sc=ac;var cc=function(){function e(e){this._paymentIntegrationService=e}return e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d,l;return(0,s.__generator)(this,(function(p){switch(p.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),i=this._shouldSubmitFullPayload(n)?e:r,o=n&&n.paymentData,a=o&&ma(o)&&o.instrumentId||void 0,c=o&&Ma(o)&&o.shouldSaveInstrument||void 0,u=o&&Ma(o)&&o.shouldSetAsDefaultInstrument||void 0,!n)throw new ha(["payment"]);return d=n.methodId,l=n.gatewayId,[4,this._paymentIntegrationService.submitOrder(i,t)];case 1:return p.sent(),[4,this._paymentIntegrationService.initializeOffsitePayment({methodId:d,gatewayId:l,instrumentId:a,shouldSaveInstrument:c,shouldSetAsDefaultInstrument:u})];case 2:return p.sent(),[2]}}))}))},e.prototype.finalize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return t=this._paymentIntegrationService.getState(),n=t.getOrder(),r=t.getPaymentStatus(),!n||r!==sc.ACKNOWLEDGE&&r!==sc.FINALIZE?[3,2]:[4,this._paymentIntegrationService.finalizeOrder(e)];case 1:return i.sent(),[2];case 2:return[2,Promise.reject(new ya)]}}))}))},e.prototype.initialize=function(){return Promise.resolve()},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype._shouldSubmitFullPayload=function(e){return!!e&&("adyen"===e.gatewayId||"barclaycard"===e.gatewayId||"ccavenuemars"===e.methodId)},e}();const uc=cc,dc=le((function(e){return new uc(e)}),[{type:"PAYMENT_TYPE_HOSTED"}]);var lc=function(){function e(e,t,n){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.loadingIndicator=n}return e.prototype.initialize=function(e){var t,n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(i=(r=e||{}).methodId,o=r.paypalcommerce,!i)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(!o)throw new ye('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');return[4,this.paymentIntegrationService.loadPaymentMethod(i)];case 1:return s.sent(),a=this.paymentIntegrationService.getState(),c=a.getPaymentMethodOrThrow(i),(null===(t=c.initializationData)||void 0===t?void 0:t.orderId)?(this.orderId=null===(n=c.initializationData)||void 0===n?void 0:n.orderId,[2]):[4,this.paypalCommerceIntegrationService.loadPayPalSdk(i)];case 2:return s.sent(),this.loadingIndicatorContainer=o.container.split("#")[1],this.renderButton(i,o),[2]}}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!n)throw new ha(["payment"]);if(!this.orderId)throw new Te;return[4,this.paymentIntegrationService.submitOrder(r,t)];case 1:return i.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n.methodId,this.orderId)];case 2:return i.sent(),[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.deinitialize=function(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()},e.prototype.renderButton=function(e,t){var n=this,r=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),i=(this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData||{}).buttonStyle,o=t.container,a=t.onError,s=t.onRenderButton,c=t.onValidate,u=t.submitForm,d={fundingSource:r.FUNDING.PAYPAL,style:this.paypalCommerceIntegrationService.getValidButtonStyle(i),createOrder:function(){return n.paypalCommerceIntegrationService.createOrder("paypalcommercecheckout")},onClick:function(e,t){return n.handleClick(t,c)},onApprove:function(e){return n.handleApprove(e,u)},onCancel:function(){return n.toggleLoadingIndicator(!1)},onError:function(e){return n.handleError(e,a)}};this.paypalButton=r.Buttons(d),this.paypalButton.isEligible()&&(s&&"function"==typeof s&&s(),this.paypalButton.render(o))},e.prototype.handleClick=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i=this;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:return n=e.resolve,r=e.reject,[4,t((function(){return i.toggleLoadingIndicator(!0),n()}),r)];case 1:return o.sent(),[2]}}))}))},e.prototype.handleApprove=function(e,t){var n=e.orderID;this.orderId=n,t(),this.toggleLoadingIndicator(!1)},e.prototype.handleError=function(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)},e.prototype.toggleLoadingIndicator=function(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()},e}();const pc=lc,hc=le((function(e){return new pc(e,Ct(e),new Gs({styles:{backgroundColor:"black"}}))}),[{id:"paypalcommerce"}]);var mc=function(){function e(e,t,n){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.loadingIndicator=n}return e.prototype.initialize=function(e){var t,n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(i=(r=e||{}).methodId,o=r.paypalcommerce,a=r.paypalcommercecredit,c=a||o,!i)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(o&&console.warn('The "options.paypalcommerce" option is deprecated for this strategy, please use "options.paypalcommercevenmo" instead'),!c)throw new ye('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');return[4,this.paymentIntegrationService.loadPaymentMethod(i)];case 1:return s.sent(),u=this.paymentIntegrationService.getState(),d=u.getPaymentMethodOrThrow(i),(null===(t=d.initializationData)||void 0===t?void 0:t.orderId)?(this.orderId=null===(n=d.initializationData)||void 0===n?void 0:n.orderId,[2]):[4,this.paypalCommerceIntegrationService.loadPayPalSdk(i)];case 2:return s.sent(),this.loadingIndicatorContainer=c.container.split("#")[1],this.renderButton(i,c),[2]}}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!n)throw new ha(["payment"]);if(!this.orderId)throw new Te;return[4,this.paymentIntegrationService.submitOrder(r,t)];case 1:return i.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n.methodId,this.orderId)];case 2:return i.sent(),[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.deinitialize=function(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()},e.prototype.renderButton=function(e,t){var n=this,r=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),i=(this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData||{}).buttonStyle,o=t.container,a=t.onError,s=t.onRenderButton,c=t.onValidate,u=t.submitForm,d=[r.FUNDING.PAYLATER,r.FUNDING.CREDIT],l=!1;d.forEach((function(e){if(!l){var t={fundingSource:e,style:n.paypalCommerceIntegrationService.getValidButtonStyle(i),createOrder:function(){return n.paypalCommerceIntegrationService.createOrder("paypalcommercecreditcheckout")},onClick:function(e,t){return n.handleClick(t,c)},onApprove:function(e){return n.handleApprove(e,u)},onCancel:function(){return n.toggleLoadingIndicator(!1)},onError:function(e){return n.handleError(e,a)}};if(n.paypalButton=r.Buttons(t),n.paypalButton.isEligible()||e!==r.FUNDING.PAYLATER){if(!n.paypalButton.isEligible()&&e===r.FUNDING.CREDIT)throw new _e("PayPal "+e+" is not available for your region. Please use PayPal Checkout instead.");s&&"function"==typeof s&&s(),n.paypalButton.render(o),l=!0}}}))},e.prototype.handleClick=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i=this;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:return n=e.resolve,r=e.reject,[4,t((function(){return i.toggleLoadingIndicator(!0),n()}),r)];case 1:return o.sent(),[2]}}))}))},e.prototype.handleApprove=function(e,t){var n=e.orderID;this.orderId=n,t(),this.toggleLoadingIndicator(!1)},e.prototype.handleError=function(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)},e.prototype.toggleLoadingIndicator=function(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()},e}();const _c=mc,yc=le((function(e){return new _c(e,Ct(e),new Gs({styles:{backgroundColor:"black"}}))}),[{id:"paypalcommercecredit"}]);var fc=function(){function e(e,t,n){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.loadingIndicator=n}return e.prototype.initialize=function(e){var t,n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(i=(r=e||{}).methodId,o=r.paypalcommerce,a=r.paypalcommercevenmo,c=a||o,!i)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(o&&console.warn('The "options.paypalcommerce" option is deprecated for this strategy, please use "options.paypalcommercevenmo" instead'),!c)throw new ye('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');return[4,this.paymentIntegrationService.loadPaymentMethod(i)];case 1:return s.sent(),u=this.paymentIntegrationService.getState(),d=u.getPaymentMethodOrThrow(i),(null===(t=d.initializationData)||void 0===t?void 0:t.orderId)?(this.orderId=null===(n=d.initializationData)||void 0===n?void 0:n.orderId,[2]):[4,this.paypalCommerceIntegrationService.loadPayPalSdk(i)];case 2:return s.sent(),this.loadingIndicatorContainer=c.container.split("#")[1],this.renderButton(i,c),[2]}}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!n)throw new ha(["payment"]);if(!this.orderId)throw new Te;return[4,this.paymentIntegrationService.submitOrder(r,t)];case 1:return i.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n.methodId,this.orderId)];case 2:return i.sent(),[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.deinitialize=function(){var e;return this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()},e.prototype.renderButton=function(e,t){var n=this,r=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),i=(this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e).initializationData||{}).buttonStyle,o=t.container,a=t.onError,s=t.onRenderButton,c=t.onValidate,u=t.submitForm,d={fundingSource:r.FUNDING.VENMO,style:this.paypalCommerceIntegrationService.getValidButtonStyle(i),createOrder:function(){return n.paypalCommerceIntegrationService.createOrder("paypalcommercevenmocheckout")},onClick:function(e,t){return n.handleClick(t,c)},onApprove:function(e){return n.handleApprove(e,u)},onCancel:function(){return n.toggleLoadingIndicator(!1)},onError:function(e){return n.handleError(e,a)}};if(this.paypalButton=r.Buttons(d),!this.paypalButton.isEligible())throw new _e("PayPal Venmo is not available for your region. Please use PayPal Checkout instead.");s&&"function"==typeof s&&s(),this.paypalButton.render(o)},e.prototype.handleClick=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i=this;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:return n=e.resolve,r=e.reject,[4,t((function(){return i.toggleLoadingIndicator(!0),n()}),r)];case 1:return o.sent(),[2]}}))}))},e.prototype.handleApprove=function(e,t){var n=e.orderID;this.orderId=n,t(),this.toggleLoadingIndicator(!1)},e.prototype.handleError=function(e,t){this.toggleLoadingIndicator(!1),t&&"function"==typeof t&&t(e)},e.prototype.toggleLoadingIndicator=function(e){e&&this.loadingIndicatorContainer?this.loadingIndicator.show(this.loadingIndicatorContainer):this.loadingIndicator.hide()},e}();const gc=fc,vc=le((function(e){return new gc(e,Ct(e),new Gs({styles:{backgroundColor:"black"}}))}),[{id:"paypalcommercevenmo"}]),wc=function(e){function t(t){var n=e.call(this,t,{message:"The request has timed out or aborted."})||this;return n.name="TimeoutError",n.type="timeout",n}return(0,s.__extends)(t,e),t}(ke);var Cc=function(){function e(e,t,n,r,i){void 0===r&&(r=3e3),void 0===i&&(i=6e5),this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t,this.loadingIndicator=n,this.pollingInterval=r,this.maxPollingTime=i,this.pollingTimer=0,this.stopPolling=Z.noop}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d,l;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.gatewayId,n=e.methodId,r=e.paypalcommerce,i=e.paypalcommercealternativemethods,o=i||r,r&&console.warn('The "options.paypalcommerce" option is deprecated for this strategy, please use "options.paypalcommercealternativemethods" instead'),!n)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(!t)throw new ye('Unable to initialize payment because "options.gatewayId" argument is not provided.');if(!o)throw new ye('Unable to initialize payment because "options.paypalcommercealternativemethods" argument is not provided.');return a=this.paymentIntegrationService.getState(),c=a.getPaymentMethodOrThrow(n,t),u=c.initializationData||{},d=u.orderId,l=u.shouldRenderFields,d?(this.orderId=d,[2]):[4,this.paypalCommerceIntegrationService.loadPayPalSdk(n)];case 1:return s.sent(),this.loadingIndicatorContainer=o.container.split("#")[1],this.renderButton(n,t,o),l&&this.renderFields(n,o),[2]}}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!n)throw new ha(["payment"]);if(!this.orderId)throw new Te;return this.isNonInstantPaymentMethod(n.methodId)?[3,2]:[4,this.paymentIntegrationService.submitOrder(r,t)];case 1:i.sent(),i.label=2;case 2:return[4,this.paypalCommerceIntegrationService.submitPayment(n.methodId,this.orderId)];case 3:return i.sent(),[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new ya)},e.prototype.deinitialize=function(){var e;return this.deinitializePollingMechanism(),this.orderId=void 0,null===(e=this.paypalButton)||void 0===e||e.close(),Promise.resolve()},e.prototype.reinitializeStrategy=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this.deinitialize()];case 1:return t.sent(),[4,this.initialize(e)];case 2:return t.sent(),[2]}}))}))},e.prototype.renderButton=function(e,t,n){var r=this,i=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),o=(this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e,t).initializationData||{}).buttonStyle,a=n.container,s=n.onError,c=n.onRenderButton,u=n.submitForm,d={fundingSource:e,style:this.paypalCommerceIntegrationService.getValidButtonStyle(o),createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommercealternativemethodscheckout")},onClick:function(i,o){return r.handleClick(e,t,n,o)},onApprove:function(e){return r.handleApprove(e,u)},onCancel:function(){return r.resetPollingMechanism()},onError:function(e){return r.handleError(e,s)}};this.paypalButton=i.Buttons(d),this.paypalButton.isEligible()&&(c&&"function"==typeof c&&c(),this.paypalButton.render(a))},e.prototype.handleClick=function(e,t,n,r){return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return i=n.onValidate,o=r.resolve,a=r.reject,this.isNonInstantPaymentMethod(e)?[3,2]:[4,this.initializePollingMechanism(e,t,n)];case 1:s.sent(),s.label=2;case 2:return[4,i((function(){return c.toggleLoadingIndicator(!0),o()}),a)];case 3:return s.sent(),[2]}}))}))},e.prototype.handleApprove=function(e,t){var n=e.orderID;this.orderId=n,this.deinitializePollingMechanism(),t(),this.toggleLoadingIndicator(!1)},e.prototype.handleError=function(e,t){this.resetPollingMechanism(),t&&"function"==typeof t&&t(e)},e.prototype.renderFields=function(e,t){var n=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),r=this.paymentIntegrationService.getState().getBillingAddressOrThrow(),i=r.firstName,o=r.lastName,a=r.email,s=t.apmFieldsContainer,c=t.apmFieldsStyles;if(!s)throw new ye('Unable to initialize payment because "options.paypalcommercealternativemethods" argument should contain "apmFieldsContainer".');var u=document.querySelector(s);u&&(u.innerHTML="");var d={fundingSource:e,style:c||{},fields:{name:{value:i+" "+o},email:{value:a}}};n.PaymentFields(d).render(s)},e.prototype.initializePollingMechanism=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return r=n.onError,i=n.submitForm,[4,new Promise((function(e,t){var n=setTimeout(e,d.pollingInterval);d.stopPolling=function(){clearTimeout(n),t()}}))];case 1:s.sent(),s.label=2;case 2:return s.trys.push([2,7,,8]),this.pollingTimer+=this.pollingInterval,[4,this.paypalCommerceIntegrationService.getOrderStatus()];case 3:return o=s.sent(),a=o===dt.Approved,c=o===dt.Created||o===dt.PayerActionRequired,a?(this.deinitializePollingMechanism(),[2,i()]):c&&this.pollingTimer0&&(n[o.code]={discount_amount:e.toInteger(o.discountedAmount),discount_display_name:o.displayName})}return t.discountAmount>0&&(n.DISCOUNTED_AMOUNT={discount_amount:e.toInteger(t.discountAmount),discount_display_name:"discount"}),n},e.prototype._getCategories=function(e){return e?e.map((function(e){return e.map((function(e){return e.name}))})):[[]]},e}();const lu=du,pu=function(){function e(e){void 0===e&&(e=window),this._window=e}return e.prototype.load=function(e,t){void 0===e&&(e="");var n=this._getScriptURI(t);if(function(e,t,n,r,i,o,a,s){var c=e[n]||{},u=document.createElement(o),d=document.getElementsByTagName(o)[0],l=function(e,t,n){return function(){e[t]._.push([n,arguments])}};c[r]=l(c,r,"set");var p=c[r];c[i]={},c[i]._=[],p._=[],c._=[],c[i][a]=l(c,i,a),c.jsReady=function(){c._.push([a,arguments])};for(var h=0,m="set add save post open empty reset on off trigger ready setProduct".split(" ");h0?o(new be(e.ErrorDescription)):e.Payment&&e.Payment.ExtendedData&&e.Payment.ExtendedData.SignatureVerification===ad.Yes?i({token:t}):o(new be("Transaction signature could not be validated."));case nd.Failure:return o(new be("User failed authentication or an error was encountered while processing the transaction."));case nd.Error:return o(new be(e.ErrorDescription))}}));var a={AcsUrl:e.acs_url,Payload:e.merchant_data},s=n._mapToPartialOrder(t,e.payer_auth_request);r.continue(od.CCA,a,s)}))}))},e.prototype._mapToPartialOrder=function(e,t){var n={BillingAddress:this._mapToCardinalAddress(e.billingAddress)};return e.paymentData&&(n.Account=this._mapToCardinalAccount(e.paymentData)),e.billingAddress.email&&(n.Email1=e.billingAddress.email),e.shippingAddress&&(n.ShippingAddress=this._mapToCardinalAddress(e.shippingAddress)),{Consumer:n,OrderDetails:{OrderNumber:e.id,Amount:e.amount,CurrencyCode:e.currencyCode,OrderChannel:"S",TransactionId:t}}},e.prototype._mapToCardinalAccount=function(e){return{AccountNumber:Number(e.ccNumber),ExpirationMonth:Number(e.ccExpiry.month),ExpirationYear:Number(e.ccExpiry.year),NameOnAccount:e.ccName,CardCode:Number(e.ccCvv)}},e.prototype._mapToCardinalAddress=function(e){var 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},e.prototype._getClientSDK=function(){if(!this._sdk)throw new Pn(bn.PaymentNotInitialized);return this._sdk},e}();const ud=function(){function e(e,t){void 0===t&&(t=window),this._scriptLoader=e,this._window=t}return e.prototype.load=function(e,t){var n=this,r=t?"https://songbirdstag.cardinalcommerce.com/edge/v1/songbird.js":"https://songbird.cardinalcommerce.com/edge/v1/songbird.js";return this._scriptLoader.loadScript(r+"?v="+e).then((function(){if(!n._window.Cardinal)throw new gi;return n._window.Cardinal}))},e}();var dd=function(){function e(e,t,n,r){this._store=e,this._paymentActionCreator=t,this._paymentMethodActionCreator=n,this._cardinalClient=r}return e.prototype.prepare=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._cardinalClient.load(e.id,e.config.testMode)];case 1:return r.sent(),n=(t=this._cardinalClient).configure,[4,this._getClientToken(e)];case 2:return[4,n.apply(t,[r.sent()])];case 3:return r.sent(),[2]}}))}))},e.prototype.start=function(e,t,n,r){return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u,d,l,p,h,m,_,y,f;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return i=this._store.getState(),o=i.instruments.getCardInstrument,a=i.paymentMethods.getPaymentMethodOrThrow,c=t.payment,d=(u=void 0===c?{}:c).methodId,l=void 0===d?"":d,p=u.paymentData,m=Gn(h=void 0===p?{}:p)&&o(h.instrumentId),(_=m?m.iin:r&&r.getBin())?[4,this._cardinalClient.runBinProcess(_)]:[3,2];case 1:s.sent(),s.label=2;case 2:return s.trys.push([2,4,,9]),[4,e((0,Z.merge)(t,{payment:{paymentData:{threeDSecure:{token:a(l).clientToken}}}}),n)];case 3:return[2,s.sent()];case 4:if(!((y=s.sent())instanceof x&&(0,Z.some)(y.body.errors,{code:"three_d_secure_required"})))throw y;return[4,this._cardinalClient.getThreeDSecureData(y.body.three_ds_result,this._getOrderData())];case 5:return f=s.sent(),r?[3,7]:[4,this._store.dispatch(this._paymentActionCreator.submitPayment((0,Z.merge)(t.payment,{paymentData:{threeDSecure:f}})))];case 6:return[2,s.sent()];case 7:return[4,r.submit((0,Z.merge)(t.payment,{paymentData:{threeDSecure:f}}))];case 8:return s.sent(),[2,this._store.getState()];case 9:return[2]}}))}))},e.prototype._getClientToken=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return e.clientToken?[2,e.clientToken]:[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e.id))];case 1:return[2,(0,t.sent().paymentMethods.getPaymentMethodOrThrow)(e.id).clientToken||""]}}))}))},e.prototype._getOrderData=function(){var e=this._store.getState(),t=e.billingAddress.getBillingAddressOrThrow(),n=e.shippingAddress.getShippingAddress(),r=e.checkout.getCheckoutOrThrow(),i=e.order.getOrderOrThrow();return{billingAddress:t,shippingAddress:n,currencyCode:r.cart.currency.code,id:i.orderId.toString(),amount:r.cart.cartAmount}},e}();const ld=dd,pd=function(e){function t(t){var n=e.call(this,t||"The selected payment method was declined. Please select another payment method.")||this;return n.name="PaymentMethodDeclinedError",n.type="payment_declined",n}return(0,s.__extends)(t,e),t}(p);var hd=function(e){function t(t,n,r,i,o,a,s){var c=e.call(this,t,n,r,i)||this;return c._paymentMethodActionCreator=o,c._CBAMGPSScriptLoader=a,c._locale=s,c._sessionId="",c}return(0,s.__extends)(t,e),t.prototype.initialize=function(t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d,l,p=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return[4,e.prototype.initialize.call(this,t)];case 1:return s.sent(),n=t.methodId,[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n))];case 2:return r=s.sent(),i=r.paymentMethods.getPaymentMethodOrThrow(n),o=i.clientToken,a=i.initializationData,c=a.isTestModeFlagEnabled,u=void 0!==c&&c,d=a.merchantId,i.config.is3dsEnabled?(l=this,[4,this._CBAMGPSScriptLoader.load(u)]):[3,5];case 3:if(l._threeDSjs=s.sent(),!this._threeDSjs)throw new Pn(bn.PaymentNotInitialized);if(!o||!d)throw new m(h.MissingPaymentMethod);return this._sessionId=o,[4,this._threeDSjs.configure({merchantId:d,sessionId:this._sessionId,callback:function(){var e;if(null===(e=p._threeDSjs)||void 0===e?void 0:e.isConfigured())return p._store.getState();throw new be("Failed to configure 3DS API.")},configuration:{userLanguage:this._locale,wsVersion:62}})];case 4:s.sent(),s.label=5;case 5:return[2,Promise.resolve(this._store.getState())]}}))}))},t.prototype.execute=function(t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d=this;return(0,s.__generator)(this,(function(l){if(r=t.payment,i=r&&r.paymentData,!r||!i)throw new cu(["payment.paymentData"]);return o=this._store.getState().paymentMethods.getPaymentMethodOrThrow,a=o(r.methodId),(c=a.config.is3dsEnabled)&&(u=(0,s.__assign)((0,s.__assign)({},i),{threeDSecure:{token:this._sessionId}}),t.payment&&(t.payment.paymentData=u)),[2,e.prototype.execute.call(this,t,n).catch((function(e){if(!(c&&e instanceof x&&(0,Z.some)(e.body.errors,{code:"three_d_secure_required"})))return Promise.reject(e);var t=d._store.getState(),n=t.order.getOrder(),r=t.config.getStoreConfigOrThrow().storeProfile.storeId;if(!n||!d._sessionId)throw new m(h.MissingCheckout);var i=r+"_"+n.orderId,o=e.body.three_ds_result.token;return o?d._initiateAuthentication(i,o):Promise.reject(e)}))]}))}))},t.prototype.finalize=function(e){var t=this._store.getState(),n=t.order.getOrder();return n&&t.payment.getPaymentStatus()===bu?this._store.dispatch(this._orderActionCreator.finalizeOrder(n.orderId,e)):Promise.reject(new Hc)},t.prototype.deinitialize=function(){return this._threeDSjs=void 0,this._sessionId="",e.prototype.deinitialize.call(this)},t.prototype._initiateAuthentication=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r=this;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return[4,new Promise((function(n,i){if(!r._threeDSjs)throw new Pn(bn.PaymentNotInitialized);r._threeDSjs.initiateAuthentication(e,t,(function(e){var t=e.error;return t?i(new pd(t.msg)):r._threeDSjs&&"PROCEED"===e.gatewayRecommendation?n(e.restApiResponse):i(new pd)}))}))];case 1:if((n=i.sent()).transaction&&"AUTHENTICATION_AVAILABLE"===n.transaction.authenticationStatus)return[2,this._authenticatePayer(e,t)];throw new pd}}))}))},t.prototype._authenticatePayer=function(e,t,n){return void 0===n&&(n=1),(0,s.__awaiter)(this,void 0,void 0,(function(){var r=this;return(0,s.__generator)(this,(function(i){return[2,new Promise((function(i,o){if(!r._threeDSjs)return o(new Pn(bn.PaymentNotInitialized));r._threeDSjs.authenticatePayer(e,t,(function(i){return(0,s.__awaiter)(r,void 0,void 0,(function(){var r;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:return(r=i.error)?r.cause&&"SERVER_BUSY"===r.cause&&n<5?[4,new Promise((function(e){return setTimeout(e,3e3)}))]:[3,2]:[3,3];case 1:return a.sent(),[2,this._authenticatePayer(e,t,++n)];case 2:return[2,o(new pd)];case 3:return[2,new Promise(Z.noop)]}}))}))}),{fullScreenRedirect:!0})}))]}))}))},t}(wu);const md=hd;var _d=function(){function e(e,t){void 0===t&&(t=window),this._scriptLoader=e,this._window=t}return e.prototype.load=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this._scriptLoader.loadScript("//"+(e?"test":"ap")+"-gateway.mastercard.com/static/threeDS/1.3.0/three-ds.min.js")];case 1:if(t.sent(),!this._window.ThreeDS)throw new gi;return[2,this._window.ThreeDS]}}))}))},e}();const yd=_d;var fd;!function(e){e.StartCheckout="startCheckout",e.CompleteCheckout="completeCheckout",e.CancelCheckout="cancelCheckout"}(fd||(fd={}));var gd=function(){function e(e,t,n,r,i,o,a,s,c){this._store=e,this._checkoutActionCreator=t,this._orderActionCreator=n,this._paymentActionCreator=r,this._paymentMethodActionCreator=i,this._paymentStrategyActionCreator=o,this._requestSender=a,this._chasePayScriptLoader=s,this._wepayRiskClient=c,this._walletEvent$=new u.Subject}return e.prototype.initialize=function(e){var t=this;if(this._methodId=e.methodId,!e.chasepay)throw new ae('Unable to initialize payment because "options.chasepay" argument is not provided.');var n=e.chasepay.walletButton&&document.getElementById(e.chasepay.walletButton);return n&&(this._walletButton=n,this._walletButton.addEventListener("click",this._handleWalletButtonClick)),this._configureWallet(e.chasepay).then((function(){return t._store.getState()}))},e.prototype.deinitialize=function(){return this._walletButton&&this._walletButton.removeEventListener("click",this._handleWalletButtonClick),this._walletButton=void 0,this._chasePayClient=void 0,Promise.resolve(this._store.getState())},e.prototype.execute=function(e,t){var n=this;return this._getPayment().catch((function(e){if(e.subtype===h.MissingPayment)return n._displayWallet().then((function(){return n._getPayment()}));throw e})).then((function(r){return n._createOrder(r,e.useStoreCredit,t)}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype._configureWallet=function(e){var t=this,n=this._store.getState(),r=n.paymentMethods.getPaymentMethod(this._methodId),i=n.config.getStoreConfig();if(!r)throw new m(h.MissingPaymentMethod);if(!i)throw new m(h.MissingCheckoutConfig);return this._chasePayScriptLoader.load(r.config.testMode).then((function(n){var r=n.ChasePay;t._chasePayClient=r,e.logoContainer&&document.getElementById(e.logoContainer)&&t._chasePayClient.insertBrandings({color:"white",containers:[e.logoContainer]}),t._chasePayClient.configure({language:i.storeProfile.storeLanguage}),t._chasePayClient.on(fd.CancelCheckout,(function(){t._walletEvent$.next({type:fd.CancelCheckout}),e.onCancel&&e.onCancel()})),t._chasePayClient.on(fd.CompleteCheckout,(function(n){t._setSessionToken(n.sessionToken).then((function(){t._walletEvent$.next({type:fd.CompleteCheckout}),e.onPaymentSelect&&e.onPaymentSelect()}))}))}))},e.prototype._displayWallet=function(){var e=this;return this._store.dispatch(this._paymentStrategyActionCreator.widgetInteraction((function(){return e._store.dispatch(e._paymentMethodActionCreator.loadPaymentMethod(e._methodId)).then((function(t){var n=t.paymentMethods.getPaymentMethod(e._methodId);if(!e._chasePayClient)throw new Pn(bn.PaymentNotInitialized);if(!n)throw new m(h.MissingPaymentMethod);e._chasePayClient.showLoadingAnimation(),e._chasePayClient.startCheckout(n.initializationData.digitalSessionId)})),new Promise((function(t,n){e._walletEvent$.pipe((0,d.take)(1)).subscribe((function(e){e.type===fd.CancelCheckout?n(new uu):e.type===fd.CompleteCheckout&&t()}))}))}),{methodId:this._methodId}),{queueId:"widgetInteraction"})},e.prototype._setSessionToken=function(e){var t=this,n=this._store.getState().paymentMethods.getPaymentMethod(this._methodId),r=n&&n.initializationData.merchantRequestId;return this._requestSender.post("checkout.php",{headers:(0,s.__assign)({Accept:"text/html","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},C),body:{action:"set_external_checkout",provider:this._methodId,sessionToken:e,merchantRequestId:r}}).then((function(){return Promise.all([t._store.dispatch(t._checkoutActionCreator.loadCurrentCheckout()),t._store.dispatch(t._paymentMethodActionCreator.loadPaymentMethod(t._methodId))])})).then((function(){return t._store.getState()}))},e.prototype._getPayment=function(){var e=this;return this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(this._methodId)).then((function(){return"wepay"===e._methodId?e._wepayRiskClient.initialize().then((function(e){return e.getRiskToken()})):""})).then((function(t){var n=e._store.getState().paymentMethods.getPaymentMethod(e._methodId);if(!n)throw new m(h.MissingPaymentMethod);if(!n.initializationData.paymentCryptogram)throw new m(h.MissingPayment);var r={method:e._methodId,cryptogramId:n.initializationData.paymentCryptogram,eci:n.initializationData.eci,transactionId:btoa(n.initializationData.reqTokenId),ccExpiry:{month:n.initializationData.expDate.toString().substr(0,2),year:n.initializationData.expDate.toString().substr(2,2)},ccNumber:n.initializationData.accountNum,accountMask:n.initializationData.accountMask,extraData:t?{riskToken:t}:void 0};return{methodId:e._methodId,paymentData:r}}))},e.prototype._createOrder=function(e,t,n){var r=this;return this._store.dispatch(this._orderActionCreator.submitOrder({useStoreCredit:t},n)).then((function(){return r._store.dispatch(r._paymentActionCreator.submitPayment(e))}))},e.prototype._handleWalletButtonClick=function(e){e.preventDefault(),this._displayWallet()},(0,s.__decorate)([yn],e.prototype,"_handleWalletButtonClick",null),e}();const vd=gd;var wd;!function(e){e.OffsiteRedirect="offsite_redirect"}(wd||(wd={}));var Cd=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return(0,s.__extends)(t,e),t.prototype.finalize=function(e){var t=this._store.getState(),n=t.order.getOrder();return n&&t.payment.getPaymentStatus()===bu?this._store.dispatch(this._orderActionCreator.finalizeOrder(n.orderId,e)):Promise.reject(new Hc)},t.prototype._executeWithHostedForm=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!(i=this._hostedForm))throw new Pn(bn.PaymentNotInitialized);if(!n||!n.methodId)throw new cu(["payment.methodId"]);a.label=1;case 1:return a.trys.push([1,5,,6]),[4,i.validate()];case 2:return a.sent(),[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 3:return a.sent(),[4,i.submit(n)];case 4:return a.sent(),[3,6];case 5:return o=a.sent(),[2,this._processResponse(o)];case 6:return[2,this._store.dispatch(this._orderActionCreator.loadCurrentOrder())]}}))}))},t.prototype._processResponse=function(e){if(!(e instanceof x))return Promise.reject(e);var t=e.body.additional_action_required;return t&&t.type===wd.OffsiteRedirect?this._performRedirect(t):Promise.reject(e)},t.prototype._performRedirect=function(e){return new Promise((function(){window.location.replace(e.data.redirect_url)}))},t}(wu);const Sd=Cd;var Id=["boleto","oxxo","qpay","ideal"],bd=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return(0,s.__extends)(t,e),t.prototype._executeWithoutHostedForm=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),i=null==n?void 0:n.paymentData,!n||!i)throw new cu(["payment.paymentData"]);return[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 1:a.sent(),a.label=2;case 2:return a.trys.push([2,4,,5]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment((0,s.__assign)((0,s.__assign)({},n),{paymentData:(0,s.__assign)((0,s.__assign)({},i),{formattedPayload:this._createFormattedPayload(n.methodId,i)})})))];case 3:return[2,a.sent()];case 4:return o=a.sent(),[2,this._processResponse(o)];case 5:return[2]}}))}))},t.prototype._createFormattedPayload=function(e,t){var n={ccDocument:""},r="ccDocument"in t?t.ccDocument:"";return-1!==Id.indexOf(e)&&r&&(n.ccDocument=r),n},t}(Sd);const Pd=bd;var Ed=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return(0,s.__extends)(t,e),t.prototype._executeWithoutHostedForm=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),i=n&&n.paymentData,!n||!i)throw new cu(["payment.paymentData"]);return[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 1:a.sent(),a.label=2;case 2:return a.trys.push([2,4,,5]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment((0,s.__assign)((0,s.__assign)({},n),{paymentData:(0,s.__assign)((0,s.__assign)({},i),{formattedPayload:this._createFormattedPayload(n.methodId,i)})})))];case 3:return[2,a.sent()];case 4:return o=a.sent(),[2,this._processResponse(o)];case 5:return[2]}}))}))},t.prototype._createFormattedPayload=function(e,t){if("fawry"===e&&"customerMobile"in t&&"customerEmail"in t)return{customerMobile:t.customerMobile,customerEmail:t.customerEmail}},t}(Sd);const Ad=Ed;var Od=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return(0,s.__extends)(t,e),t.prototype._executeWithoutHostedForm=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),i=null==n?void 0:n.paymentData,!n||!i)throw new cu(["payment.paymentData"]);return[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 1:a.sent(),a.label=2;case 2:return a.trys.push([2,4,,5]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment((0,s.__assign)((0,s.__assign)({},n),{paymentData:(0,s.__assign)((0,s.__assign)({},i),{formattedPayload:this._createFormattedPayload(n.methodId,i)})})))];case 3:return[2,a.sent()];case 4:return o=a.sent(),[2,this._processResponse(o)];case 5:return[2]}}))}))},t.prototype._createFormattedPayload=function(e,t){if("ideal"===e&&"bic"in t)return{bic:t.bic}},t}(Sd);const kd=Od;var Td=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return(0,s.__extends)(t,e),t.prototype._executeWithoutHostedForm=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),i=null==n?void 0:n.paymentData,!n||!i)throw new cu(["payment.paymentData"]);return[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 1:a.sent(),a.label=2;case 2:return a.trys.push([2,4,,5]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment((0,s.__assign)((0,s.__assign)({},n),{paymentData:(0,s.__assign)((0,s.__assign)({},i),{formattedPayload:this._createFormattedPayload(n.methodId,i)})})))];case 3:return[2,a.sent()];case 4:return o=a.sent(),[2,this._processResponse(o)];case 5:return[2]}}))}))},t.prototype._createFormattedPayload=function(e,t){var n={iban:"",bic:""},r="iban"in t?t:n,i=r.iban,o=r.bic;return"sepa"===e&&document&&(n.iban=i,n.bic=o),n},t}(Sd);const Md=Td;var Dd=function(){function e(e,t,n,r,i,o,a,s){this._store=e,this._checkoutValidator=t,this._orderActionCreator=n,this._paymentActionCreator=r,this._paymentMethodActionCreator=i,this._remoteCheckoutRequestSender=o,this._storeCreditActionCreator=a,this._clearpayScriptLoader=s}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return t=this._store.getState().paymentMethods.getPaymentMethodOrThrow,n=t(e.methodId,e.gatewayId),r=this,[4,this._clearpayScriptLoader.load(n)];case 1:return r._clearpaySdk=i.sent(),[2,this._store.getState()]}}))}))},e.prototype.deinitialize=function(){return this._clearpaySdk=void 0,Promise.resolve(this._store.getState())},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!e.payment)throw new cu(["payment.gatewayId","payment.methodId"]);if(n=e.payment,r=n.gatewayId,i=n.methodId,!r||!i)throw new cu(["payment.gatewayId","payment.methodId"]);return o=this._store.getState().checkout.getCheckoutOrThrow().isStoreCreditApplied,a=this._store.getState(),void 0===o?[3,2]:[4,this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(o))];case 1:a=s.sent(),s.label=2;case 2:return[4,this._checkoutValidator.validate(a.checkout.getCheckout(),t)];case 3:if(s.sent(),c=this._store.getState().billingAddress.getBillingAddressOrThrow().countryCode,!this._isCountrySupported(c))throw new ae("Unable to proceed because billing country is not supported.");return[4,this._loadPaymentMethod(r,i,t)];case 4:return a=s.sent(),[4,this._redirectToClearpay(c,a.paymentMethods.getPaymentMethod(i,r))];case 5:return s.sent(),[2,new Promise(Z.noop)]}}))}))},e.prototype.finalize=function(e){var t,n,r;return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(i=this._store.getState(),o=i.payment.getPaymentId(),a=i.config.getContextConfig(),!o)throw new m(h.MissingCheckout);if(!a||!a.payment.token)throw new m(h.MissingCheckoutConfig);return c={methodId:o.providerId,paymentData:{nonce:a.payment.token}},[4,this._store.dispatch(this._orderActionCreator.submitOrder({},e))];case 1:s.sent(),s.label=2;case 2:return s.trys.push([2,4,,7]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment(c))];case 3:return[2,s.sent()];case 4:return u=s.sent(),[4,this._remoteCheckoutRequestSender.forgetCheckout()];case 5:return s.sent(),[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethods())];case 6:throw s.sent(),new hu(null===(r=null===(n=null===(t=u.body)||void 0===t?void 0:t.errors)||void 0===n?void 0:n[0])||void 0===r?void 0:r.message);case 7:return[2]}}))}))},e.prototype._redirectToClearpay=function(e,t){if(!this._clearpaySdk||!t||!t.clientToken)throw new Pn(bn.PaymentNotInitialized);this._clearpaySdk.initialize({countryCode:e}),this._clearpaySdk.redirect({token:t.clientToken})},e.prototype._isCountrySupported=function(e){return"GB"===e},e.prototype._loadPaymentMethod=function(e,t,n){var r;return(0,s.__awaiter)(this,void 0,void 0,(function(){var i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e,(0,s.__assign)((0,s.__assign)({},n),{params:(0,s.__assign)((0,s.__assign)({},null==n?void 0:n.params),{method:t})})))];case 1:return[2,o.sent()];case 2:if((i=o.sent())instanceof x&&422===(null===(r=i.body)||void 0===r?void 0:r.status))throw new ae("Clearpay can't process your payment for this order, please try another payment method");throw i;case 3:return[2]}}))}))},e}();const Rd=Dd;var zd=function(){function e(e,t){void 0===t&&(t=window),this._scriptLoader=e,this._window=t}return e.prototype.load=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this._scriptLoader.loadScript(this._getScriptUrl(e.config.testMode))];case 1:if(t.sent(),!this._window.AfterPay)throw new gi;return[2,this._window.AfterPay]}}))}))},e.prototype._getScriptUrl=function(e){return e?"//portal.sandbox.clearpay.co.uk/afterpay-async.js":"//portal.clearpay.co.uk/afterpay-async.js"},e}();const Nd=zd,Ld=function(e){function t(t,n,r,i,o){var a=e.call(this,t,n,r,i)||this;return a._formPoster=o,a}return(0,s.__extends)(t,e),t.prototype.execute=function(t,n){var r=this;return e.prototype.execute.call(this,t,n).catch((function(e){return e instanceof x&&(0,Z.some)(e.body.errors,{code:"three_d_secure_required"})?new Promise((function(){r._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)}))},t.prototype.finalize=function(e){var t=this._store.getState(),n=t.order.getOrder();return n&&t.payment.getPaymentStatus()===bu?this._store.dispatch(this._orderActionCreator.finalizeOrder(n.orderId,e)):Promise.reject(new Hc)},t}(wu);var Fd=function(e){function t(t,n,r,i,o){var a=e.call(this,t,n,r,i)||this;return a._store=t,a._orderActionCreator=n,a._paymentActionCreator=r,a._hostedFormFactory=i,a._formPoster=o,a}return(0,s.__extends)(t,e),t.prototype.finalize=function(e){var t=this._store.getState(),n=t.order.getOrder();return n&&t.payment.getPaymentStatus()===bu?this._store.dispatch(this._orderActionCreator.finalizeOrder(n.orderId,e)):Promise.reject(new Hc)},t.prototype._executeWithoutHostedForm=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a=this;return(0,s.__generator)(this,(function(c){switch(c.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),i=n&&n.paymentData,!n||!i)throw new cu(["payment.paymentData"]);return[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 1:c.sent(),c.label=2;case 2:return c.trys.push([2,4,,5]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment((0,s.__assign)((0,s.__assign)({},n),{paymentData:i})))];case 3:return[2,c.sent()];case 4:return(o=c.sent())instanceof x&&(0,Z.some)(o.body.errors,{code:"three_d_secure_required"})?[2,new Promise((function(){return a._formPoster.postForm(o.body.three_ds_result.acs_url,{PaReq:o.body.three_ds_result.payer_auth_request||null,TermUrl:o.body.three_ds_result.callback_url||null,MD:o.body.three_ds_result.merchant_data||null})}))]:[2,Promise.reject(o)];case 5:return[2]}}))}))},t.prototype._executeWithHostedForm=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a=this;return(0,s.__generator)(this,(function(c){switch(c.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!(i=this._hostedForm))throw new Pn(bn.PaymentNotInitialized);if(!n||!n.methodId)throw new cu(["payment.methodId"]);c.label=1;case 1:return c.trys.push([1,5,,6]),[4,i.validate()];case 2:return c.sent(),[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 3:return c.sent(),[4,i.submit(n)];case 4:return c.sent(),[3,6];case 5:return(o=c.sent())instanceof x&&(0,Z.some)(o.body.errors,{code:"three_d_secure_required"})?[2,new Promise((function(){return a._formPoster.postForm(o.body.three_ds_result.acs_url,{PaReq:o.body.three_ds_result.payer_auth_request||null,TermUrl:o.body.three_ds_result.callback_url||null,MD:o.body.three_ds_result.merchant_data||null})}))]:[2,Promise.reject(o)];case 6:return[2,this._store.dispatch(this._orderActionCreator.loadCurrentOrder())]}}))}))},t}(wu);const Bd=Fd;var Ud=function(e){function t(t,n,r,i,o){var a=e.call(this,t,n,r,i)||this;return a._threeDSecureFlow=o,a}return(0,s.__extends)(t,e),t.prototype.initialize=function(t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return[4,e.prototype.initialize.call(this,t)];case 1:return i.sent(),n=this._store.getState().paymentMethods.getPaymentMethodOrThrow,(r=n(t.methodId)).config.is3dsEnabled?[4,this._threeDSecureFlow.prepare(r)]:[3,3];case 2:i.sent(),i.label=3;case 3:return[2,this._store.getState()]}}))}))},t.prototype.execute=function(t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o;return(0,s.__generator)(this,(function(a){return r=t.payment,i=(void 0===r?{}:r).methodId,o=void 0===i?"":i,(0,this._store.getState().paymentMethods.getPaymentMethodOrThrow)(o).config.is3dsEnabled?[2,this._threeDSecureFlow.start(e.prototype.execute.bind(this),t,n,this._hostedForm)]:[2,e.prototype.execute.call(this,t,n)]}))}))},t}(wu);const xd=Ud;var qd=function(e){function t(t,n,r,i,o){var a=e.call(this,t,n,r,i)||this;return a._threeDSecureFlow=o,a}return(0,s.__extends)(t,e),t.prototype.initialize=function(t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return[4,e.prototype.initialize.call(this,t)];case 1:return i.sent(),n=this._store.getState().paymentMethods.getPaymentMethodOrThrow,(r=n(t.methodId)).config.is3dsEnabled?[4,this._threeDSecureFlow.prepare(r)]:[3,3];case 2:i.sent(),i.label=3;case 3:return[2,this._store.getState()]}}))}))},t.prototype.execute=function(t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o;return(0,s.__generator)(this,(function(a){return r=t.payment,i=(void 0===r?{}:r).methodId,o=void 0===i?"":i,(0,this._store.getState().paymentMethods.getPaymentMethodOrThrow)(o).config.is3dsEnabled?[2,this._threeDSecureFlow.start(e.prototype.execute.bind(this),t,n,this._hostedForm)]:[2,e.prototype.execute.call(this,t,n)]}))}))},t}(wu);const Vd=qd;var Gd;!function(e){e.complete="complete",e.authentication_not_required="authentication_not_required",e.failed="failed"}(Gd||(Gd={}));const Hd=function(e){function t(t,n,r){var i=e.call(this,r||"There was an error while processing your payment. Please try again or contact us.")||this;return i.type=t,i.name=n,i}return(0,s.__extends)(t,e),t}(p);var Yd=function(){function e(e,t,n,r,i,o,a){this._store=e,this._paymentMethodActionCreator=t,this._orderActionCreator=n,this._paymentActionCreator=r,this._storeCreditActionCreator=i,this._digitalRiverScriptLoader=o,this._billingAddressActionCreator=a}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u=this;return(0,s.__generator)(this,(function(d){switch(d.label){case 0:return this._digitalRiverInitializeOptions=e.digitalriver,t=this._store.getState().paymentMethods.getPaymentMethodOrThrow(e.methodId),n=t.initializationData,r=n.publicKey,i=n.paymentLanguage,o=this._getDigitalRiverInitializeOptions().containerId,a=this,[4,this._digitalRiverScriptLoader.load(r,i)];case 1:return a._digitalRiverJS=d.sent(),c=this,[4,this._store.subscribe((function(t){return(0,s.__awaiter)(u,void 0,void 0,(function(){var n,a;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return t.paymentStrategies.isInitialized({methodId:e.methodId,gatewayId:e.gatewayId})?(n=document.getElementById(o))?(n.innerHTML="",a=this,[4,this._digitalRiverScriptLoader.load(r,i)]):[3,2]:[3,4];case 1:a._digitalRiverJS=s.sent(),s.label=2;case 2:return[4,this._loadWidget(e)];case 3:s.sent(),s.label=4;case 4:return[2]}}))}))}),(function(e){var t=e.checkout.getCheckout();return t&&t.outstandingBalance}),(function(e){var t=e.checkout.getCheckout();return t&&t.coupons}))];case 2:return c._unsubscribe=d.sent(),[2,this._loadWidget(e)]}}))}))},e.prototype.deinitialize=function(){this._unsubscribe&&this._unsubscribe();var e=this._getDigitalRiverInitializeOptions().containerId,t=document.getElementById(e);return t&&(t.innerHTML=""),Promise.resolve(this._store.getState())},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d,l,p;return(0,s.__generator)(this,(function(_){switch(_.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!n||!n.paymentData)throw new cu(["payment.paymentData"]);return i=n.paymentData,o=n.methodId,a=i.shouldSetAsDefaultInstrument,c=void 0!==a&&a,void 0===(u=this._store.getState().checkout.getCheckoutOrThrow().isStoreCreditApplied)?[3,2]:[4,this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(u))];case 1:_.sent(),_.label=2;case 2:return[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 3:if(_.sent(),!this._digitalRiverCheckoutData)throw new m(h.MissingPaymentMethod);if(!Gn(i))return[3,10];_.label=4;case 4:return _.trys.push([4,6,,9]),[4,this._submitVaultedInstrument(o,i.instrumentId,this._digitalRiverCheckoutData.checkoutData.checkoutId,c,!1)];case 5:return[2,_.sent()];case 6:if(d=_.sent(),!this._isAuthenticateSourceAction(d))throw d;return[4,this._authenticateSource(d.body.provider_data)];case 7:return l=_.sent(),[4,this._submitVaultedInstrument(o,i.instrumentId,this._digitalRiverCheckoutData.checkoutData.checkoutId,c,l)];case 8:return[2,_.sent()];case 9:return[3,11];case 10:if(!this._loadSuccessResponse)throw new cu(["this._loadSuccessResponse"]);return p={methodId:n.methodId,paymentData:{formattedPayload:{credit_card_token:{token:JSON.stringify({checkoutId:this._digitalRiverCheckoutData.checkoutData.checkoutId,source:this._loadSuccessResponse,sessionId:this._digitalRiverCheckoutData.sessionId})},vault_payment_instrument:this._loadSuccessResponse.readyForStorage,set_as_default_stored_instrument:!1}}},[2,this._store.dispatch(this._paymentActionCreator.submitPayment(p))];case 11:return[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype._getDigitalRiverJs=function(){if(!this._digitalRiverJS)throw new Pn(bn.PaymentNotInitialized);return this._digitalRiverJS},e.prototype._getErrorMessage=function(e){return e.errors.map((function(e){return"code: "+e.code+" message: "+e.message})).join("\n")},e.prototype._onSuccessResponse=function(e){var t,n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c;return(0,s.__generator)(this,(function(u){switch(u.label){case 0:return r=new ae("Unable to initialize payment because success argument is not provided."),e&&this._submitFormEvent?(i=e.source,o=i.browserInfo,a=i.owner,this._loadSuccessResponse=o?{source:(0,s.__assign)({id:e.source.id,reusable:e.source.reusable},o),readyForStorage:e.readyForStorage}:{source:{id:e.source.id,reusable:e.source.reusable},readyForStorage:e.readyForStorage},a?(c={firstName:a.firstName,lastName:a.lastName,city:a.address.city,company:"",address1:a.address.line1,address2:"",postalCode:a.address.postalCode,countryCode:a.address.country,phone:a.phoneNumber,stateOrProvince:a.address.state,stateOrProvinceCode:a.address.country,customFields:[],email:a.email||a.email},this._loadSuccessResponse.source.owner=e.source.owner,[4,this._store.dispatch(this._billingAddressActionCreator.updateAddress(c))]):[3,2]):[3,3];case 1:u.sent(),u.label=2;case 2:return[2,this._submitFormEvent()];case 3:return[2,null===(n=(t=this._getDigitalRiverInitializeOptions()).onError)||void 0===n?void 0:n.call(t,r)]}}))}))},e.prototype._onReadyResponse=function(e){var t,n;e&&(null===(n=(t=this._getDigitalRiverInitializeOptions()).onRenderButton)||void 0===n||n.call(t))},e.prototype._getDigitalRiverInitializeOptions=function(){if(!this._digitalRiverInitializeOptions)throw new Pn(bn.PaymentNotInitialized);return this._digitalRiverInitializeOptions},e.prototype._loadWidget=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d,l,p,_,y=this;return(0,s.__generator)(this,(function(f){switch(f.label){case 0:return f.trys.push([0,3,,4]),[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e.methodId))];case 1:if(t=f.sent(),n=t.billingAddress.getBillingAddressOrThrow(),r=t.customer.getCustomerOrThrow(),i=t.config.getStoreConfigOrThrow().checkoutSettings.features,o=this._getDigitalRiverInitializeOptions().configuration.paymentMethodConfiguration,a=this._getDigitalRiverInitializeOptions(),c=a.containerId,u=a.configuration,!(d=t.paymentMethods.getPaymentMethodOrThrow(e.methodId).clientToken))throw new m(h.MissingPaymentMethod);if(this._digitalRiverCheckoutData=JSON.parse(d),!this._digitalRiverCheckoutData)throw new m(h.MissingPaymentMethod);return this._mountComplianceSection(this._digitalRiverCheckoutData.checkoutData.sellingEntity),this._submitFormEvent=this._getDigitalRiverInitializeOptions().onSubmitForm,l=i["PROJECT-4802.digital_river_paypal_support"]?[]:["payPal"],p={sessionId:this._digitalRiverCheckoutData.sessionId,options:(0,s.__assign)((0,s.__assign)({},u),{showSavePaymentAgreement:Boolean(r.email)&&u.showSavePaymentAgreement}),billingAddress:{firstName:n.firstName,lastName:n.lastName,email:n.email||r.email,phoneNumber:n.phone,address:{line1:n.address1,line2:n.address2,city:n.city,state:n.stateOrProvinceCode,postalCode:n.postalCode,country:n.countryCode}},paymentMethodConfiguration:(0,s.__assign)((0,s.__assign)({},o),{disabledPaymentMethods:l}),onSuccess:function(e){y._onSuccessResponse(e)},onReady:function(e){y._onReadyResponse(e)},onError:function(e){var t,n,r=new Error(y._getErrorMessage(e));null===(n=(t=y._getDigitalRiverInitializeOptions()).onError)||void 0===n||n.call(t,r)}},_=this,[4,this._getDigitalRiverJs().createDropin(p)];case 2:return _._digitalRiverDropComponent=f.sent(),this._digitalRiverDropComponent.mount(c),[2,t];case 3:throw f.sent(),new Hd("payment.digitalriver_checkout_error","digitalRiverCheckoutError");case 4:return[2]}}))}))},e.prototype._isAuthenticateSourceAction=function(e){return!!(e instanceof x&&(0,Z.some)(e.body.errors,{code:"additional_action_required"}))},e.prototype._authenticateSource=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:if(!this._digitalRiverCheckoutData)throw new ae("Unable to proceed because payload payment argument is not provided.");return[4,this._getDigitalRiverJs().authenticateSource({sessionId:this._digitalRiverCheckoutData.sessionId,sourceId:e.source_id,sourceClientSecret:e.source_client_secret})];case 1:if((t=n.sent()).status===Gd.failed)throw new Error("Source authentication failed, please try again");return[2,t.status===Gd.complete||t.status===Gd.authentication_not_required]}}))}))},e.prototype._submitVaultedInstrument=function(e,t,n,r,i){return(0,s.__awaiter)(this,void 0,void 0,(function(){var o;return(0,s.__generator)(this,(function(a){return o={methodId:e,paymentData:{formattedPayload:{bigpay_token:{token:t},credit_card_token:{token:JSON.stringify({checkoutId:n})},confirm:i,set_as_default_stored_instrument:r||null}}},[2,this._store.dispatch(this._paymentActionCreator.submitPayment(o))]}))}))},e.prototype._mountComplianceSection=function(e){var t=document.getElementById("compliance"),n={classes:{base:"DRElement"},compliance:{entity:e}};if(t)t.innerHTML="",this._getDigitalRiverJs().createElement("compliance",n).mount("compliance");else{var r=document.createElement("div");r.setAttribute("id","compliance"),r.style.cssText="min-height: 45px;",r.classList.add("layout"),document.body.appendChild(r),this._getDigitalRiverJs().createElement("compliance",n).mount("compliance")}},e}();const jd=Yd;var Wd=function(){function e(e,t,n){void 0===n&&(n=window),this._scriptLoader=e,this._stylesheetLoader=t,this._window=n}return e.prototype.load=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return[4,Promise.all([this._stylesheetLoader.loadStylesheet("https://js.digitalriverws.com/v1/css/DigitalRiver.css"),this._scriptLoader.loadScript("https://js.digitalriverws.com/v1/DigitalRiver.js")])];case 1:if(n.sent(),!this._window.DigitalRiver)throw new gi;return[2,Promise.resolve(new this._window.DigitalRiver(e,{locale:t}))]}}))}))},e}();const Kd=Wd;function Jd(){return{color_depth:screen.colorDepth||24,java_enabled:"function"==typeof navigator.javaEnabled&&navigator.javaEnabled(),language:navigator.language||navigator.userLanguage,screen_height:screen.height,screen_width:screen.width,time_zone_offset:(new Date).getTimezoneOffset().toString()}}var Zd=function(){function e(e,t,n,r,i,o,a,s,c){this._store=e,this._checkoutActionCreator=t,this._paymentMethodActionCreator=n,this._paymentStrategyActionCreator=r,this._paymentActionCreator=i,this._orderActionCreator=o,this._googlePayPaymentProcessor=a,this._googlePayProviderProcessor=s,this._braintreeSDKCreator=c}return e.prototype.initialize=function(e){var t;return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:return n=e.methodId,[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n))];case 1:return r=o.sent(),this._paymentMethod=r.paymentMethods.getPaymentMethodOrThrow(n),this._is3dsEnabled=r.paymentMethods.getPaymentMethodOrThrow(n).initializationData.isThreeDSecureEnabled,this._googlePayOptions=this._getGooglePayOptions(e),this._buttonClickEventHandler=this._handleButtonClickedEvent(n),this._paymentMethod.clientToken&&(null===(t=this._braintreeSDKCreator)||void 0===t||t.initialize(this._paymentMethod.clientToken)),[4,this._googlePayPaymentProcessor.initialize(n)];case 2:if(o.sent(),!this._googlePayOptions.walletButton)throw new ae("walletButton argument is missing");if(!(i=document.getElementById(this._googlePayOptions.walletButton)))throw new ae("Unable to create wallet, walletButton ID could not be found");return this._walletButton=i,this._walletButton.addEventListener("click",this._buttonClickEventHandler),[2,Promise.resolve(this._store.getState())]}}))}))},e.prototype.deinitialize=function(){var e=this;return this._walletButton&&this._buttonClickEventHandler&&this._walletButton.removeEventListener("click",this._buttonClickEventHandler),this._buttonClickEventHandler=void 0,this._walletButton=void 0,this._googlePayPaymentProcessor.deinitialize().then((function(){return e._store.getState()}))},e.prototype.execute=function(e,t){var n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d,l,p,_;return(0,s.__generator)(this,(function(y){switch(y.label){case 0:if(!this._googlePayOptions)throw new ae('Unable to initialize payment because "options.googlepay" argument is not provided.');if(!e.payment)throw new cu(["payment"]);return r=e.payment.methodId,""!==(null===(n=this._paymentMethod)||void 0===n?void 0:n.initializationData.nonce)&&(u=this._store.getState(),this._paymentMethod=u.paymentMethods.getPaymentMethodOrThrow(r)),[4,this._getPayment(r)];case 1:return(i=y.sent()).paymentData.nonce&&i.paymentData.cardInformation?[3,4]:(o=this._googlePayOptions,a=o.onError,c=o.onPaymentSelect,[4,this._displayWallet(r,c,a)]);case 2:return y.sent(),[4,this._getPayment(r,!0)];case 3:i=y.sent(),y.label=4;case 4:if(!i.paymentData.nonce)throw new m(h.MissingPayment);y.label=5;case 5:return y.trys.push([5,10,,11]),[4,this._store.dispatch(this._orderActionCreator.submitOrder({useStoreCredit:e.useStoreCredit},t))];case 6:return u=y.sent(),d=void 0,this._is3dsEnabled?(l=u.order.getOrderOrThrow,[4,this._verifyCard(r,l().orderAmount,i)]):[3,8];case 7:d=y.sent(),y.label=8;case 8:return p=(0,s.__assign)((0,s.__assign)({},i),{paymentData:(0,s.__assign)((0,s.__assign)({},i.paymentData),{nonce:(null==d?void 0:d.nonce)||i.paymentData.nonce})}),[4,this._store.dispatch(this._paymentActionCreator.submitPayment(p))];case 9:return[2,y.sent()];case 10:return _=y.sent(),[2,this._processAdditionalAction(_)];case 11:return[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype._processAdditionalAction=function(e){return this._googlePayProviderProcessor?this._googlePayProviderProcessor.processAdditionalAction(e):Promise.reject(e)},e.prototype._verifyCard=function(e,t,n){var r;return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:return e!==Wc.BRAINTREE_GOOGLE_PAY?[3,2]:(i=n.paymentData.nonce,[4,null===(r=this._braintreeSDKCreator)||void 0===r?void 0:r.get3DS()]);case 1:if(o=a.sent(),!i||!o)throw new Pn(bn.PaymentNotInitialized);return[2,this._braintreePresent3DSChallenge(o,t,i)];case 2:return[2]}}))}))},e.prototype._braintreePresent3DSChallenge=function(e,t,n){return new cn(e.verifyCard({amount:t,nonce:n,onLookupComplete:function(e,t){t()}})).promise},e.prototype._getGooglePayOptions=function(e){if(e.methodId===Wc.ADYENV2_GOOGLEPAY&&e.googlepayadyenv2){if(!this._googlePayProviderProcessor)throw new Pn(bn.PaymentNotInitialized);return this._googlePayProviderProcessor.initialize(e),e.googlepayadyenv2}if(e.methodId===Wc.ADYENV3_GOOGLEPAY&&e.googlepayadyenv3){if(!this._googlePayProviderProcessor)throw new Pn(bn.PaymentNotInitialized);return this._googlePayProviderProcessor.initialize(e),e.googlepayadyenv3}if(e.methodId===Wc.AUTHORIZENET_GOOGLE_PAY&&e.googlepayauthorizenet)return e.googlepayauthorizenet;if(e.methodId===Wc.BNZ_GOOGLEPAY&&e.googlepaybnz)return e.googlepaybnz;if(e.methodId===Wc.CHECKOUTCOM_GOOGLE_PAY&&e.googlepaycheckoutcom)return e.googlepaycheckoutcom;if(e.methodId===Wc.CYBERSOURCEV2_GOOGLE_PAY&&e.googlepaycybersourcev2)return e.googlepaycybersourcev2;if(e.methodId===Wc.ORBITAL_GOOGLE_PAY&&e.googlepayorbital)return e.googlepayorbital;if(e.methodId===Wc.BRAINTREE_GOOGLE_PAY&&e.googlepaybraintree)return e.googlepaybraintree;if(e.methodId===Wc.STRIPE_GOOGLE_PAY&&e.googlepaystripe)return e.googlepaystripe;if(e.methodId===Wc.STRIPE_UPE_GOOGLE_PAY&&e.googlepaystripeupe)return e.googlepaystripeupe;if(e.methodId===Wc.WORLDPAYACCESS_GOOGLE_PAY&&e.googlepayworldpayaccess)return e.googlepayworldpayaccess;throw new ae('Unable to initialize payment because "options.googlepay" argument is not provided.')},e.prototype._getPayment=function(e,t){return void 0===t&&(t=!1),(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a;return(0,s.__generator)(this,(function(c){switch(c.label){case 0:if(!e||!this._paymentMethod)throw new Pn(bn.PaymentNotInitialized);return n=this._paymentMethod.initializationData.card_information,(r=this._paymentMethod.initializationData.nonce)&&(this._paymentMethod=(0,s.__assign)((0,s.__assign)({},this._paymentMethod),{initializationData:{nonce:""}})),t?[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(e))]:[3,2];case 1:i=c.sent(),this._paymentMethod=i.paymentMethods.getPaymentMethodOrThrow(e),r=this._paymentMethod.initializationData.nonce,c.label=2;case 2:return o={methodId:e},a={method:e,cardInformation:n},[4,this._encodeNonce(e,r)];case 3:return[2,(o.paymentData=(a.nonce=c.sent(),a),o)]}}))}))},e.prototype._encodeNonce=function(e,t){var n,r;return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(i){return e===Wc.ADYENV2_GOOGLEPAY?[2,JSON.stringify({type:null===(n=this._paymentMethod)||void 0===n?void 0:n.method,googlePayToken:t,browser_info:Jd()})]:e===Wc.ADYENV3_GOOGLEPAY?[2,JSON.stringify({type:null===(r=this._paymentMethod)||void 0===r?void 0:r.method,googlePayToken:t,browser_info:Jd()})]:[2,t]}))}))},e.prototype._paymentInstrumentSelected=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:if(!t)throw new Pn(bn.PaymentNotInitialized);return[4,this._googlePayPaymentProcessor.handleSuccess(e)];case 1:return r.sent(),n=this._store.getState(),this._paymentMethod=n.paymentMethods.getPaymentMethodOrThrow(t),[2,Promise.all([this._store.dispatch(this._checkoutActionCreator.loadCurrentCheckout()),this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(t))])]}}))}))},e.prototype._handleButtonClickedEvent=function(e){var t=this;return function(n){null==n||n.preventDefault();var r=t._store.getState().cart.getCartOrThrow(),i={transactionInfo:{currencyCode:r.currency.code,totalPrice:String(r.cartAmount)}};if(t._googlePayPaymentProcessor.updatePaymentDataRequest(i),!e||!t._googlePayOptions)throw new Pn(bn.PaymentNotInitialized);var o=t._googlePayOptions,a=o.onError,c=o.onPaymentSelect;return t._store.dispatch(t._paymentStrategyActionCreator.widgetInteraction((function(){return(0,s.__awaiter)(t,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){return[2,this._displayWallet(e,c,a)]}))}))}),{methodId:e}),{queueId:"widgetInteraction"})}},e.prototype._displayWallet=function(e,t,n){return void 0===t&&(t=Z.noop),void 0===n&&(n=Z.noop),(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:return o.trys.push([0,3,,4]),[4,this._googlePayPaymentProcessor.displayWallet()];case 1:return r=o.sent(),[4,this._paymentInstrumentSelected(r,e)];case 2:return o.sent(),[2,t()];case 3:if("CANCELED"===(i=o.sent()).statusCode)throw new Error("CANCELED");return n(i),[3,4];case 4:return[2]}}))}))},e}();const Qd=Zd;var Xd=function(){function e(e,t,n){this._store=e,this._paymentActionCreator=t,this._scriptLoader=n}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=this._store.getState(),n=t.paymentMethods.getPaymentMethodOrThrow(e.methodId),!(r=t.config.getStoreConfig()))throw new m(h.MissingCheckoutConfig);return i={key:"",value:""},n.initializationData.originKey?(i.key="originKey",i.value=n.initializationData.originKey):(i.key="clientKey",i.value=n.initializationData.clientKey),o=this,[4,this._scriptLoader.load((a={environment:n.config.testMode?"test":"live",locale:r.storeProfile.storeLanguage},a[i.key]=i.value,a.paymentMethodsResponse=n.initializationData.paymentMethodsResponse,a))];case 1:return o._adyenClient=s.sent(),[2]}}))}))},e.prototype.processAdditionalAction=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return e instanceof x&&(0,Z.some)(e.body.errors,{code:"additional_action_required"})?[4,this._handleAction(e.body.provider_data)]:[2,Promise.reject(e)];case 1:t=r.sent(),r.label=2;case 2:return r.trys.push([2,4,,5]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment(t))];case 3:return[2,r.sent()];case 4:return n=r.sent(),[2,this.processAdditionalAction(n)];case 5:return[2]}}))}))},e.prototype._handleAction=function(e){var t=this;return new Promise((function(n,r){var i=JSON.parse(e.action);t._getAdyenClient().createFromAction(i,{onAdditionalDetails:function(e){var t={methodId:i.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};n(t)},size:"05",onError:function(e){return r(e)}}).mount("body"),r(new uu)}))},e.prototype._getAdyenClient=function(){if(!this._adyenClient)throw new Pn(bn.PaymentNotInitialized);return this._adyenClient},e}();const $d=Xd;var el=function(){function e(e,t,n){this._store=e,this._paymentActionCreator=t,this._scriptLoader=n}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(t=this._store.getState(),n=t.paymentMethods.getPaymentMethodOrThrow(e.methodId),!(r=t.config.getStoreConfig()))throw new m(h.MissingCheckoutConfig);return i=this,[4,this._scriptLoader.load({environment:n.config.testMode?"test":"live",locale:r.storeProfile.storeLanguage,clientKey:n.initializationData.clientKey,paymentMethodsResponse:n.initializationData.paymentMethodsResponse})];case 1:return i._adyenClient=o.sent(),[2]}}))}))},e.prototype.processAdditionalAction=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return e instanceof x&&(0,Z.some)(e.body.errors,{code:"additional_action_required"})?[4,this._handleAction(e.body.provider_data)]:[2,Promise.reject(e)];case 1:t=r.sent(),r.label=2;case 2:return r.trys.push([2,4,,5]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment(t))];case 3:return[2,r.sent()];case 4:return n=r.sent(),[2,this.processAdditionalAction(n)];case 5:return[2]}}))}))},e.prototype._handleAction=function(e){var t=this;return new Promise((function(n,r){var i=JSON.parse(e.action);t._getAdyenClient().createFromAction(i,{onAdditionalDetails:function(e){var t={methodId:i.paymentMethodType,paymentData:{nonce:JSON.stringify(e.data)}};n(t)},challengeWindowSize:"05",onError:function(e){return r(e)}}).mount("body"),r(new uu)}))},e.prototype._getAdyenClient=function(){if(!this._adyenClient)throw new Pn(bn.PaymentNotInitialized);return this._adyenClient},e}();const tl=el,nl=function(){function e(){}return e.prototype.initialize=function(e){return Promise.resolve()},e.prototype.processAdditionalAction=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){return e instanceof x&&(0,Z.some)(e.body.errors,{code:"three_d_secure_required"})?(t=e.body.three_ds_result.acs_url,[2,this._performRedirect(t)]):[2,Promise.reject(e)]}))}))},e.prototype._performRedirect=function(e){return new Promise((function(){window.location.assign(e)}))},e}();var rl=function(){function e(e,t,n,r,i){this._store=e,this._orderActionCreator=t,this._paymentActionCreator=n,this._formPoster=r,this._paymentMethodActionCreator=i}return e.prototype.execute=function(e,t){var n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c;return(0,s.__generator)(this,(function(u){switch(u.label){case 0:if(r=e.payment,i=(0,s.__rest)(e,["payment"]),!(null==r?void 0:r.methodId))throw new cu(["payment.methodId"]);return[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(r.methodId,t))];case 1:if(o=u.sent(),a=o.paymentMethods.getPaymentMethodOrThrow(r.methodId),!(null===(n=a.initializationData)||void 0===n?void 0:n.processable))throw new Tc("payment.humm_not_processable_error","hummNotProcessableError");return[4,this._store.dispatch(this._orderActionCreator.submitOrder(i,t))];case 2:u.sent(),u.label=3;case 3:return u.trys.push([3,5,,6]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment({methodId:r.methodId}))];case 4:return[2,u.sent()];case 5:return c=u.sent(),this._isOffsiteRedirectResponse(c)?[2,this._handleOffsiteRedirectResponse(c)]:[2,Promise.reject(c)];case 6:return[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype.initialize=function(){return Promise.resolve(this._store.getState())},e.prototype.deinitialize=function(){return Promise.resolve(this._store.getState())},e.prototype._handleOffsiteRedirectResponse=function(e){var t=this,n=e.body.additional_action_required.data.redirect_url,r=e.body.provider_data;return new Promise((function(){t._formPoster.postForm(n,JSON.parse(r))}))},e.prototype._isOffsiteRedirectResponse=function(e){if("object"!=typeof e||null===e)return!1;var t=e;if(!t.body)return!1;var n=t.body;return"additional_action_required"===n.status&&!!n.additional_action_required&&"offsite_redirect"===n.additional_action_required.type&&"string"==typeof n.provider_data},e}();const il=rl;var ol=["AT","BE","CA","CH","CZ","DE","DK","ES","FI","FR","GB","GR","IE","IT","NL","NO","NZ","PL","PT","SE"],al=["AU"],sl=function(){function e(e,t,n,r,i){this._store=e,this._orderActionCreator=t,this._paymentMethodActionCreator=n,this._remoteCheckoutActionCreator=r,this._klarnaScriptLoader=i}return e.prototype.initialize=function(e){var t=this;return this._klarnaScriptLoader.load().then((function(e){t._klarnaCredit=e})).then((function(){return t._unsubscribe=t._store.subscribe((function(n){n.paymentStrategies.isInitialized({methodId:e.methodId,gatewayId:e.gatewayId})&&t._loadWidget(e)}),(function(e){var t=e.checkout.getCheckout();return t&&t.outstandingBalance}),(function(e){var t=e.checkout.getCheckout();return t&&t.coupons})),t._loadWidget(e)})).then((function(){return t._store.getState()}))},e.prototype.deinitialize=function(){return this._unsubscribe&&this._unsubscribe(),Promise.resolve(this._store.getState())},e.prototype.execute=function(e,t){var n=this;if(!e.payment)throw new ae('Unable to proceed because "payload.payment" argument is not provided.');var r=e.payment,i=(r.paymentData,(0,s.__rest)(r,["paymentData"]));return this._authorize().then((function(e){var t=e.authorization_token;return n._store.dispatch(n._remoteCheckoutActionCreator.initializePayment(i.methodId,{authorizationToken:t}))})).then((function(){return n._store.dispatch(n._orderActionCreator.submitOrder((0,s.__assign)((0,s.__assign)({},e),{payment:i,useStoreCredit:e.useStoreCredit}),t))}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype._loadWidget=function(e){var t=this;if(!e.klarna)throw new ae('Unable to load widget because "options.klarna" argument is not provided.');var n=e.methodId,r=e.klarna,i=r.container,o=r.onLoad;return this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n)).then((function(e){return new Promise((function(r){var a=e.paymentMethods.getPaymentMethod(n);if(!a)throw new m(h.MissingPaymentMethod);if(!t._klarnaCredit||!a.clientToken)throw new Pn(bn.PaymentNotInitialized);t._klarnaCredit.init({client_token:a.clientToken}),t._klarnaCredit.load({container:i},(function(e){o&&o(e),r(e)}))}))}))},e.prototype._getUpdateSessionData=function(e,t){if(!(0,Z.includes)((0,s.__spreadArrays)(ol,al),e.countryCode))return{};var n={billing_address:this._mapToKlarnaAddress(e,e.email)};return t&&(n.shipping_address=this._mapToKlarnaAddress(t,e.email)),n},e.prototype._needsStateCode=function(e){return(0,Z.includes)(al,e)},e.prototype._mapToKlarnaAddress=function(e,t){var n={street_address:e.address1,city:e.city,country:e.countryCode,given_name:e.firstName,family_name:e.lastName,postal_code:e.postalCode,region:this._needsStateCode(e.countryCode)?e.stateOrProvinceCode:e.stateOrProvince,email:t};return e.address2&&(n.street_address2=e.address2),e.phone&&(n.phone=e.phone),n},e.prototype._authorize=function(){var e=this;return new Promise((function(t,n){var r=e._store.getState().billingAddress.getBillingAddress(),i=e._store.getState().shippingAddress.getShippingAddress();if(!r)throw new m(h.MissingBillingAddress);if(!e._klarnaCredit)throw new Pn(bn.PaymentNotInitialized);var o=e._getUpdateSessionData(r,i);e._klarnaCredit.authorize(o,(function(e){return e.approved?t(e):e.show_form?n(new uu):void n(new Te)}))}))},e}();const cl=sl,ul=function(){function e(e){this._scriptLoader=e}return e.prototype.load=function(){return this._scriptLoader.loadScript("//credit.klarnacdn.net/lib/v1/api.js").then((function(){return window.Klarna.Credit}))},e}();var dl=function(){function e(e,t,n,r,i){this._store=e,this._orderActionCreator=t,this._remoteCheckoutActionCreator=n,this._klarnav2ScriptLoader=r,this._klarnav2TokenUpdater=i}return e.prototype.initialize=function(e){var t=this;return this._klarnav2ScriptLoader.load().then((function(e){t._klarnaPayments=e})).then((function(){return t._unsubscribe=t._store.subscribe((function(n){n.paymentStrategies.isInitialized({methodId:e.methodId,gatewayId:e.gatewayId})&&t._loadPaymentsWidget(e)}),(function(e){var t=e.checkout.getCheckout();return t&&t.outstandingBalance}),(function(e){var t=e.checkout.getCheckout();return t&&t.coupons})),t._loadPaymentsWidget(e)})).then((function(){return t._store.getState()}))},e.prototype.deinitialize=function(){return this._unsubscribe&&this._unsubscribe(),Promise.resolve(this._store.getState())},e.prototype.execute=function(e,t){var n=this;if(!e.payment)throw new ae('Unable to proceed because "payload.payment" argument is not provided.');var r=e.payment,i=(r.paymentData,(0,s.__rest)(r,["paymentData"])),o=i.gatewayId;if(!o)throw new ae('Unable to proceed because "payload.payment.gatewayId" argument is not provided.');return this._authorize(i.methodId).then((function(e){var t=e.authorization_token;return n._store.dispatch(n._remoteCheckoutActionCreator.initializePayment(o,{authorizationToken:t}))})).then((function(){return n._store.dispatch(n._orderActionCreator.submitOrder((0,s.__assign)((0,s.__assign)({},e),{payment:i,useStoreCredit:e.useStoreCredit}),t))}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype._loadPaymentsWidget=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!e.klarnav2)throw new ae('Unable to load widget because "options.klarnav2" argument is not provided.');if(t=e.methodId,n=e.gatewayId,r=e.klarnav2,i=r.container,o=r.onLoad,!n)throw new ae('Unable to proceed because "payload.payment.gatewayId" argument is not provided.');return a=this._store.getState(),c=a.cart.getCartOrThrow().id,u={params:c},[4,this._klarnav2TokenUpdater.updateClientToken(n,{params:u}).catch((function(){throw new m(h.MissingPaymentMethod)}))];case 1:return s.sent(),[2,new Promise((function(e){var n=a.paymentMethods.getPaymentMethodOrThrow(t);if(!d._klarnaPayments||!n.clientToken)throw new Pn(bn.PaymentNotInitialized);d._klarnaPayments.init({client_token:n.clientToken}),d._klarnaPayments.load({container:i,payment_method_category:n.id},(function(t){o&&o(t),e(t)}))}))]}}))}))},e.prototype._getUpdateSessionData=function(e,t){if(!(0,Z.includes)((0,s.__spreadArrays)(ol,al),e.countryCode))return{};var n={billing_address:this._mapToKlarnaAddress(e,e.email)};return t&&(n.shipping_address=this._mapToKlarnaAddress(t,e.email)),n},e.prototype._needsStateCode=function(e){return(0,Z.includes)(al,e)},e.prototype._mapToKlarnaAddress=function(e,t){var n={street_address:e.address1,city:e.city,country:e.countryCode,given_name:e.firstName,family_name:e.lastName,postal_code:e.postalCode,region:this._needsStateCode(e.countryCode)?e.stateOrProvinceCode:e.stateOrProvince,email:t};return e.address2&&(n.street_address2=e.address2),e.phone&&(n.phone=e.phone),n},e.prototype._authorize=function(e){var t=this;return new Promise((function(n,r){var i=t._store.getState().billingAddress.getBillingAddress(),o=t._store.getState().shippingAddress.getShippingAddress();if(!i)throw new m(h.MissingBillingAddress);var a=t._getUpdateSessionData(i,o);if(!t._klarnaPayments)throw new Pn(bn.PaymentNotInitialized);t._klarnaPayments.authorize({payment_method_category:e},a,(function(e){return e.approved?n(e):e.show_form?r(new uu):void r(new Te)}))}))},e}();const ll=dl,pl=function(){function e(e){this._scriptLoader=e}return e.prototype.load=function(){return this._scriptLoader.loadScript("https://x.klarnacdn.net/kp/lib/v1/api.js").then((function(){return window.Klarna.Payments}))},e}();var hl=function(){function e(e){this._requestSender=e}return e.prototype.updateClientToken=function(e,t){var n=void 0===t?{}:t,r=n.timeout,i=n.params,o="/api/storefront/payments/"+e;return this._requestSender.get(o,{timeout:r,headers:(0,s.__assign)({Accept:w.JsonV1,"X-API-INTERNAL":V},C),params:i})},e}();const ml=hl,_l=function(){function e(e,t,n,r,i){this._store=e,this._orderActionCreator=t,this._paymentActionCreator=n,this._masterpassScriptLoader=r,this._locale=i}return e.prototype.initialize=function(e){var t=this,n=e.methodId;if(this._paymentMethod=this._store.getState().paymentMethods.getPaymentMethod(n),!this._paymentMethod)throw new m(h.MissingPaymentMethod);var r={useMasterpassSrc:this._paymentMethod.initializationData.isMasterpassSrcEnabled,language:Jo(this._locale),testMode:this._paymentMethod.config.testMode,checkoutId:this._paymentMethod.initializationData.checkoutId};return this._masterpassScriptLoader.load(r).then((function(n){if(t._masterpassClient=n,!e.masterpass)throw new ae('Unable to initialize payment because "options.masterpass" argument is not provided.');var r=e.masterpass.walletButton&&document.getElementById(e.masterpass.walletButton);return r&&(t._walletButton=r,t._walletButton.addEventListener("click",t._handleWalletButtonClick)),t._store.getState()}))},e.prototype.deinitialize=function(){return this._paymentMethod=void 0,this._walletButton&&this._walletButton.removeEventListener("click",this._handleWalletButtonClick),this._walletButton=void 0,this._masterpassClient=void 0,Promise.resolve(this._store.getState())},e.prototype.execute=function(e,t){var n=this,r=e.payment,i={useStoreCredit:e.useStoreCredit};if(!r)throw new ae('Unable to submit payment because "payload.payment" argument is not provided.');if(!this._paymentMethod||!this._paymentMethod.initializationData||!this._paymentMethod.initializationData.gateway)throw new m(h.MissingPaymentMethod);var o=this._paymentMethod.initializationData.paymentData;if(!o)throw new ae('Unable to proceed because "paymentMethod.initializationData.paymentData" argument is not provided.');return this._store.dispatch(this._orderActionCreator.submitOrder(i,t)).then((function(){return n._store.dispatch(n._paymentActionCreator.submitPayment((0,s.__assign)((0,s.__assign)({},r),{paymentData:o})))}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype._createMasterpassPayload=function(){var e=this._store.getState(),t=e.checkout.getCheckout(),n=e.config.getStoreConfig();if(!t)throw new m(h.MissingCheckout);if(!n)throw new m(h.MissingCheckoutConfig);if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new m(h.MissingPaymentMethod);return{checkoutId:this._paymentMethod.initializationData.checkoutId,allowedCardTypes:this._paymentMethod.initializationData.allowedCardTypes,amount:t.subtotal.toFixed(2),currency:n.currency.code,cartId:t.cart.id,callbackUrl:Wo("checkout")}},e.prototype._handleWalletButtonClick=function(e){if(e.preventDefault(),this._masterpassClient){var t=this._createMasterpassPayload();this._masterpassClient.checkout(t)}},(0,s.__decorate)([yn],e.prototype,"_handleWalletButtonClick",null),e}();var yl;!function(e){e.creditcard="credit_card"}(yl||(yl={}));var fl=["klarnapaylater","klarnasliceit"],gl=function(){function e(e,t,n,r,i){this._hostedFormFactory=e,this._store=t,this._mollieScriptLoader=n,this._orderActionCreator=r,this._paymentActionCreator=i}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d,l,p,_,y,f,g=this;return(0,s.__generator)(this,(function(v){switch(v.label){case 0:if(t=e.mollie,n=e.methodId,r=e.gatewayId,!t)throw new ae('Unable to initialize payment because "options.mollie" argument is not provided.');if(!n||!r)throw new ae('Unable to initialize payment because "methodId" and/or "gatewayId" argument is not provided.');if(i=document.querySelectorAll(".mollie-components-controller"),(0,Z.each)(i,(function(e){return e.remove()})),o=this._store.getState(),!(a=o.config.getStoreConfig()))throw new m(h.MissingCheckoutConfig);if(this._initializeOptions=t,c=o.paymentMethods,u=c.getPaymentMethodOrThrow(n,r),d=u.config,l=d.merchantId,p=d.testMode,_=u.initializationData.locale,this._locale=_,!l)throw new ae('Unable to initialize payment because "merchantId" argument is not provided.');return this.isCreditCard(n)&&t.form&&this.shouldShowTSVHostedForm(n,r)?(y=this,[4,this._mountCardVerificationfields(t.form)]):[3,2];case 1:return y._hostedForm=v.sent(),[3,4];case 2:return this.isCreditCard(n)?(f=this,[4,this._loadMollieJs(l,a.storeProfile.storeLanguage,p)]):[3,4];case 3:f._mollieClient=v.sent(),this._mountElements(),v.label=4;case 4:return this._unsubscribe=this._store.subscribe((function(i){return(0,s.__awaiter)(g,void 0,void 0,(function(){var o;return(0,s.__generator)(this,(function(a){return i.paymentStrategies.isInitialized({methodId:e.methodId,gatewayId:e.gatewayId})&&((o=document.getElementById(r+"-"+n+"-paragraph"))&&o.remove(),t.disableButton(!1),this._loadPaymentMethodsAllowed(t,n,r,i)),[2]}))}))}),(function(e){var t=e.checkout.getCheckout();return t&&t.outstandingBalance}),(function(e){var t=e.checkout.getCheckout();return t&&t.coupons})),this._loadPaymentMethodsAllowed(t,n,r,o),[2,Promise.resolve(this._store.getState())]}}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),i=null==n?void 0:n.paymentData,!n||!n.gatewayId||!i)throw new cu(["payment","gatewayId","paymentData"]);a.label=1;case 1:return a.trys.push([1,8,,9]),[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 2:return a.sent(),Gn(i)?[4,this.executeWithVaulted(n)]:[3,4];case 3:return[2,a.sent()];case 4:return this.isCreditCard(n.methodId)?[4,this.executeWithCC(n)]:[3,6];case 5:return[2,a.sent()];case 6:return[4,this.executeWithAPM(n)];case 7:return[2,a.sent()];case 8:return o=a.sent(),[2,this._processAdditionalAction(o)];case 9:return[2]}}))}))},e.prototype.finalize=function(){return Promise.resolve(this._store.getState())},e.prototype.deinitialize=function(e){if(this._unsubscribe&&this._unsubscribe(),this._hostedForm&&this._hostedForm.detach(),e&&e.methodId&&e.gatewayId&&!this._hostedForm){var 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(this._store.getState())},e.prototype.executeWithCC=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c;return(0,s.__generator)(this,(function(u){switch(u.label){case 0:return t=e.paymentData,n=t.shouldSaveInstrument,r=t.shouldSetAsDefaultInstrument,[4,this._getMollieClient().createToken()];case 1:return i=u.sent(),o=i.token,(a=i.error)?[2,Promise.reject(a)]:(c={credit_card_token:{token:o},vault_payment_instrument:n,set_as_default_stored_instrument:r,browser_info:Jd(),shopper_locale:this._getShopperLocale()},[2,this._store.dispatch(this._paymentActionCreator.submitPayment((0,s.__assign)((0,s.__assign)({},e),{paymentData:{formattedPayload:c}})))])}}))}))},e.prototype.executeWithVaulted=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:if(!this._isHostedPaymentFormEnabled(e.methodId,e.gatewayId))return[3,3];if(!(t=this._hostedForm))throw new Pn(bn.PaymentNotInitialized);return[4,t.validate()];case 1:return n.sent(),[4,t.submit(e)];case 2:return n.sent(),[2,this._store.dispatch(this._orderActionCreator.loadCurrentOrder())];case 3:return[2,this._store.dispatch(this._paymentActionCreator.submitPayment(e))]}}))}))},e.prototype.executeWithAPM=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){return t=e.paymentData,n=t&&"issuer"in t?t.issuer:"",[2,this._store.dispatch(this._paymentActionCreator.submitPayment((0,s.__assign)((0,s.__assign)({},e),{paymentData:(0,s.__assign)((0,s.__assign)({},t),{formattedPayload:{issuer:n,shopper_locale:this._getShopperLocale()}})})))]}))}))},e.prototype.isCreditCard=function(e){return e===yl.creditcard},e.prototype.shouldShowTSVHostedForm=function(e,t){return this._isHostedPaymentFormEnabled(e,t)&&this._isHostedFieldAvailable()},e.prototype._mountCardVerificationfields=function(e){var t=this;return new Promise((function(n,r){return(0,s.__awaiter)(t,void 0,void 0,(function(){var t,i,o,a,c;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(s.trys.push([0,2,,3]),t=this._store.getState().config,!(i=null===(c=t.getStoreConfig())||void 0===c?void 0:c.paymentSettings.bigpayBaseUrl))throw new m(h.MissingCheckoutConfig);return[4,(o=this._hostedFormFactory.create(i,e)).attach()];case 1:return s.sent(),n(o),[3,3];case 2:return a=s.sent(),r(a),[3,3];case 3:return[2]}}))}))}))},e.prototype._isHostedPaymentFormEnabled=function(e,t){return!0===(0,this._store.getState().paymentMethods.getPaymentMethodOrThrow)(e,t).config.isHostedFormEnabled},e.prototype._isHostedFieldAvailable=function(){var e;return!!(null===(e=this._getInitializeOptions().form)||void 0===e?void 0:e.fields)},e.prototype._processAdditionalAction=function(e){if(!(e instanceof x&&(0,Z.some)(e.body.errors,{code:"additional_action_required"})))return Promise.reject(e);var t=e.body.additional_action_required.data.redirect_url;return new Promise((function(){return window.location.replace(t)}))},e.prototype._getInitializeOptions=function(){if(!this._initializeOptions)throw new Pn(bn.PaymentNotInitialized);return this._initializeOptions},e.prototype._loadMollieJs=function(e,t,n){return void 0===n&&(n=!1),this._mollieClient?Promise.resolve(this._mollieClient):this._mollieScriptLoader.load(e,t,n)},e.prototype._getMollieClient=function(){if(!this._mollieClient)throw new Pn(bn.PaymentNotInitialized);return this._mollieClient},e.prototype._getShopperLocale=function(){if(!this._locale)throw new Pn(bn.PaymentNotInitialized);return this._locale},e.prototype._mountElements=function(){var e,t=this,n=this._getInitializeOptions(),r=n.containerId,i=n.cardNumberId,o=n.cardCvcId,a=n.cardExpiryId,s=n.cardHolderId,c=n.styles;r&&(e=document.getElementById(r)),setTimeout((function(){if(!r||"none"!==(null==e?void 0:e.style.display)){var n=t._getMollieClient();t._cardHolderElement=n.createComponent("cardHolder",{styles:c}),t._cardHolderElement.mount("#"+s),t._cardNumberElement=n.createComponent("cardNumber",{styles:c}),t._cardNumberElement.mount("#"+i),t._verificationCodeElement=n.createComponent("verificationCode",{styles:c}),t._verificationCodeElement.mount("#"+o),t._expiryDateElement=n.createComponent("expiryDate",{styles:c}),t._expiryDateElement.mount("#"+a)}}),0)},e.prototype._loadPaymentMethodsAllowed=function(e,t,n,r){if(fl.includes(t)){var i=r.cart.getCartOrThrow().lineItems.digitalItems;if(i&&i.length>0){var o=this._getInitializeOptions().containerId;if(o){var a=document.getElementById(o);if(a){var s=document.createElement("p");s.setAttribute("id",n+"-"+t+"-paragraph"),e.unsupportedMethodMessage&&(s.innerText=e.unsupportedMethodMessage,a.appendChild(s),e.disableButton(!0))}}}}},e}();const vl=gl;var wl=function(){function e(e,t){void 0===t&&(t=window),this._scriptLoader=e,this._window=t}return e.prototype._isMollieWindow=function(e){return!!e.Mollie},e.prototype.load=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._scriptLoader.loadScript("https://js.mollie.com/v1/mollie.js")];case 1:if(r.sent(),!this._isMollieWindow(this._window))throw new gi;return[2,this._window.Mollie(e,{locale:t,testmode:n})]}}))}))},e}();const Cl=wl;var Sl="moneris-payment-iframe",Il=function(){function e(e,t,n,r,i){this._hostedFormFactory=e,this._store=t,this._orderActionCreator=n,this._paymentActionCreator=r,this._storeCreditActionCreator=i}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=this._store.getState(),n=e.moneris,!(r=e.methodId))throw new ae('Unable to initialize payment because "methodId" argument is not provided.');if(!n)throw new ae('Unable to initialize payment because "options.moneris" argument is not provided.');if(this._initializeOptions=n,i=t.paymentMethods.getPaymentMethodOrThrow(r),o=i.config,!(null==(a=i.initializationData)?void 0:a.profileId))throw new m(h.MissingPaymentMethod);return n.form&&this._shouldShowTSVHostedForm(r)?(c=this,[4,this._mountCardVerificationfields(n.form)]):[3,2];case 1:c._hostedForm=s.sent(),s.label=2;case 2:return this._iframe||(this._iframe=this._createIframe(n.containerId,a,!!o.testMode)),[2,Promise.resolve(this._store.getState())]}}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!n)throw new cu(["payment"]);return void 0===(i=this._store.getState().checkout.getCheckoutOrThrow().isStoreCreditApplied)?[3,2]:[4,this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(i))];case 1:o.sent(),o.label=2;case 2:return[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 3:return o.sent(),n.paymentData&&Gn(n.paymentData)?[2,this._executeWithVaulted(n)]:[2,this._executeWithCC(n)]}}))}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype.deinitialize=function(){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(this._store.getState())},e.prototype._executeWithCC=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return t=this._store.getState().paymentMethods.getPaymentMethodOrThrow,n=t(e.methodId),r=n.config.testMode,i=e.paymentData||{},o=Vu(i)?i:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1},a=o.shouldSaveInstrument,c=o.shouldSetAsDefaultInstrument,[4,new Promise((function(e,t){if(!d._iframe)throw new Pn(bn.PaymentNotInitialized);var n=d._iframe.contentWindow;null==n||n.postMessage("tokenize",d._monerisURL(!!r)),d._windowEventListener=function(n){if("string"==typeof n.data)try{e(d._handleMonerisResponse(n))}catch(e){t(e)}},window.addEventListener("message",d._windowEventListener)}))];case 1:return void 0!==(u=s.sent())?[2,this._store.dispatch(this._paymentActionCreator.submitPayment({methodId:e.methodId,paymentData:{nonce:u,shouldSaveInstrument:a,shouldSetAsDefaultInstrument:c}}))]:[2,this._store.getState()]}}))}))},e.prototype._executeWithVaulted=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:if(!this._hostedForm)return[3,3];if(!(t=this._hostedForm))throw new Pn(bn.PaymentNotInitialized);return[4,t.validate()];case 1:return n.sent(),[4,t.submit(e)];case 2:return n.sent(),[2,this._store.dispatch(this._orderActionCreator.loadCurrentOrder())];case 3:return[2,this._store.dispatch(this._paymentActionCreator.submitPayment(e))]}}))}))},e.prototype._shouldShowTSVHostedForm=function(e){return this._isHostedPaymentFormEnabled(e)&&this._isHostedFieldAvailable()},e.prototype._isHostedPaymentFormEnabled=function(e){var t=(0,this._store.getState().paymentMethods.getPaymentMethodOrThrow)(e);return Boolean(t.config.isHostedFormEnabled)},e.prototype._isHostedFieldAvailable=function(){var e,t=this._getInitializeOptions(),n=(0,Z.omitBy)(null===(e=t.form)||void 0===e?void 0:e.fields,Z.isEmpty);return!(0,Z.isEmpty)(n)},e.prototype._getInitializeOptions=function(){if(!this._initializeOptions)throw new Pn(bn.PaymentNotInitialized);return this._initializeOptions},e.prototype._mountCardVerificationfields=function(e){var t;return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(n=this._store.getState().config,!(r=null===(t=n.getStoreConfig())||void 0===t?void 0:t.paymentSettings.bigpayBaseUrl))throw new m(h.MissingCheckoutConfig);return[4,(i=this._hostedFormFactory.create(r,e)).attach()];case 1:return o.sent(),[2,i]}}))}))},e.prototype._createIframe=function(e,t,n,r){var i=document.getElementById(e);if(!i)throw new ae("Unable to create iframe without valid container ID.");var o=document.createElement("iframe"),a={id:t.profileId,pmmsg:!0,display_labels:1,enable_exp:1,enable_cvd:1,css_body:(null==r?void 0:r.cssBody)||"font-family: Arial, Helvetica,sans-serif;background: transparent;",css_textbox:(null==r?void 0:r.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==r?void 0:r.cssTextboxCardNumber)||"width: 240px;",css_textbox_exp:(null==r?void 0:r.cssTextboxExpiryDate)||"margin-bottom: 0;width: calc(30% - 12px);",css_textbox_cvd:(null==r?void 0:r.cssTextboxCVV)||"margin-bottom: 0;width: calc(30% - 12px);",css_input_label:(null==r?void 0:r.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=(0,Z.map)(a,(function(e,t){return t+"="+e})).join("&");return o.width="100%",o.height="100%",o.name=Sl,o.id=Sl,o.style.border="none",o.src=this._monerisURL(n)+"?"+s,i.appendChild(o),o},e.prototype._handleMonerisResponse=function(e){var t=JSON.parse(e.data);if("001"!==t.responseCode[0])throw new Error(t.errorMessage);return t.dataKey},e.prototype._monerisURL=function(e){return"https://"+(e?"esqa":"www3")+".moneris.com/HPPtoken/index.php"},e}();const bl=Il;var Pl,El;function Al(e){var t;return!!(null===(t=e.initializationData)||void 0===t?void 0:t.widgetConfig)}!function(e){e.FORM_POST="FormPost",e.WAIT_FOR_CUSTOMER="WaitForCustomer"}(Pl||(Pl={})),function(e){e.InvalidCart="invalid_cart"}(El||(El={}));const Ol=function(e){function t(t,n){var r=e.call(this,function(e,t){return e===El.InvalidCart?"Cart price is different to "+t+" plan amount.":"There was an error while processing your payment. Please try again or contact us."}(t,n))||this;return r.name="OpyError",r.type="opy_error",r.subtype=t,r}return(0,s.__extends)(t,e),t}(p);var kl=function(){function e(e,t,n,r,i,o){this._store=e,this._orderActionCreator=t,this._paymentMethodActionCreator=n,this._storefrontPaymentRequestSender=r,this._paymentActionCreator=i,this._scriptLoader=o}return e.prototype.initialize=function(e){var t;return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:return(null===(t=null==e?void 0:e.opy)||void 0===t?void 0:t.containerId)?(n=e.methodId,r=e.opy.containerId,(i=this._store.getState().paymentMethods.getPaymentMethod(n))&&Al(i)?(o=i.initializationData.widgetConfig,[4,this._installWidget(r,o)]):[3,2]):[3,2];case 1:a.sent(),a.label=2;case 2:return[2,Promise.resolve(this._store.getState())]}}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d,l,p,_,y,f,g;return(0,s.__generator)(this,(function(v){switch(v.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!n)throw new cu(["payment"]);return i=n.methodId,[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(i,t))];case 1:if(o=v.sent().paymentMethods.getPaymentMethodOrThrow,!Al(a=o(i)))throw new m(h.MissingPaymentMethod);if(c=a.clientToken,!(u=a.initializationData.nextAction))throw d=a.config.displayName,l=void 0===d?"Openpay":d,new Ol(El.InvalidCart,l);if(!c)throw new m(h.MissingPaymentToken);return[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 2:return v.sent(),[4,this._storefrontPaymentRequestSender.saveExternalId(i,c)];case 3:v.sent(),v.label=4;case 4:return v.trys.push([4,6,,7]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment({methodId:i,paymentData:{nonce:c}}))];case 5:return[2,v.sent()];case 6:if((p=v.sent())instanceof x&&"additional_action_required"===p.body.status){if(u.type===Pl.FORM_POST)return _=u.formPost,y=_.formPostUrl,f=_.formFields,g=new URL(y.replace(/\/$/,"")),f.forEach((function(e){var t=e.fieldName,n=e.fieldValue;g.searchParams.append(t,n)})),[2,new Promise((function(){return window.location.assign(decodeURI(g.href))}))];throw new bo("Unsupported action type: "+u.type)}throw p;case 7:return[2]}}))}))},e.prototype.finalize=function(e){return Promise.reject(new Hc)},e.prototype.deinitialize=function(e){return Promise.resolve(this._store.getState())},e.prototype._installWidget=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:if(!(n=document.getElementById(e)))return[3,5];r.label=1;case 1:return r.trys.push([1,3,,4]),[4,this._scriptLoader.loadOpyWidget(t.region)];case 2:return r.sent().Config(t),[3,4];case 3:return r.sent(),[2];case 4:n.appendChild(document.createElement("opy-learn-more-button")),r.label=5;case 5:return[2]}}))}))},e}();const Tl=kl;var Ml;!function(e){e.AU="AU",e.UK="UK",e.US="US"}(Ml||(Ml={}));var Dl="https://widgets.openpay.com.au/lib/openpay-widgets.min.js",Rl={AU:Dl,UK:Dl,US:"https://widgets.opy.com/lib/openpay-widgets.min.js"},zl=function(){function e(e,t){void 0===t&&(t=window),this._scriptLoader=e,this._window=t}return e.prototype.loadOpyWidget=function(e){return void 0===e&&(e=Ml.AU),(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this._scriptLoader.loadScript(Rl[e])];case 1:if(t.sent(),!this._window.OpenpayWidgets)throw new gi;return[2,this._window.OpenpayWidgets]}}))}))},e}();const Nl=zl;var Ll=function(e){function t(t,n,r,i,o){var a=e.call(this,t,n,r,i)||this;return a._threeDSecureFlow=o,a}return(0,s.__extends)(t,e),t.prototype.initialize=function(t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return[4,e.prototype.initialize.call(this,t)];case 1:return i.sent(),n=this._store.getState().paymentMethods.getPaymentMethodOrThrow,(r=n(t.methodId)).config.is3dsEnabled?[4,this._threeDSecureFlow.prepare(r)]:[3,3];case 2:i.sent(),i.label=3;case 3:return[2,this._store.getState()]}}))}))},t.prototype.execute=function(t,n){var r=t.payment,i=(void 0===r?{}:r).methodId,o=void 0===i?"":i,a=this._store.getState(),c=a.payment.getPaymentStatus,u=a.paymentMethods.getPaymentMethodOrThrow;return c()===Iu?this._store.dispatch(this._orderActionCreator.submitOrder((0,s.__assign)((0,s.__assign)({},t),{payment:{methodId:o}}),n)):u(o).config.is3dsEnabled?this._threeDSecureFlow.start(e.prototype.execute.bind(this),t,n,this._hostedForm):e.prototype.execute.call(this,t,n)},t}(wu);const Fl=Ll,Bl=function(){function e(e,t,n,r){void 0===r&&(r=window),this._store=e,this._orderActionCreator=t,this._scriptLoader=n,this._window=r,this._useRedirectFlow=!1}return e.prototype.initialize=function(e){var t=this,n=this._store.getState();return this._paymentMethod=n.paymentMethods.getPaymentMethod(e.methodId),this._useRedirectFlow=!0===(e.paypalexpress&&e.paypalexpress.useRedirectFlow),this._isInContextEnabled()?this._scriptLoader.loadPaypal().then((function(e){if(t._paypalSdk=e,!t._paymentMethod||!t._paymentMethod.config.merchantId)throw new m(h.MissingPaymentMethod);t._paypalSdk.checkout.setup(t._paymentMethod.config.merchantId,{button:"paypal-button",environment:t._paymentMethod.config.testMode?"sandbox":"production"})})).then((function(){return t._store.getState()})):Promise.resolve(this._store.getState())},e.prototype.deinitialize=function(){return this._isInContextEnabled()&&this._paypalSdk&&(this._paypalSdk.checkout.closeFlow(),this._paypalSdk=void 0),Promise.resolve(this._store.getState())},e.prototype.execute=function(e,t){var n=this,r=this._paypalSdk;if(this._isAcknowledgedOrFinalized())return this._store.dispatch(this._orderActionCreator.submitOrder(e,t));if(!this._isInContextEnabled()||this._useRedirectFlow)return this._store.dispatch(this._orderActionCreator.submitOrder(e,t)).then((function(e){var t=e.payment.getPaymentRedirectUrl();return t&&(n._window.top.location.href=t),new Promise(Z.noop)}));if(!r)throw new Pn(bn.PaymentNotInitialized);return r.checkout.initXO(),this._store.dispatch(this._orderActionCreator.submitOrder(e,t)).then((function(e){var t=e.payment.getPaymentRedirectUrl();return t&&r.checkout.startFlow(t),new Promise(Z.noop)})).catch((function(e){return r.checkout.closeFlow(),Promise.reject(e)}))},e.prototype.finalize=function(e){var t=this._store.getState().order.getOrder();return t&&this._isAcknowledgedOrFinalized()?this._store.dispatch(this._orderActionCreator.finalizeOrder(t.orderId,e)):Promise.reject(new Hc)},e.prototype._isAcknowledgedOrFinalized=function(){var e=this._store.getState();return e.payment.getPaymentStatus()===Iu||e.payment.getPaymentStatus()===bu},e.prototype._isInContextEnabled=function(){return!(!this._paymentMethod||!this._paymentMethod.config.merchantId)},e}();var Ul=function(){function e(e){this._scriptLoader=e,this._window=window}return e.prototype.loadPaypal=function(e){return void 0===e&&(e=""),(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return t="//www.paypalobjects.com/api/checkout.min.js",n={async:!0,attributes:{"data-merchant-id":e}},e?[4,this._scriptLoader.loadScript(t,n)]:[3,2];case 1:return r.sent(),[3,4];case 2:return[4,this._scriptLoader.loadScript(t)];case 3:r.sent(),r.label=4;case 4:if(!this._window.paypal)throw new gi;return[2,this._window.paypal]}}))}))},e}();const xl=Ul,ql=require("query-string");var Vl,Gl="redirecting",Hl=function(){function e(){this._isRedirecting=this.currentUrlHasRedirectingParam()}return e.prototype.isRedirecting=function(){return this._isRedirecting},e.prototype.setRedirecting=function(e){e?this.setRedirectingParamOnUrl():this.removeRedirectingParamFromUrl(),this._isRedirecting=e},e.prototype.currentUrlHasRedirectingParam=function(){return Gl in this.getCurrentUrl().query},e.prototype.getCurrentUrl=function(){return(0,ql.parseUrl)(window.location.href)},e.prototype.replaceCurrentUrl=function(e){window.history.replaceState(null,"",e)},e.prototype.setRedirectingParamOnUrl=function(){var e;if(!this.currentUrlHasRedirectingParam()){var t=this.getCurrentUrl(),n=(0,s.__assign)((0,s.__assign)({},t),{query:(0,s.__assign)((0,s.__assign)({},t.query),(e={},e[Gl]="true",e))});this.replaceCurrentUrl((0,ql.stringifyUrl)(n))}},e.prototype.removeRedirectingParamFromUrl=function(){this.currentUrlHasRedirectingParam()&&this.replaceCurrentUrl((0,ql.exclude)(window.location.href,[Gl]))},e}(),Yl=(0,Z.overSome)([function(e){return"continue"===(0,Z.get)(e,"type")&&"redirect"===(0,Z.get)(e,"code")&&(t=(0,Z.get)(e,"parameters"),n=(0,Z.get)(t,"form_fields"),(0,Z.isString)((0,Z.get)(t,"url"))&&((0,Z.isUndefined)(n)||(0,Z.isObject)(n)));var t,n},function(e){return"continue"===(0,Z.get)(e,"type")&&"resubmit_with_human_verification"===(0,Z.get)(e,"code")&&(t=(0,Z.get)(e,"parameters"),n=(0,Z.get)(t,"available_methods"),(0,Z.isArray)(n));var t,n}]),jl=function(){function e(e,t){this._formPoster=e,this._humanVerificationHandler=t}return e.prototype.handle=function(e,t){switch(e.code){case"redirect":return function(e,t){var n=e.url,r=e.form_fields,i=new Hl;return i.isRedirecting()?(i.setRedirecting(!1),Promise.reject(new uu)):(i.setRedirecting(!0),r?t.postForm(n,r):window.location.assign(n),new Promise(Z.noop))}(e.parameters,this._formPoster);case"resubmit_with_human_verification":return function(e,t,n){var r=e.available_methods;return(0,s.__awaiter)(void 0,void 0,void 0,(function(){var e,i,o,a;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!n)throw new Error("PPSDK human verification callback function is missing.");if(!t)throw new Error("PPSDK human verification handler is missing.");if(0===r.length)throw Error("Human verification method is missing.");return e=r[0],i=e.id,o=e.parameters,[4,t.handle(i,o.key)];case 1:return a=s.sent(),[2,n(a)]}}))}))}(e.parameters,this._humanVerificationHandler,null==t?void 0:t.humanVerification)}},e}(),Wl=function(){function e(e){this._continueHandler=e}return e.prototype.handle=function(e,t){var n=e.body;return function(e){return"success"===(0,Z.get)(e,"type")}(n)?Promise.resolve():function(e){return Yl(e)}(n)?this._continueHandler.handle(n,null==t?void 0:t.continue):function(e){return"failure"===(0,Z.get)(e.body,"type")&&(0,Z.isString)((0,Z.get)(e.body,"code"))}(e)?function(e){return Promise.reject(new x((t=e,(0,s.__assign)((0,s.__assign)({},t),{body:{errors:[{code:t.body.code}]}}))));var t}(e):(function(e){(0,Z.get)(e.body,"type")}(e),function(e){return Promise.reject(new x(e))}(e))},e}(),Kl=function(e,t){return new Wl(new jl(e,t))},Jl="completed-payments",Zl=function(){function e(e){this._browserStorage=e}return e.prototype.isCompleted=function(e){return this.getCompletedPayments().indexOf(e)>=0},e.prototype.setCompleted=function(e){var t=this.getCompletedPayments();t.push(e),this.setCompletedPayments(t)},e.prototype.getCompletedPayments=function(){return this._browserStorage.getItem(Jl)||[]},e.prototype.setCompletedPayments=function(e){this._browserStorage.setItem(Jl,e)},e}(),Ql=function(){function e(e,t,n,r,i){this._store=e,this._orderActionCreator=t,this._subStrategyRegistry=n,this._paymentResumer=r,this._completedPayments=new Zl(i)}return e.prototype.execute=function(e,t){var n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u;return(0,s.__generator)(this,(function(d){switch(d.label){case 0:if(r=this._store.getState().config.getStoreConfigOrThrow().paymentSettings.bigpayBaseUrl,!(null==t?void 0:t.methodId))throw new ae('Unable to submit payment because "options.methodId" argument is not provided.');if(i=t.methodId,o=e.payment,a=(0,s.__rest)(e,["payment"]),!(c=this._subStrategy))throw new Pn(bn.PaymentNotInitialized);return[4,this._store.dispatch(this._orderActionCreator.submitOrder(a,t))];case 1:if(d.sent(),!(u=null===(n=this._store.getState().order.getOrderMeta())||void 0===n?void 0:n.token))throw new m(h.MissingOrder);return[4,c.execute({methodId:i,payment:o,bigpayBaseUrl:r,token:u})];case 2:return d.sent(),[2,this._store.getState()]}}))}))},e.prototype.finalize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o=this;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:if((t=this._store.getState().order.getOrderOrThrow()).isComplete)return[2,this._store.getState()];if(n=this._store.getState().config.getStoreConfigOrThrow().paymentSettings.bigpayBaseUrl,!(null==e?void 0:e.methodId))throw new ae('Unable to submit payment because "options.methodId" argument is not provided.');if(!(r=this._store.getState().order.getPaymentId(e.methodId))||!t||this._completedPayments.isCompleted(r))throw new Hc;return i=t.orderId,[4,this._paymentResumer.resume({paymentId:r,bigpayBaseUrl:n,orderId:i}).catch((function(e){throw o._completedPayments.setCompleted(r),e}))];case 1:return a.sent(),[2,this._store.getState()]}}))}))},e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:if(!(null==e?void 0:e.methodId))throw new ae('Unable to submit payment because "options.methodId" argument is not provided.');if(!(t=function(e,t){var n=e.getState().paymentMethods.getPaymentMethod(t);if(n&&Xc(n))return n}(this._store,e.methodId)))throw new Pn(bn.PaymentNotInitialized);if(this._subStrategy=this._subStrategyRegistry.getByMethod(t),!this._subStrategy)throw new Pn(bn.PaymentNotInitialized);return[4,this._subStrategy.initialize(e)];case 1:return n.sent(),[2,this._store.getState()]}}))}))},e.prototype.deinitialize=function(e){var t;return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){return null===(t=this._subStrategy)||void 0===t||t.deinitialize(),[2,this._store.getState()]}))}))},e}();!function(e){e.CARD="card_ui",e.NONE="none",e.UNSUPPORTED="unsupported"}(Vl||(Vl={}));var Xl=(0,Z.cond)([[function(e){return"card_ui"===e.type},(0,Z.constant)(Vl.CARD)],[function(e){return"none"===e.type},(0,Z.constant)(Vl.NONE)],[Z.stubTrue,(0,Z.constant)(Vl.UNSUPPORTED)]]),$l=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return(0,s.__extends)(t,e),t.prototype.getByMethod=function(e){var t=Xl(e.initializationStrategy);return this.get(t)},t}(ce),ep=function(){function e(e,t,n,r){this._store=e,this._orderActionCreator=t,this._hostedFormFactory=n,this._ppsdkStepHandler=r}return e.prototype.execute=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c=this;return(0,s.__generator)(this,(function(u){switch(u.label){case 0:if(!(t=this._hostedForm))throw new Pn(bn.PaymentNotInitialized);if(n=e.additionalAction,!(r=e.payment)||!r.methodId)throw new cu(["payment.methodId"]);return[4,t.validate()];case 1:return u.sent(),[4,t.submit(r,n)];case 2:return i=u.sent().payload,o=i.response,a=function(t){return(0,s.__awaiter)(c,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){return[2,this.execute((0,s.__assign)({additionalAction:t},e))]}))}))},[4,this._ppsdkStepHandler.handle(o,{continue:{humanVerification:a}})];case 3:return u.sent(),[4,this._store.dispatch(this._orderActionCreator.loadCurrentOrder())];case 4:return u.sent(),[2]}}))}))},e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e&&e.creditCard&&e.creditCard.form,n=this._store.getState().config,r=(n.getStoreConfig()||{}).paymentSettings,i=(void 0===r?{}:r).bigpayBaseUrl,o=void 0===i?"":i,!t)throw new ae;return[4,(a=t&&this._hostedFormFactory.create(o,t)).attach()];case 1:return s.sent(),this._hostedForm=a,[2]}}))}))},e.prototype.deinitialize=function(){this._hostedForm&&this._hostedForm.detach()},e}(),tp=function(){function e(e,t){this._requestSender=e,this._stepHandler=t}return e.prototype.execute=function(e){var t=this,n=e.methodId,r=e.bigpayBaseUrl,i={credentials:!1,body:{payment_method_id:n},headers:{authorization:e.token,"X-XSRF-TOKEN":null}};return this._requestSender.post(r+"/payments",i).then((function(e){return t._stepHandler.handle(e)}))},e.prototype.initialize=function(){return Promise.resolve()},e.prototype.deinitialize=function(){},e}(),np=function(e,t,n,r,i){var o=new $l;return o.register(Vl.CARD,(function(){return new ep(e,t,i,r)})),o.register(Vl.NONE,(function(){return new tp(n,r)})),o.register(Vl.UNSUPPORTED,(function(){})),o},rp=function(){function e(e,t){this._requestSender=e,this._stepHandler=t}return e.prototype.resume=function(e){var t=e.paymentId,n=e.bigpayBaseUrl,r=e.orderId;return(0,s.__awaiter)(this,void 0,void 0,(function(){var e,i,o=this;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:return[4,this._getToken(r).catch((function(){throw new Hc}))];case 1:return e=a.sent(),i={credentials:!1,headers:{authorization:e,"X-XSRF-TOKEN":null}},[2,this._requestSender.get(n+"/payments/"+t,i).then((function(e){return o._stepHandler.handle(e)}))]}}))}))},e.prototype._getToken=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){return t={params:{order_id:e}},[2,this._requestSender.get("/api/storefront/payments/auth-token",t).then((function(e){return e.body.auth_token}))]}))}))},e}(),ip=function(){function e(e,t,n,r,i,o,a){this._store=e,this._orderActionCreator=t,this._paymentActionCreator=n,this._paymentMethodActionCreator=r,this._storeCreditActionCreator=i,this._remoteCheckoutActionCreator=o,this._storefrontPaymentRequestSender=a}return e.prototype.initialize=function(){return Promise.resolve(this._store.getState())},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d,l,p,_,y;return(0,s.__generator)(this,(function(f){switch(f.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!n)throw new cu(["payment"]);return i=n.methodId,[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(i,t))];case 1:if(o=f.sent().paymentMethods.getPaymentMethodOrThrow,a=o(i),c=a.clientToken,u=a.initializationData,d=(void 0===u?{}:u).redirectUrl,!c||!d)throw new m(h.MissingPaymentMethod);if(!(l=JSON.parse(c).id))throw new m(h.MissingPaymentToken);return p={methodId:i,paymentData:{nonce:l}},_=this._store.getState().checkout.getCheckoutOrThrow().isStoreCreditApplied,[4,this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(_))];case 2:return f.sent(),[4,this._store.dispatch(this._remoteCheckoutActionCreator.initializePayment(i,{useStoreCredit:_}))];case 3:return f.sent(),[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 4:return f.sent(),[4,this._prepareForReferredRegistration(i,l)];case 5:f.sent(),f.label=6;case 6:return f.trys.push([6,8,,9]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment(p))];case 7:return[2,f.sent()];case 8:if((y=f.sent())instanceof x&&"additional_action_required"===y.body.status)return window.location.replace(d),[2,new Promise(Z.noop)];throw y;case 9:return[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype.deinitialize=function(){return Promise.resolve(this._store.getState())},e.prototype._prepareForReferredRegistration=function(e,t){return this._storefrontPaymentRequestSender.saveExternalId(e,t)},e}();const op=ip,ap=function(e){function t(t,n,r,i,o){var a=e.call(this,t,n,r,i)||this;return a._formPoster=o,a}return(0,s.__extends)(t,e),t.prototype.execute=function(t,n){var r=this,i=t.payment;if(!i)throw new Pn(bn.PaymentNotInitialized);var o=i.paymentData;if(!o)throw new m(h.MissingPayment);if(this._isThreeDSTwoExperimentOn()){var a=(0,s.__assign)((0,s.__assign)({},o),{browser_info:Jd()});t.payment&&(t.payment.paymentData=a)}return e.prototype.execute.call(this,t,n).catch((function(e){return e instanceof x&&(0,Z.some)(e.body.errors,{code:"three_d_secure_required"})?new Promise((function(){var t;t=r._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},r._formPoster.postForm(e.body.three_ds_result.acs_url,t,void 0,"_top")})):Promise.reject(e)}))},t.prototype.finalize=function(t){var n=this._store.getState(),r=n.order.getOrder();return r&&n.payment.getPaymentStatus()===bu?this._store.dispatch(this._orderActionCreator.finalizeOrder(r.orderId,t)):e.prototype.finalize.call(this,t)},t.prototype._isThreeDSTwoExperimentOn=function(){return!0===this._store.getState().config.getStoreConfigOrThrow().checkoutSettings.features["INT-4994.Opayo_3DS2"]},t}(wu);const sp=function(e){function t(t){var n=e.call(this,t,{message:"The request has timed out or aborted."})||this;return n.name="TimeoutError",n.type="timeout",n}return(0,s.__extends)(t,e),t}(x);var cp,up,dp;!function(e){e.CHARGE="CHARGE",e.STORE="STORE"}(cp||(cp={})),function(e){e.americanExpress="AMERICAN_EXPRESS",e.discover="DISCOVER",e.discoverDiners="DISCOVER_DINERS",e.JCB="JCB",e.masterCard="MASTERCARD",e.unionPay="CHINA_UNIONPAY",e.unknown="OTHER_BRAND",e.visa="VISA",e.squareGift="SQUARE_GIFT_CARD"}(up||(up={})),function(e){e.applePay="APPLEPAY",e.none="NONE"}(dp||(dp={}));var lp=function(){function e(e,t,n,r,i,o,a,s){this._store=e,this._checkoutActionCreator=t,this._orderActionCreator=n,this._paymentActionCreator=r,this._paymentMethodActionCreator=i,this._paymentStrategyActionCreator=o,this._requestSender=a,this._scriptLoader=s}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i=this;return(0,s.__generator)(this,(function(o){if(t=e.methodId,n=e.gatewayId,!(r=e.square))throw new ae('Unable to proceed because "options.square" argument is not provided.');return this._squareOptions=r,this._syncPaymentMethod(t),[2,new Promise((function(e,r){return(0,s.__awaiter)(i,void 0,void 0,(function(){var i,o,a;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:i=this._store.getState(),o=i.paymentMethods.getPaymentMethodOrThrow(t,n).config.testMode,s.label=1;case 1:return s.trys.push([1,3,,4]),[4,this._scriptLoader.load(o)];case 2:return a=s.sent(),this._paymentForm=a(this._getFormOptions({resolve:e,reject:r})),this._getPaymentForm().build(),[3,4];case 3:return s.sent(),r(new gi),[3,4];case 4:return[2]}}))}))})).then((function(){return i._store.getState()}))]}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:if(!(n=e.payment)||!n.methodId)throw new ae('Unable to submit payment because "payload.payment.methodId" argument is not provided.');return this._syncPaymentMethod(n.methodId),[4,this._getNonceInstrument(n.methodId)];case 1:return r=i.sent(),[4,this._store.dispatch(this._orderActionCreator.submitOrder((0,Z.omit)(e,"payment"),t))];case 2:return i.sent(),[4,this._store.dispatch(this._paymentActionCreator.submitPayment((0,s.__assign)((0,s.__assign)({},n),{paymentData:r})))];case 3:return i.sent(),[2,this._store.getState()]}}))}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype.deinitialize=function(){return Promise.resolve(this._store.getState())},e.prototype._syncPaymentMethod=function(e){var t=this._store.getState();if(this._paymentMethod=t.paymentMethods.getPaymentMethodOrThrow(e),!this._paymentMethod.initializationData)throw new m(h.MissingPaymentMethod)},e.prototype._getCountryCode=function(e){switch(e.toUpperCase()){case"NEW ZELAND":return"NZ";case"AUSTRALIA":return"AU";default:return"US"}},e.prototype._getNonceInstrument=function(e){var t=this,n=this._store.getState().paymentMethods.getPaymentMethod(e);if(n){var r=n.initializationData;if(r&&r.paymentData.nonce)return Promise.resolve({nonce:n.initializationData.paymentData.nonce})}return new Promise((function(e,n){t._deferredRequestNonce&&t._deferredRequestNonce.reject(new sp),t._deferredRequestNonce={resolve:e,reject:n},t._getPaymentForm().requestCardNonce()}))},e.prototype._getFormOptions=function(e){var t,n=this;return(0,s.__assign)((0,s.__assign)((0,s.__assign)({},this._getInitializeOptions()),null===(t=this._paymentMethod)||void 0===t?void 0:t.initializationData),{callbacks:{cardNonceResponseReceived:function(e,t,r,i,o){var a=n._getDeferredRequestNonce(),s=n._getInitializeOptions().onError,c=void 0===s?Z.noop:s;if(!t)return c(e),a.reject((0,Z.get)(e,"0",{}));r&&r.digital_wallet_type!==dp.none&&t?n._handleWalletNonceResponse(t,r,i,o):n._is3DSExperimentOn()?n._getPaymentForm().verifyBuyer(t,n._getVerificationDetails(),(function(e,n){if(!(0,Z.isEmpty)(e))return c(e),a.reject((0,Z.get)(e,"0",{}));a.resolve({nonce:JSON.stringify({nonce:t,token:n.token})})})):a.resolve({nonce:t})},createPaymentRequest:this._paymentRequestPayload.bind(this),paymentFormLoaded:function(){e.resolve(),n._setPostalCode()},unsupportedBrowserDetected:function(){return e.reject(new Si)}}})},e.prototype._getInitializeOptions=function(){if(!this._squareOptions)throw new Pn(bn.PaymentNotInitialized);return this._squareOptions},e.prototype._handleWalletNonceResponse=function(e,t,n,r){var i=this._getInitializeOptions(),o=i.onError,a=void 0===o?Z.noop:o,s=i.onPaymentSelect,c=void 0===s?Z.noop:s;e&&this._paymentMethod&&this._paymentInstrumentSelected(this._paymentMethod.id,e,t,n,r).then(c).catch(a)},e.prototype._paymentInstrumentSelected=function(e,t,n,r,i){var o=this;return this._store.dispatch(this._paymentStrategyActionCreator.widgetInteraction((function(){return o._setExternalCheckoutData(t,n,r,i).then((function(){return Promise.all([o._store.dispatch(o._checkoutActionCreator.loadCurrentCheckout()),o._store.dispatch(o._paymentMethodActionCreator.loadPaymentMethod(e))])}))}),{methodId:e}),{queueId:"widgetInteraction"})},e.prototype._paymentRequestPayload=function(){var e=this._store.getState(),t=e.checkout.getCheckout(),n=e.config.getStoreConfigOrThrow();if(!t)throw new m(h.MissingCheckout);return{requestShippingAddress:!0,requestBillingInfo:!0,currencyCode:n.currency.code,countryCode:this._getCountryCode(n.storeProfile.storeCountry),total:{label:n.storeProfile.storeName,amount:String(t.subtotal),pending:!1}}},e.prototype._setExternalCheckoutData=function(e,t,n,r){return this._requestSender.post("/checkout.php",{headers:(0,s.__assign)({Accept:"text/html","Content-Type":"application/x-www-form-urlencoded"},C),body:{nonce:e,provider:"squarev2",action:"set_external_checkout",cardData:JSON.stringify(t),billingContact:JSON.stringify(n),shippingContact:JSON.stringify(r)}})},e.prototype._setPostalCode=function(){var e=this._store.getState().billingAddress.getBillingAddress();e&&e.postalCode&&this._getPaymentForm().setPostalCode(e.postalCode)},e.prototype._getBillingContact=function(){var e=this._store.getState().billingAddress.getBillingAddressOrThrow();return{givenName:e.firstName,familyName:e.lastName,email:e.email||"",country:e.countryCode,countryName:e.country,region:"",city:e.city,postalCode:e.postalCode,addressLines:[e.address1,e.address2],phone:e.phone}},e.prototype._getAmountAndCurrencyCode=function(){var e=this._store.getState(),t=e.cart.getCartOrThrow(),n=e.checkout.getCheckoutOrThrow();return[String(n.grandTotal),t.currency.code]},e.prototype._getVerificationDetails=function(){var e=this._getBillingContact(),t=this._getAmountAndCurrencyCode(),n=t[0],r=t[1];return{intent:cp.CHARGE,currencyCode:r,amount:n,billingContact:e}},e.prototype._getDeferredRequestNonce=function(){if(!this._deferredRequestNonce)throw new Pn(bn.PaymentNotInitialized);return this._deferredRequestNonce},e.prototype._getPaymentForm=function(){if(!this._paymentForm)throw new Pn(bn.PaymentNotInitialized);return this._paymentForm},e.prototype._is3DSExperimentOn=function(){return!0===this._store.getState().config.getStoreConfigOrThrow().checkoutSettings.features["PROJECT-3828.add_3ds_support_on_squarev2"]},e}();const pp=lp;var hp=function(){function e(e,t){void 0===t&&(t=window),this._scriptLoader=e,this._window=t}return e.prototype._isSquareWindow=function(e){return!!e.SqPaymentForm},e.prototype.load=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t=this;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return[4,this._scriptLoader.loadScript(e?"//js.squareupsandbox.com/v2/paymentform":"//js.squareup.com/v2/paymentform")];case 1:return n.sent(),[2,function(e){if(!t._isSquareWindow(t._window))throw new gi;return new t._window.SqPaymentForm(e)}]}}))}))},e}();const mp=hp;var _p={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 yp(e){var t=e.replace(/_/g,"-").toLowerCase().split("-"),n=t[0],r=t[1],i=_p[n];if(!i)return"auto";var o=r?n+"-"+r.toUpperCase():n;return i.indexOf(o)>-1?o:i[0]}var fp=[na.SOFORT,na.EPS,na.GRABPAY,na.BANCONTACT,na.IDEAL,na.GIROPAY,na.ALIPAY,na.KLARNA],gp=function(){function e(e,t,n,r,i,o,a){this._store=e,this._paymentMethodActionCreator=t,this._paymentActionCreator=n,this._orderActionCreator=r,this._stripeScriptLoader=i,this._storeCreditActionCreator=o,this._billingAddressActionCreator=a,this._isMounted=!1}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o=this;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:if(t=e.stripeupe,n=e.methodId,r=e.gatewayId,!(null==t?void 0:t.containerId))throw new Pn(bn.PaymentNotInitialized);if(!r)throw new ae('Unable to initialize payment because "gatewayId" argument is not provided.');return this._isDeinitialize=!1,this._loadStripeElement(t,r,n).catch((function(e){var n;return null===(n=t.onError)||void 0===n?void 0:n.call(t,e)})),i=this,[4,this._store.subscribe((function(e){return(0,s.__awaiter)(o,void 0,void 0,(function(){var e,i,o,a,c;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return(e=null===(o=this._stripeElements)||void 0===o?void 0:o.getElement(ia.PAYMENT))?[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(r,{params:{method:n}})).catch((function(e){return i=e}))]:[3,4];case 1:return s.sent(),i?(this._isMounted&&(e.unmount(),this._isMounted=!1),null===(a=t.onError)||void 0===a||a.call(t,i),[3,4]):[3,2];case 2:return this._isMounted?[3,4]:[4,null===(c=this._stripeElements)||void 0===c?void 0:c.fetchUpdates()];case 3:s.sent(),e.mount("#"+t.containerId),this._isMounted=!0,s.label=4;case 4:return[2]}}))}))}),(function(e){var t=e.checkout.getCheckout();return t&&t.outstandingBalance}),(function(e){var t=e.checkout.getCheckout();return t&&t.coupons}))];case 1:return i._unsubscribe=a.sent(),[2,Promise.resolve(this._store.getState())]}}))}))},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d,l,p,h,m,_,y,f,g;return(0,s.__generator)(this,(function(v){switch(v.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!n||!n.paymentData)throw new cu(["payment.paymentData"]);if(!this._stripeUPEClient)throw new Pn(bn.PaymentNotInitialized);return i=n.paymentData,o=n.methodId,a=n.gatewayId,c=Vu(i)?i:{},u=c.shouldSaveInstrument,d=void 0!==u&&u,l=c.shouldSetAsDefaultInstrument,p=void 0!==l&&l,(h=this._store.getState().checkout.getCheckoutOrThrow().isStoreCreditApplied)?[4,this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(h))]:[3,2];case 1:v.sent(),v.label=2;case 2:return a?[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(a,{params:{method:o}}))]:[3,5];case 3:return m=v.sent().customer.getCustomerOrThrow,_=m(),y=_.email,void 0===_.isStripeLinkAuthenticated||y?[3,5]:(f=this._store.getState().billingAddress.getBillingAddressOrThrow(),[4,this._store.dispatch(this._billingAddressActionCreator.updateAddress(f))]);case 4:v.sent(),v.label=5;case 5:return Gn(i)?[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))]:[3,7];case 6:return v.sent(),g=i.instrumentId,[2,this._executeWithVaulted(n.methodId,g,p)];case 7:return(0,Z.includes)(fp,o)?[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))]:[3,9];case 8:return v.sent(),[2,this._executeWithAPM(n.methodId)];case 9:return[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 10:return v.sent(),[2,this._executeWithoutRedirect(n.methodId,d,p)]}}))}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype.deinitialize=function(){var e,t;return this._unsubscribe&&this._unsubscribe(),null===(t=null===(e=this._stripeElements)||void 0===e?void 0:e.getElement(ia.PAYMENT))||void 0===t||t.unmount(),this._isMounted=!1,this._isDeinitialize=!0,Promise.resolve(this._store.getState())},e.prototype._isCancellationError=function(e){var t,n;return e&&-1!==(null===(n=null===(t=e.payment_intent.last_payment_error)||void 0===t?void 0:t.message)||void 0===n?void 0:n.indexOf("canceled"))},e.prototype._throwDisplayableStripeError=function(e){if((0,Z.includes)(["card_error","invalid_request_error","validation_error"],e.type))throw new Error(e.message)},e.prototype._executeWithAPM=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:t=this._store.getState().paymentMethods.getPaymentMethodOrThrow(e),n={methodId:e,paymentData:{formattedPayload:{credit_card_token:{token:t.clientToken},vault_payment_instrument:!1,confirm:!1,set_as_default_stored_instrument:!1}}},i.label=1;case 1:return i.trys.push([1,3,,5]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment(n))];case 2:return[2,i.sent()];case 3:return r=i.sent(),[4,this._processAdditionalAction(r)];case 4:return[2,i.sent()];case 5:return[2]}}))}))},e.prototype._executeWithoutRedirect=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:r=this._store.getState().paymentMethods.getPaymentMethodOrThrow(e),i={methodId:e,paymentData:{formattedPayload:{credit_card_token:{token:r.clientToken},vault_payment_instrument:t,confirm:!1,set_as_default_stored_instrument:n}}},a.label=1;case 1:return a.trys.push([1,3,,5]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment(i))];case 2:return[2,a.sent()];case 3:return o=a.sent(),[4,this._processAdditionalAction(o,t,n,e)];case 4:return[2,a.sent()];case 5:return[2]}}))}))},e.prototype._executeWithVaulted=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o;return(0,s.__generator)(this,(function(a){switch(a.label){case 0:r=this._store.getState().paymentMethods.getPaymentMethodOrThrow(e),a.label=1;case 1:return a.trys.push([1,3,,5]),i={methodId:e,paymentData:{formattedPayload:{bigpay_token:{token:t},confirm:!1,client_token:r.clientToken,set_as_default_stored_instrument:n}}},[4,this._store.dispatch(this._paymentActionCreator.submitPayment(i))];case 2:return[2,a.sent()];case 3:return o=a.sent(),[4,this._processVaultedAdditionalAction(o,e,n)];case 4:return[2,a.sent()];case 5:return[2]}}))}))},e.prototype._loadStripeElement=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d,l,p,_,y,f,g,v,w,C;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:return r=e.containerId,i=e.style,o=e.render,[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(t,{params:{method:n}}))];case 1:if(a=s.sent(),c=a.paymentMethods.getPaymentMethodOrThrow(n),u=c.initializationData,d=u.stripePublishableKey,l=u.stripeConnectedAccount,p=u.shopperLanguage,!c.clientToken)throw new m(h.MissingPaymentMethod);return _=this,[4,this._loadStripeJs(d,l)];case 2:_._stripeUPEClient=s.sent(),i&&(y={variables:{colorPrimary:(f=i).fieldInnerShadow,colorBackground:f.fieldBackground,colorText:f.labelText,colorDanger:f.fieldErrorText,colorTextSecondary:f.labelText,colorTextPlaceholder:f.fieldPlaceholderText,colorIcon:f.fieldPlaceholderText},rules:{".Input":{borderColor:f.fieldBorder,color:f.fieldText,boxShadow:f.fieldInnerShadow}}}),this._stripeElements=this._stripeScriptLoader.getElements(this._stripeUPEClient,{clientSecret:c.clientToken,locale:yp(p),appearance:y}),g=a.billingAddress.getBillingAddress,v=a.shippingAddress.getShippingAddress,w=(v()||g()||{}).postalCode,C=this._stripeElements.getElement(ia.PAYMENT)||this._stripeElements.create(ia.PAYMENT,{fields:{billingDetails:{email:ra.NEVER,address:{country:ra.NEVER,city:ra.NEVER,postalCode:w?ra.NEVER:ra.AUTO}}},wallets:{applePay:ra.NEVER,googlePay:ra.NEVER}});try{C.mount("#"+r),this._isMounted=!0}catch(e){if(!this._isDeinitialize)throw new ae("Unable to mount Stripe component without valid container ID.")}return C.on("ready",(function(){o()})),[2]}}))}))},e.prototype._processAdditionalAction=function(e,t,n,r){var i;return void 0===t&&(t=!1),void 0===n&&(n=!1),(0,s.__awaiter)(this,void 0,void 0,(function(){var o,a,c,u,d,l,p,h,m,_,y,f;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!(e instanceof x))throw e;if(!this._stripeUPEClient||!this._stripeElements)throw new Pn(bn.PaymentNotInitialized);return(0,Z.some)(e.body.errors,{code:"additional_action_required"})?(o=e.body.additional_action_required,a=o.type,c=o.data,u=c.token,d=c.redirect_url,"redirect_to_url"===a&&d?[4,this._stripeUPEClient.confirmPayment(this._mapStripePaymentData(d))]:[3,2]):[3,11];case 1:if(l=s.sent(),p=l.paymentIntent,h=l.error)throw this._throwDisplayableStripeError(h),new be;if(!p)throw new x;return[3,11];case 2:if(!r||"additional_action_requires_payment_method"!==a||!u)return[3,11];m=void 0,_=!1,y=this._mapStripePaymentData(),s.label=3;case 3:return s.trys.push([3,5,,10]),[4,this._stripeUPEClient.confirmPayment(y)];case 4:return m=s.sent(),[3,10];case 5:s.sent(),s.label=6;case 6:return s.trys.push([6,8,,9]),[4,this._stripeUPEClient.retrievePaymentIntent(u)];case 7:return m=s.sent(),[3,9];case 8:return s.sent(),_=!0,[3,9];case 9:return[3,10];case 10:if(null==m?void 0:m.error){if(this._throwDisplayableStripeError(m.error),this._isCancellationError(m.error))throw new uu;throw new be}if(!(null==m?void 0:m.paymentIntent)&&!_)throw new x;return f={methodId:r,paymentData:{formattedPayload:{credit_card_token:{token:_?u:null===(i=null==m?void 0:m.paymentIntent)||void 0===i?void 0:i.id},confirm:!1,vault_payment_instrument:t,set_as_default_stored_instrument:n}}},[2,this._store.dispatch(this._paymentActionCreator.submitPayment(f))];case 11:throw e}}))}))},e.prototype._processVaultedAdditionalAction=function(e,t,n){var r;return void 0===n&&(n=!1),(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!(e instanceof x))throw e;if(!this._stripeUPEClient||!this._stripeElements)throw new Pn(bn.PaymentNotInitialized);if(!(0,Z.some)(e.body.errors,{code:"three_d_secure_required"})||!t)return[3,9];i=e.body.three_ds_result.token,o=void 0,a=!1,s.label=1;case 1:return s.trys.push([1,3,,8]),[4,this._stripeUPEClient.confirmCardPayment(i)];case 2:return o=s.sent(),[3,8];case 3:s.sent(),s.label=4;case 4:return s.trys.push([4,6,,7]),[4,this._stripeUPEClient.retrievePaymentIntent(i)];case 5:return o=s.sent(),[3,7];case 6:return s.sent(),a=!0,[3,7];case 7:return[3,8];case 8:if(null==o?void 0:o.error){if(this._throwDisplayableStripeError(o.error),this._isCancellationError(o.error))throw new uu;throw new be}if(!(null==o?void 0:o.paymentIntent)&&!a)throw new x;return c={methodId:t,paymentData:{formattedPayload:{credit_card_token:{token:a?i:null===(r=null==o?void 0:o.paymentIntent)||void 0===r?void 0:r.id},confirm:!1,set_as_default_stored_instrument:n}}},[2,this._store.dispatch(this._paymentActionCreator.submitPayment(c))];case 9:throw e}}))}))},e.prototype._mapStripeAddress=function(e){if(e)return{city:e.city,country:e.countryCode,postal_code:e.postalCode};throw new m(h.MissingBillingAddress)},e.prototype._mapStripePaymentData=function(e){var t=this._store.getState().billingAddress.getBillingAddress(),n=this._mapStripeAddress(t),r=null==t?void 0:t.email;if(!this._stripeElements)throw new Pn(bn.PaymentNotInitialized);if(!(r&&n&&n.city&&n.country))throw new m(h.MissingBillingAddress);return{elements:this._stripeElements,redirect:ra.IF_REQUIRED,confirmParams:(0,s.__assign)({payment_method_data:{billing_details:{email:r,address:n}}},e&&{return_url:e})}},e.prototype._loadStripeJs=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){return this._stripeUPEClient?[2,this._stripeUPEClient]:[2,this._stripeScriptLoader.getStripeClient(e,t)]}))}))},e}();const vp=gp;var wp,Cp,Sp,Ip;function bp(e){return Boolean(e.cardNumberElementOptions)&&Boolean(e.cardCvcElementOptions)&&Boolean(e.cardExpiryElementOptions)}!function(e){e.Solid="solid",e.Default="default"}(wp||(wp={})),function(e){e.Alipay="alipay",e.CardCvc="cardCvc",e.CardExpiry="cardExpiry",e.CardNumber="cardNumber",e.CreditCard="card",e.IDEAL="idealBank",e.Sepa="iban"}(Cp||(Cp={})),function(e){e.Alipay="alipay",e.CreditCard="card",e.IDEAL="ideal",e.Sepa="sepa_debit"}(Sp||(Sp={})),function(e){e.AuthFailure="auth_failure"}(Ip||(Ip={}));const Pp=function(e){function t(t){var n=e.call(this,t===Ip.AuthFailure?"User did not authenticate":"There was an error while processing your payment. Please try again or contact us.")||this;return n.type="stripev3_error",n.subtype=t,n}return(0,s.__extends)(t,e),t}(p);var Ep=[Cp.Alipay,Cp.IDEAL],Ap=function(){function e(e,t,n,r,i,o,a,s){this._store=e,this._paymentMethodActionCreator=t,this._paymentActionCreator=n,this._orderActionCreator=r,this._stripeScriptLoader=i,this._storeCreditActionCreator=o,this._hostedFormFactory=a,this._locale=s}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d,l,p,h;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.stripev3,n=e.methodId,!(r=e.gatewayId))throw new ae('Unable to initialize payment because "gatewayId" argument is not provided.');return this._initializeOptions=t,this._isDeinitialize=!1,i=this._store.getState().paymentMethods.getPaymentMethodOrThrow(n),o=i.initializationData,a=o.stripePublishableKey,c=o.stripeConnectedAccount,u=o.useIndividualCardFields,d=this._getInitializeOptions().form,this._useIndividualCardFields=u,l=this,[4,this._loadStripeJs(a,c)];case 1:return l._stripeV3Client=s.sent(),this._isCreditCard(n)&&this._shouldShowTSVHostedForm(n,r)&&d?(p=this,[4,this._mountCardVerificationFields(d)]):[3,3];case 2:return p._hostedForm=s.sent(),[3,5];case 3:return h=this,[4,this._mountCardFields(n)];case 4:h._stripeElement=s.sent(),s.label=5;case 5:return[2,Promise.resolve(this._store.getState())]}}))}))},e.prototype.execute=function(e,t){var n,r;return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u,d,l,p,_,y,f,g,v,w,C,S,I,b,P,E,A,O,k;return(0,s.__generator)(this,(function(T){switch(T.label){case 0:if(i=e.payment,o=(0,s.__rest)(e,["payment"]),!i||!i.paymentData)throw new cu(["payment.paymentData"]);return u=i.paymentData,d=i.gatewayId,l=i.methodId,p=Vu(u)?u:{shouldSaveInstrument:!1,shouldSetAsDefaultInstrument:!1},_=p.shouldSaveInstrument,y=p.shouldSetAsDefaultInstrument,f=(0,Z.includes)(Ep,l),(g=this._store.getState().checkout.getCheckoutOrThrow().isStoreCreditApplied)?[4,this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(g))]:[3,2];case 1:T.sent(),T.label=2;case 2:return T.trys.push([2,13,,15]),f?[4,this._store.dispatch(this._orderActionCreator.submitOrder(o,t))]:[3,4];case 3:T.sent(),T.label=4;case 4:return[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(""+d,{params:{method:l}}))];case 5:return v=T.sent(),Gn(u)?[4,this._store.dispatch(this._orderActionCreator.submitOrder(o,t))]:[3,8];case 6:if(T.sent(),w=u.instrumentId,C=v.paymentMethods.getPaymentMethodOrThrow(i.methodId),!(S=C.clientToken))throw new m(h.MissingPaymentMethod);return[4,this._executeWithVaulted(i,w,y,S)];case 7:return[2,T.sent()];case 8:return I=v.paymentMethods.getPaymentMethodOrThrow(l),[4,this._confirmStripePayment(I)];case 9:return b=T.sent(),P=I.clientToken,E=I.method,A=(null!==(r=null!==(n=b.paymentIntent)&&void 0!==n?n:b.paymentMethod)&&void 0!==r?r:{id:""}).id,c=b.error,a={credit_card_token:{token:A},vault_payment_instrument:_,confirm:!1,set_as_default_stored_instrument:y},E===Cp.CreditCard&&(a.client_token=P),f?[3,11]:[4,this._store.dispatch(this._orderActionCreator.submitOrder(o,t))];case 10:T.sent(),T.label=11;case 11:return O=this._buildPaymentPayload(l,a,y),[4,this._store.dispatch(this._paymentActionCreator.submitPayment(O))];case 12:return[2,T.sent()];case 13:return k=T.sent(),[4,this._processAdditionalAction(this._handleEmptyPaymentIntentError(k,c),l,_,y)];case 14:return[2,T.sent()];case 15:return[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype.deinitialize=function(){return this._hostedForm&&this._hostedForm.detach(),this._isDeinitialize=!0,this._unmountElement(),Promise.resolve(this._store.getState())},e.prototype._buildPaymentPayload=function(e,t,n){return{methodId:e,paymentData:n?{formattedPayload:(0,s.__assign)((0,s.__assign)({},t),{set_as_default_stored_instrument:n})}:{formattedPayload:t}}},e.prototype._isCancellationError=function(e){var t,n;return e&&-1!==(null===(n=null===(t=e.payment_intent.last_payment_error)||void 0===t?void 0:t.message)||void 0===n?void 0:n.indexOf("canceled"))},e.prototype._isAuthError=function(e){return"payment_intent_authentication_failure"===(null==e?void 0:e.code)},e.prototype._isCreditCard=function(e){return e===Sp.CreditCard},e.prototype._isHostedFieldAvailable=function(){var e,t=this._getInitializeOptions(),n=(0,Z.omitBy)(null===(e=t.form)||void 0===e?void 0:e.fields,Z.isEmpty);return!(0,Z.isEmpty)(n)},e.prototype._isHostedPaymentFormEnabled=function(e,t){var n=(0,this._store.getState().paymentMethods.getPaymentMethodOrThrow)(e,t);return Boolean(n.config.isHostedFormEnabled)},e.prototype._confirmStripePayment=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a;return(0,s.__generator)(this,(function(s){if(t=e.clientToken,n=e.method,r=e.returnUrl,!t)throw new m(h.MissingPaymentMethod);switch(n){case Cp.Alipay:return[2,this._getStripeJs().confirmAlipayPayment(t,{return_url:r},{handleActions:!1})];case Cp.IDEAL:return i=this._mapStripePaymentData(Sp.IDEAL,r),[2,this._getStripeJs().confirmIdealPayment(t,i,{handleActions:!1})];case Cp.Sepa:return i=this._mapStripePaymentData(Sp.Sepa),[2,this._getStripeJs().confirmSepaDebitPayment(t,i)];default:return o=this._useIndividualCardFields?this._getStripeCardElements()[0]:this._getStripeElement(),a=this._mapStripeBillingDetails(this._store.getState().billingAddress.getBillingAddress(),this._store.getState().customer.getCustomer()),[2,this._getStripeJs().createPaymentMethod({type:Sp.CreditCard,card:o,billing_details:a})]}return[2]}))}))},e.prototype._executeWithVaulted=function(e,t,n,r){var i;return(0,s.__awaiter)(this,void 0,void 0,(function(){var o,a,c;return(0,s.__generator)(this,(function(u){switch(u.label){case 0:return o={bigpay_token:{token:t},confirm:!0,client_token:r,set_as_default_stored_instrument:n},this._isHostedPaymentFormEnabled(e.methodId,e.gatewayId)&&this._hostedForm?(a=this._hostedForm,e.paymentData&&Gn(e.paymentData)&&(e.paymentData=(0,s.__assign)((0,s.__assign)({},e.paymentData),{instrumentId:JSON.stringify({token:(null===(i=e.paymentData)||void 0===i?void 0:i.instrumentId)||"",client_token:r})})),[4,a.validate()]):[3,3];case 1:return u.sent(),[4,a.submit(e)];case 2:return u.sent(),[2,this._store.dispatch(this._orderActionCreator.loadCurrentOrder())];case 3:return c=this._buildPaymentPayload(e.methodId,o,n),[2,this._store.dispatch(this._paymentActionCreator.submitPayment(c))]}}))}))},e.prototype._getInitializeOptions=function(){if(!this._initializeOptions)throw new Pn(bn.PaymentNotInitialized);return this._initializeOptions},e.prototype._getStripeCardElements=function(){if(!this._stripeCardElements)throw new Pn(bn.PaymentNotInitialized);return this._stripeCardElements},e.prototype._getStripeElement=function(){if(!this._stripeElement)throw new Pn(bn.PaymentNotInitialized);return this._stripeElement},e.prototype._getStripeJs=function(){if(!this._stripeV3Client)throw new Pn(bn.PaymentNotInitialized);return this._stripeV3Client},e.prototype._handleEmptyPaymentIntentError=function(e,t){return e instanceof x&&(0,Z.some)(e.body.errors,{code:"required_field"})&&t?new Error(t.message):e},e.prototype._loadStripeJs=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){return this._stripeV3Client?[2,Promise.resolve(this._stripeV3Client)]:[2,this._stripeScriptLoader.load(e,t,this._locale)]}))}))},e.prototype._mapStripeAddress=function(e){return e?{city:e.city,country:e.countryCode,line1:e.address1,line2:e.address2,postal_code:e.postalCode,state:e.stateOrProvinceCode}:{line1:""}},e.prototype._mapStripeBillingDetails=function(e,t){var n=e||t||{firstName:"Guest",lastName:""},r=(n.firstName+" "+n.lastName).trim(),i=this._getInitializeOptions().options;if(this._useIndividualCardFields&&bp(i)){var o=i.zipCodeElementOptions;if(o){var a=document.getElementById(o.containerId)?document.getElementById(o.containerId).value:"";a&&e&&(e=(0,s.__assign)((0,s.__assign)({},e),{postalCode:a}))}}var c,u={address:this._mapStripeAddress(e)};if(t&&t.addresses[0]&&or(t.addresses[0])){var d=t.addresses[0],l=t.email;return(c=d.phone)?(0,s.__assign)((0,s.__assign)({},u),{email:l,name:r,phone:c}):(0,s.__assign)((0,s.__assign)({},u),{email:l,name:r})}return e?(l=e.email,(c=e.phone)?(0,s.__assign)((0,s.__assign)({},u),{email:l,name:r,phone:c}):(0,s.__assign)((0,s.__assign)({},u),{email:l,name:r})):(0,s.__assign)((0,s.__assign)({},u),{name:r})},e.prototype._mapStripePaymentData=function(e,t){var n,r=this._store.getState().customer.getCustomer(),i=this._store.getState().billingAddress.getBillingAddress(),o={payment_method:(n={},n[e]=this._getStripeElement(),n.billing_details=this._mapStripeBillingDetails(i,r),n)};return e===Sp.IDEAL?(0,s.__assign)((0,s.__assign)({},o),{return_url:t}):o},e.prototype._mountCardFields=function(e){var t,n=this,r=this._getInitializeOptions(),i=r.options,o=r.containerId;return new Promise((function(r,a){switch(n._stripeElements||(n._stripeElements=n._getStripeJs().elements()),e){case Cp.CreditCard:if(n._useIndividualCardFields&&bp(i)){var s=i.cardNumberElementOptions,c=i.cardExpiryElementOptions,u=i.cardCvcElementOptions,d=n._stripeElements.getElement(Cp.CardNumber)||n._stripeElements.create(Cp.CardNumber,s),l=n._stripeElements.getElement(Cp.CardExpiry)||n._stripeElements.create(Cp.CardExpiry,c),p=n._stripeElements.getElement(Cp.CardCvc)||n._stripeElements.create(Cp.CardCvc,u);n._stripeCardElements=[d,l,p],t=n._stripeCardElements[0];try{d.mount("#"+s.containerId),l.mount("#"+c.containerId),p.mount("#"+u.containerId)}catch(e){n._isDeinitialize||a(new ae("Unable to mount Stripe component without valid container ID."))}}else{t=n._stripeElements.getElement(e)||n._stripeElements.create(e,i);try{t.mount("#"+o)}catch(e){n._isDeinitialize||a(new ae("Unable to mount Stripe component without valid container ID."))}}break;case Cp.IDEAL:case Cp.Sepa:t=n._stripeElements.getElement(e)||n._stripeElements.create(e,i);try{t.mount("#"+o)}catch(e){n._isDeinitialize||a(new ae("Unable to mount Stripe component without valid container ID."))}case Cp.Alipay:}r(t)}))},e.prototype._mountCardVerificationFields=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(t=this._store.getState().config,!(n=t.getStoreConfig()))throw new m(h.MissingCheckoutConfig);return r=n.paymentSettings.bigpayBaseUrl,[4,(i=this._hostedFormFactory.create(r,e)).attach()];case 1:return o.sent(),[2,i]}}))}))},e.prototype._processAdditionalAction=function(e,t,n,r){return void 0===n&&(n=!1),void 0===r&&(r=!1),(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u,d,l,p,h,m,_;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!(e instanceof x))throw e;if(i=(0,Z.some)(e.body.errors,{code:"additional_action_required"}),o=(0,Z.some)(e.body.errors,{code:"three_d_secure_required"}),i&&(a=e.body.additional_action_required)&&"redirect_to_url"===a.type)return[2,new Promise((function(){a.data.redirect_url&&window.location.replace(a.data.redirect_url)}))];if(!o)return[3,8];c=e.body.three_ds_result.token,u=!1,d=!1,l=void 0,s.label=1;case 1:return s.trys.push([1,3,,4]),[4,this._getStripeJs().confirmCardPayment(c)];case 2:return l=s.sent(),[3,4];case 3:return s.sent(),d=!0,[3,4];case 4:if(null==l?void 0:l.error){if(this._isCancellationError(l.error))throw new uu;if(this._isAuthError(l.error))throw new Pp(Ip.AuthFailure);throw new Error(l.error.message)}p=this._getPaymentToken(null==l?void 0:l.paymentIntent,c,d),h={credit_card_token:{token:p},vault_payment_instrument:n,confirm:u},m=this._buildPaymentPayload(t,h,r),s.label=5;case 5:return s.trys.push([5,7,,8]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment(m))];case 6:return[2,s.sent()];case 7:throw _=s.sent(),this._handleEmptyPaymentIntentError(_,null==l?void 0:l.error);case 8:throw e}}))}))},e.prototype._getPaymentToken=function(e,t,n){return!e||n?t:e.id},e.prototype._shouldShowTSVHostedForm=function(e,t){return this._isHostedFieldAvailable()&&this._isHostedPaymentFormEnabled(e,t)},e.prototype._unmountElement=function(){this._stripeElement&&(this._stripeElement.unmount(),this._stripeElement=void 0)},e}();const Op=Ap,kp=function(){function e(e,t){void 0===t&&(t=window),this._scriptLoader=e,this._window=t}return e.prototype.load=function(e,t,n){var r=this;return this._scriptLoader.loadScript("https://js.stripe.com/v3/").then((function(){if(!r._window.Stripe)throw new gi;return r._window.Stripe(e,{stripeAccount:t,locale:n,betas:["payment_intent_beta_3","alipay_pm_beta_1"],apiVersion:"2020-03-02;alipay_beta=v1"})}))},e}(),Tp=function(){function e(e){this._scriptLoader=e}return e.prototype.initialize=function(){var e=this;return this._scriptLoader.loadScript("//static.wepay.com/min/js/risk.1.latest.js").then((function(){return e._riskClient=window.WePay.risk})).then((function(){return e}))},e.prototype.getRiskToken=function(){if(!this._riskClient)throw new Pn(bn.PaymentNotInitialized);return this._riskClient.generate_risk_token(),this._riskClient.get_risk_token()},e}(),Mp=function(e){function t(t,n,r,i,o){var a=e.call(this,t,n,r,i)||this;return a._wepayRiskClient=o,a}return(0,s.__extends)(t,e),t.prototype.initialize=function(t){return this._wepayRiskClient.initialize(),e.prototype.initialize.call(this,t)},t.prototype.execute=function(t,n){var r=this._wepayRiskClient.getRiskToken(),i=(0,Z.merge)({},t,{payment:{paymentData:{deviceSessionId:r}}});return e.prototype.execute.call(this,i,n)},t}(wu);var Dp,Rp="Payment cannot continue",zp=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return(0,s.__extends)(t,e),t.prototype.initialize=function(t){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(n){if(this._initializeOptions=t&&t.worldpay,!this._initializeOptions)throw new Pn(bn.PaymentNotInitialized);return[2,e.prototype.initialize.call(this,t)]}))}))},t.prototype.execute=function(t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:if(r=t.payment,Dp=this._submitAdditionalAction(),!r)throw new cu(["payment"]);o.label=1;case 1:return o.trys.push([1,3,,5]),[4,e.prototype.execute.call(this,t,n)];case 2:return[2,o.sent()];case 3:return i=o.sent(),[4,this._processAdditionalAction(i,r)];case 4:return[2,o.sent()];case 5:return[2]}}))}))},t.prototype._processAdditionalAction=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n=this;return(0,s.__generator)(this,(function(r){return e instanceof x&&(0,Z.some)(e.body.errors,{code:"additional_action_required"})?[2,new Promise((function(r,i){var o,a=function(e){return(0,s.__awaiter)(n,void 0,void 0,(function(){var n,u,d,l,p,h;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if("string"!=typeof e.data||!this._isValidJsonWithSessionId(e.data))return[2,i(new Error(Rp))];window.removeEventListener("message",a),window.removeEventListener("remove_event_message",c),o.remove(),n=JSON.parse(e.data),u=(0,Z.merge)({},t,{paymentData:{threeDSecure:{token:n.SessionId}}}),s.label=1;case 1:return s.trys.push([1,3,,4]),d=r,[4,Dp(u)];case 2:return d.apply(void 0,[s.sent()]),[3,4];case 3:if(!((l=s.sent())instanceof x&&(0,Z.some)(l.body.errors,{code:"three_d_secure_required"})))return[2,i(l)];if(!this._initializeOptions)return[2,i(new Pn(bn.PaymentNotInitialized))];p=this._initializeOptions.onLoad,h=this._createIframe(l.body.three_ds_result);try{p(h,(function(){return i(new Error("Payment was cancelled"))}))}catch(e){i(new Error(Rp))}return[3,4];case 4:return[2]}}))}))},c=function(){return window.removeEventListener("remove_event_message",c),window.removeEventListener("message",a),o.remove(),i(new Error(Rp))};window.addEventListener("message",a),window.addEventListener("remove_event_message",c);try{o=n._createHiddenIframe(e.body)}catch(e){throw window.removeEventListener("remove_event_message",c),window.removeEventListener("message",a),new Error(Rp)}}))]:[2,Promise.reject(e)]}))}))},t.prototype._createHiddenIframe=function(e){var t=document.createElement("iframe");if(!t)throw new Error;if(document.body.appendChild(t),!t.contentWindow)throw new Error;t.id="worldpay_hosted_hidden_payment_page",t.height="0px",t.width="0px";var n=document.createElement("form"),r="collectionForm";n.id=r,n.name="devicedata",n.method="post";var i=e.additional_action_required.data.redirect_url;n.action=i;var o=document.createElement("input");o.name="Bin",o.type="hidden",o.value=e.provider_data.source_id,n.appendChild(o);var a=document.createElement("input");a.name="JWT",a.type="hidden",a.value=e.provider_data.data,n.appendChild(a);var s=document.createElement("button");s.type="submit",s.id="btnsubmit",n.appendChild(s),navigator.userAgent.match("Firefox")?t.srcdoc=n.outerHTML:t.contentWindow.document.body.appendChild(n);var c=document.createElement("script");return c.innerHTML="\n const data = new URLSearchParams()\n data.append('Bin', '"+e.provider_data.source_id+"');\n data.append('JWT', '"+e.provider_data.data+"');\n\n window.parent.fetch('"+i+"', {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: data\n })\n .then((response) => {\n if (!response.ok) {\n window.parent.dispatchEvent(new Event('remove_event_message'));\n } else {\n document.getElementById('"+r+"').submit();\n }\n })\n .catch((error) => {\n window.parent.dispatchEvent(new Event('remove_event_message'));\n })\n ",t.contentWindow.document.body.appendChild(c),t},t.prototype._createIframe=function(e){var t=document.createElement("form");t.id="challengeForm",t.method="POST",t.action=e.acs_url;var n=document.createElement("input");n.name="JWT",n.type="hidden",n.value=e.payer_auth_request,t.appendChild(n);var r=document.createElement("input");r.name="MD",r.type="hidden",r.value="merchantSessionId="+e.merchant_data,t.appendChild(r);var i=document.createElement("script");i.type="text/javascript",i.innerHTML="window.onload = function() { document.getElementById('challengeForm').submit(); }";var o=document.createElement("iframe");return o.name="worldpay_hosted_payment_page",o.height="400",o.width="100%",o.srcdoc=t.outerHTML+" "+i.outerHTML,o},t.prototype._submitAdditionalAction=function(){var e=this;if(this._shouldRenderHostedForm){if(!this._hostedForm||!this._hostedForm.submit)throw new Pn(bn.PaymentNotInitialized);var t=this._hostedForm;return function(n){return(0,s.__awaiter)(e,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){switch(e.label){case 0:return[4,t.submit(n)];case 1:return e.sent(),[2,this._store.getState()]}}))}))}}return function(t){return(0,s.__awaiter)(e,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){return[2,this._store.dispatch(this._paymentActionCreator.submitPayment(t))]}))}))}},t.prototype._isValidJsonWithSessionId=function(e){try{return!!JSON.parse(e).SessionId}catch(e){return!1}},t}(wu);const Np=zp;var Lp=function(){function e(e,t,n,r,i,o,a){this._store=e,this._paymentMethodActionCreator=t,this._storeCreditActionCreator=n,this._remoteCheckoutActionCreator=r,this._orderActionCreator=i,this._storefrontPaymentRequestSender=o,this._paymentActionCreator=a}return e.prototype.initialize=function(){return Promise.resolve(this._store.getState())},e.prototype.execute=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d,l,p,_;return(0,s.__generator)(this,(function(y){switch(y.label){case 0:if(n=e.payment,r=(0,s.__rest)(e,["payment"]),!n)throw new cu(["payment"]);return i=n.methodId,[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(i,t))];case 1:if(o=y.sent().paymentMethods.getPaymentMethodOrThrow,a=o(i),c=a.clientToken,u=a.initializationData,d=(void 0===u?{}:u).redirectUrl,!c||!d)throw new m(h.MissingPaymentMethod);if(!(l=JSON.parse(c).id))throw new m(h.MissingPaymentToken);return p=this._store.getState().checkout.getCheckoutOrThrow().isStoreCreditApplied,[4,this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(p))];case 2:return y.sent(),[4,this._store.dispatch(this._remoteCheckoutActionCreator.initializePayment(i,{useStoreCredit:p}))];case 3:return y.sent(),[4,this._store.dispatch(this._orderActionCreator.submitOrder(r,t))];case 4:return y.sent(),[4,this._prepareForReferredRegistration(i,l)];case 5:y.sent(),y.label=6;case 6:return y.trys.push([6,8,,9]),[4,this._store.dispatch(this._paymentActionCreator.submitPayment({methodId:i,paymentData:{nonce:l}}))];case 7:return[2,y.sent()];case 8:if((_=y.sent())instanceof x&&"additional_action_required"===_.body.status)return[2,new Promise((function(){return window.location.replace(d)}))];throw _;case 9:return[2]}}))}))},e.prototype.finalize=function(){return Promise.reject(new Hc)},e.prototype.deinitialize=function(){return Promise.resolve(this._store.getState())},e.prototype._prepareForReferredRegistration=function(e,t){return this._storefrontPaymentRequestSender.saveExternalId(e,t)},e}();const Fp=Lp;var Bp;!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"}(Bp||(Bp={}));var Up=function(){function e(e){this._instrumentRequestSender=e}return e.prototype.loadInstruments=function(){var e=this;return function(t){return u.Observable.create((function(n){n.next((0,c.createAction)(Bp.LoadInstrumentsRequested));var r=e._getSessionContext(t),i=e._getCurrentAccessToken(t),o=e._getShippingAddress(t);return e._getValidAccessToken(i).then((function(t){return e._instrumentRequestSender.loadInstruments((0,s.__assign)((0,s.__assign)({},r),{authToken:t.vaultAccessToken}),o).then((function(e){var r=e.body;n.next((0,c.createAction)(Bp.LoadInstrumentsSucceeded,r,t)),n.complete()}))})).catch((function(e){n.error((0,c.createErrorAction)(Bp.LoadInstrumentsFailed,e))}))}))}},e.prototype.deleteInstrument=function(e){var t=this;return function(n){return u.Observable.create((function(r){r.next((0,c.createAction)(Bp.DeleteInstrumentRequested,void 0,{instrumentId:e}));var i=t._getSessionContext(n),o=t._getCurrentAccessToken(n);return t._getValidAccessToken(o).then((function(n){return t._instrumentRequestSender.deleteInstrument((0,s.__assign)((0,s.__assign)({},i),{authToken:n.vaultAccessToken}),e).then((function(t){var i=t.body;r.next((0,c.createAction)(Bp.DeleteInstrumentSucceeded,i,(0,s.__assign)({instrumentId:e},n))),r.complete()}))})).catch((function(t){r.error((0,c.createErrorAction)(Bp.DeleteInstrumentFailed,t,{instrumentId:e}))}))}))}},e.prototype._isValidVaultAccessToken=function(e){return!(!e||!e.vaultAccessToken)&&function(e){return e.valueOf()>Date.now()}((t=new Date(e.vaultAccessExpiry),2,(n=new Date(t.getTime())).setMinutes(t.getMinutes()+2),n));var t,n},e.prototype._getCurrentAccessToken=function(e){var t=e.getState().instruments.getInstrumentsMeta();if(t)return{vaultAccessToken:t.vaultAccessToken,vaultAccessExpiry:t.vaultAccessExpiry}},e.prototype._getValidAccessToken=function(e){return e&&this._isValidVaultAccessToken(e)?Promise.resolve(e):this._instrumentRequestSender.getVaultAccessToken().then((function(e){return e.body}))},e.prototype._getShippingAddress=function(e){var t=e.getState(),n=t.shippingAddress.getShippingAddresses();return n.length>1?n:t.shippingAddress.getShippingAddress()},e.prototype._getSessionContext=function(e){var t=e.getState(),n=t.config.getStoreConfig(),r=t.cart.getCart();if(!n)throw new m(h.MissingCheckoutConfig);if(!r)throw new m(h.MissingCart);return{customerId:r.customerId,storeId:n.storeProfile.storeId,currencyCode:(n.shopperCurrency.isTransactional?n.shopperCurrency:n.currency).code}},e}();const xp=Up;var qp=function(){function e(){}return e.prototype.transformResponse=function(e){var t=this._transformResponse(e),n=t.body,r=(0,s.__rest)(t,["body"]);return(0,s.__assign)((0,s.__assign)({},r),{body:{vaultedInstruments:this._transformVaultedInstruments(n.vaulted_instruments)}})},e.prototype.transformErrorResponse=function(e){return this._transformResponse(e)},e.prototype.transformVaultAccessResponse=function(e){return(0,s.__assign)((0,s.__assign)({},e),{body:{vaultAccessToken:e.body.data.token,vaultAccessExpiry:e.body.data.expires_at}})},e.prototype._transformVaultedInstruments=function(e){var t=this;return void 0===e&&(e=[]),e.map((function(e){return t._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):t._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)}))},e.prototype._isPayPalInstrument=function(e){return"paypal"===e.method_type},e.prototype._isBankInstrument=function(e){return"bank"===e.method_type},e.prototype._transformResponse=function(e){var t=e.data,n=(0,s.__rest)(e,["data"]);return(0,s.__assign)((0,s.__assign)({},n),{body:t})},e}();const Vp=qp;var Gp=function(){function e(e,t){this._client=e,this._requestSender=t,this._transformer=new Vp}return e.prototype.getVaultAccessToken=function(e){var t=(void 0===e?{}:e).timeout;return this._requestSender.get("/internalapi/v1/checkout/payments/vault-access-token",{timeout:t}).then((function(e){return(0,s.__assign)((0,s.__assign)({},e),{body:{vaultAccessToken:e.body.data.token,vaultAccessExpiry:e.body.data.expires_at}})}))},e.prototype.loadInstruments=function(e,t){return t?this._loadInstrumentsWithAddress(e,t):this._loadInstruments(e)},e.prototype.deleteInstrument=function(e,t){var n=this,r=(0,s.__assign)((0,s.__assign)({},e),{instrumentId:t});return new Promise((function(e,t){n._client.deleteShopperInstrument(r,(function(r,i){return r?t(n._transformer.transformErrorResponse(r)):e(n._transformer.transformResponse(i))}))}))},e.prototype._loadInstruments=function(e){var t=this;return new Promise((function(n,r){t._client.loadInstruments(e,(function(e,i){return e?r(t._transformer.transformErrorResponse(e)):n(t._transformer.transformResponse(i))}))}))},e.prototype._loadInstrumentsWithAddress=function(e,t){var n=this,r=(0,s.__assign)((0,s.__assign)({},e),{shippingAddress:Array.isArray(t)?t.map((function(e){return ar(e)})):ar(t)});return new Promise((function(e,t){n._client.loadInstrumentsWithAddress(r,(function(r,i){return r?t(n._transformer.transformErrorResponse(r)):e(n._transformer.transformResponse(i))}))}))},e}();const Hp=Gp;var Yp;!function(e){e.LoadPickupOptionsRequested="LOAD_PICKUP_OPTIONS_REQUESTED",e.LoadPickupOptionsSucceeded="LOAD_PICKUP_OPTIONS_SUCCEEDED",e.LoadPickupOptionsFailed="LOAD_PICKUP_OPTIONS_FAILED"}(Yp||(Yp={}));const jp=function(){function e(e){this._pickupOptionRequestSender=e}return e.prototype.loadPickupOptions=function(e){var t=this;return function(n){return new u.Observable((function(r){var i=t._hydrateApiQuery(n,e);r.next((0,c.createAction)(Yp.LoadPickupOptionsRequested)),t._pickupOptionRequestSender.fetchPickupOptions(i).then((function(t){r.next((0,c.createAction)(Yp.LoadPickupOptionsSucceeded,t.body.results,e)),r.complete()})).catch((function(e){r.error((0,c.createErrorAction)(Yp.LoadPickupOptionsFailed,e))}))}))}},e.prototype._hydrateApiQuery=function(e,t){var n=e.getState(),r=n.cart.getCartOrThrow();if(!r)throw new m(h.MissingCart);var i=n.consignments.getConsignmentById(t.consignmentId);if(!i)throw new m(h.MissingConsignments);var o=i.lineItemIds,a=r.lineItems.physicalItems.filter((function(e){return(0,Z.includes)(o,e.id)})).map((function(e){return{variantId:e.variantId,quantity:e.quantity}}));return{searchArea:t.searchArea,items:a}},e}(),Wp=function(){function e(e){this._requestSender=e}return e.prototype.fetchPickupOptions=function(e){return this._requestSender.post("/api/storefront/pickup-options",{headers:(0,s.__assign)({Accept:w.Json},C),body:e})},e}();var Kp;!function(e){e.LoadShippingCountriesRequested="LOAD_SHIPPING_COUNTRIES_REQUESTED",e.LoadShippingCountriesSucceeded="LOAD_SHIPPING_COUNTRIES_SUCCEEDED",e.LoadShippingCountriesFailed="LOAD_SHIPPING_COUNTRIES_FAILED"}(Kp||(Kp={}));const Jp=function(){function e(e){this._shippingCountryRequestSender=e}return e.prototype.loadCountries=function(e){var t=this;return u.Observable.create((function(n){n.next((0,c.createAction)(Kp.LoadShippingCountriesRequested)),t._shippingCountryRequestSender.loadCountries(e).then((function(e){n.next((0,c.createAction)(Kp.LoadShippingCountriesSucceeded,e.body.data)),n.complete()})).catch((function(e){n.error((0,c.createErrorAction)(Kp.LoadShippingCountriesFailed,e))}))}))},e}();var Zp=function(){function e(e,t){this._requestSender=e,this._config=t}return e.prototype.loadCountries=function(e){var t=(void 0===e?{}:e).timeout,n=(0,s.__assign)({"Accept-Language":this._config.locale},C);return this._requestSender.get("/internalapi/v1/shipping/countries",{headers:n,timeout:t})},e}();const Qp=Zp;var Xp;!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"}(Xp||(Xp={}));const $p=function(){function e(e){this._strategyRegistry=e}return e.prototype.updateAddress=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o=r.getState().payment.getPaymentId(),a=t&&t.methodId||o&&o.providerId;i.next((0,c.createAction)(Xp.UpdateAddressRequested,void 0,{methodId:a})),n._strategyRegistry.get(a).updateAddress(e,(0,s.__assign)((0,s.__assign)({},t),{methodId:a})).then((function(){i.next((0,c.createAction)(Xp.UpdateAddressSucceeded,void 0,{methodId:a})),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(Xp.UpdateAddressFailed,e,{methodId:a}))}))}))}},e.prototype.selectOption=function(e,t){var n=this;return function(r){return u.Observable.create((function(i){var o=r.getState().payment.getPaymentId(),a=t&&t.methodId||o&&o.providerId;i.next((0,c.createAction)(Xp.SelectOptionRequested,void 0,{methodId:a})),n._strategyRegistry.get(a).selectOption(e,(0,s.__assign)((0,s.__assign)({},t),{methodId:a})).then((function(){i.next((0,c.createAction)(Xp.SelectOptionSucceeded,void 0,{methodId:a})),i.complete()})).catch((function(e){i.error((0,c.createErrorAction)(Xp.SelectOptionFailed,e,{methodId:a}))}))}))}},e.prototype.initialize=function(e){var t=this;return function(n){return u.Observable.create((function(r){var i=n.getState(),o=i.payment.getPaymentId(),a=e&&e.methodId||o&&o.providerId,u=(0,s.__assign)((0,s.__assign)({},e),{methodId:a});if(a&&i.shippingStrategies.isInitialized(a))return r.complete();r.next((0,c.createAction)(Xp.InitializeRequested,void 0,{methodId:a})),t._strategyRegistry.get(a).initialize(u).then((function(){r.next((0,c.createAction)(Xp.InitializeSucceeded,void 0,{methodId:a})),r.complete()})).catch((function(e){r.error((0,c.createErrorAction)(Xp.InitializeFailed,e,{methodId:a}))}))}))}},e.prototype.deinitialize=function(e){var t=this;return function(n){return u.Observable.create((function(r){var i=n.getState(),o=i.payment.getPaymentId(),a=e&&e.methodId||o&&o.providerId;if(a&&!i.shippingStrategies.isInitialized(a))return r.complete();r.next((0,c.createAction)(Xp.DeinitializeRequested,void 0,{methodId:a})),t._strategyRegistry.get(a).deinitialize((0,s.__assign)((0,s.__assign)({},e),{methodId:a})).then((function(){r.next((0,c.createAction)(Xp.DeinitializeSucceeded,void 0,{methodId:a})),r.complete()})).catch((function(e){r.error((0,c.createErrorAction)(Xp.DeinitializeFailed,e,{methodId:a}))}))}))}},e.prototype.widgetInteraction=function(e,t){return u.Observable.create((function(n){var r={methodId:t&&t.methodId};n.next((0,c.createAction)(Xp.WidgetInteractionStarted,void 0,r)),e().then((function(){n.next((0,c.createAction)(Xp.WidgetInteractionFinished,void 0,r)),n.complete()})).catch((function(e){n.error((0,c.createErrorAction)(Xp.WidgetInteractionFailed,e,r))}))}))},e}();var eh=function(){function e(e,t,n,r,i){this._store=e,this._consignmentActionCreator=t,this._paymentMethodActionCreator=n,this._amazonPayV2PaymentProcessor=r,this._shippingStrategyActionCreator=i}return e.prototype.updateAddress=function(e,t){var n=this._store.getState().shippingAddress.getShippingAddress();if(!n)throw new m(h.MissingShippingAddress);var r=(0,s.__assign)((0,s.__assign)({},n),{customFields:e.customFields});return this._store.dispatch(this._consignmentActionCreator.updateAddress(r,t))},e.prototype.selectOption=function(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))},e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.amazonpay,n=e.methodId,!t||!n)throw new ae('Unable to proceed because "options.amazonpay" argument is not provided.');return[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(n))];case 1:return r=s.sent(),i=r.paymentMethods.getPaymentMethodOrThrow(n),[4,this._amazonPayV2PaymentProcessor.initialize(i)];case 2:return s.sent(),o=i.initializationData,a=o.paymentToken,c=o.region,u=t.editAddressButtonId,a&&u&&(d=this._shouldShowLoadingSpinner(c),this._bindEditButton(u,a,"changeAddress",d)),[2,this._store.getState()]}}))}))},e.prototype.deinitialize=function(){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(e){switch(e.label){case 0:return[4,this._amazonPayV2PaymentProcessor.deinitialize()];case 1:return e.sent(),[2,Promise.resolve(this._store.getState())]}}))}))},e.prototype._bindEditButton=function(e,t,n,r){var i=this,o=document.getElementById(e);if(o&&o.parentNode){if(r){var a=o.cloneNode(!0);o.parentNode.replaceChild(a,o),a.addEventListener("click",(function(){return i._showLoadingSpinner()}))}this._amazonPayV2PaymentProcessor.bindButton(e,t,n)}},e.prototype._showLoadingSpinner=function(){return this._store.dispatch(this._shippingStrategyActionCreator.widgetInteraction((function(){return new Promise(u.noop)})),{queueId:"widgetInteraction"})},e.prototype._shouldShowLoadingSpinner=function(e){return"us"!==e},e}();const th=eh,nh=function(){function e(e,t){this._store=e,this._consignmentActionCreator=t}return e.prototype.updateAddress=function(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))},e.prototype.selectOption=function(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))},e.prototype.initialize=function(){return Promise.resolve(this._store.getState())},e.prototype.deinitialize=function(){return Promise.resolve(this._store.getState())},e}();var rh=function(){function e(e,t,n,r){this._store=e,this._stripeUPEScriptLoader=t,this._consignmentActionCreator=n,this._paymentMethodActionCreator=r}return e.prototype.updateAddress=function(e,t){return this._store.dispatch(this._consignmentActionCreator.updateAddress(e,t))},e.prototype.selectOption=function(e,t){return this._store.dispatch(this._consignmentActionCreator.selectShippingOption(e,t))},e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d,l,p,_,y,f,g,v,w,C,S,I,b,P,E,A,O,k,T,M,D,R,z,N,L,F,B=this;return(0,s.__generator)(this,(function(U){switch(U.label){case 0:if(!e.stripeupe)throw new ae('Unable to proceed because "options" argument is not provided.');return t=e.stripeupe,n=t.container,r=t.gatewayId,i=t.methodId,o=t.onChangeShipping,a=t.getStyles,c=t.availableCountries,u=t.getStripeState,Object.entries(e.stripeupe).forEach((function(e){var t=e[0];if(!e[1])throw new ae('Unable to proceed because "'+t+'" argument is not provided.')})),[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(r,{params:{method:i}}))];case 1:if(d=U.sent(),l=d.paymentMethods.getPaymentMethodOrThrow(i,r),p=l.initializationData,_=p.stripePublishableKey,y=p.stripeConnectedAccount,!l||!l.initializationData.stripePublishableKey||!l.clientToken)throw new m(h.MissingPaymentMethod);return f=this,[4,this._stripeUPEScriptLoader.getStripeClient(_,y)];case 2:return f._stripeUPEClient=U.sent(),v=a&&a(),w=this._store.getState(),C=w.form.getShippingAddressFields,S=w.shippingAddress.getShippingAddress,I=C([],""),g=v?{variables:{colorPrimary:v.fieldInnerShadow,colorBackground:v.fieldBackground,colorText:v.labelText,colorDanger:v.fieldErrorText,colorTextSecondary:v.labelText,colorTextPlaceholder:v.fieldPlaceholderText,spacingUnit:"4px",borderRadius:"4px"},rules:{".Input":{borderColor:v.fieldBorder,color:v.fieldText,boxShadow:v.fieldInnerShadow}}}:{variables:{spacingUnit:"4px",borderRadius:"4px"}},this._stripeElements=this._stripeUPEScriptLoader.getElements(this._stripeUPEClient,{clientSecret:l.clientToken,appearance:g}),b=S(),P=I.find((function(e){return"phone"===e.name})),E={mode:ea.SHIPPING,allowedCountries:[c],fields:{phone:"always"},validation:{phone:{required:P&&P.required?"always":"never"}},display:{name:ta.SPLIT}},b&&(A=b.stateOrProvinceCode,O=b.countryCode,k=b.lastName,T=b.firstName,M=b.phone,D=b.address1,R=b.address2,z=b.city,N=b.postalCode,L=A&&O?u(O,A):A,E=(0,s.__assign)((0,s.__assign)({},E),{defaultValues:{firstName:T,lastName:k,phone:M,address:{line1:D,line2:R,city:z,state:L,postal_code:N,country:O}}})),(F=this._stripeElements.getElement(ia.SHIPPING))&&F.destroy(),(F=this._stripeElements.create(ia.SHIPPING,E)).on("change",(function(e){if(!("isNewAddress"in e))throw new m(h.MissingShippingAddress);(e.complete||e.isNewAddress)&&(B.sendData&&clearTimeout(B.sendData),B.sendData=setTimeout((function(){o((0,s.__assign)((0,s.__assign)({},e),{phoneFieldRequired:!!P&&P.required}))}),1e3))})),F.mount("#"+n),[2,Promise.resolve(this._store.getState())]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve(this._store.getState())},e}();const ih=rh;var oh;!function(e){e.SendSignInEmailRequested="SEND_SIGNIN_EMAIL_REQUESTED",e.SendSignInEmailSucceeded="SEND_SIGNIN_EMAIL_SUCCEEDED",e.SendSignInEmailFailed="SEND_SIGNIN_EMAIL_FAILED"}(oh||(oh={}));var ah=function(){function e(e){this._requestSender=e}return e.prototype.sendSignInEmail=function(e,t){var n=this;return(0,u.concat)((0,u.of)((0,c.createAction)(oh.SendSignInEmailRequested)),(0,u.defer)((function(){return(0,s.__awaiter)(n,void 0,void 0,(function(){var n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._requestSender.sendSignInEmail(e,t)];case 1:return n=r.sent().body,[2,(0,c.createAction)(oh.SendSignInEmailSucceeded,n)]}}))}))}))).pipe((0,d.catchError)((function(e){return l(oh.SendSignInEmailFailed,e)})))},e}();const sh=ah;var ch=function(){function e(e){this._requestSender=e}return e.prototype.sendSignInEmail=function(e,t){var n=e.email,r=e.redirectUrl,i=(void 0===t?{}:t).timeout,o=(0,s.__assign)({Accept:w.JsonV1},C);return this._requestSender.post("/login.php?action=passwordless_login",{body:{email:n,redirect_url:r||hn(window.top.location.href).pathname},headers:o,timeout:i})},e}();const uh=ch,dh=require("reselect");function lh(e){return function(){for(var t=[],n=0;n0}})),W=ph(x,(function(e){return function(t){return!(!t||!t.nonce)||e()===Iu||e()===bu}})),(0,z.memoizeOne)((function(e,t){return{getPaymentId:B({checkout:e,order:t}),getPaymentIdOrThrow:U({checkout:e,order:t}),getPaymentStatus:x({checkout:e,order:t}),getPaymentStatusOrThrow:q({checkout:e,order:t}),getPaymentToken:V({checkout:e,order:t}),getPaymentTokenOrThrow:G({checkout:e,order:t}),getPaymentRedirectUrl:H({checkout:e,order:t}),getPaymentRedirectUrlOrThrow:Y({checkout:e,order:t}),isPaymentDataRequired:j({checkout:e,order:t}),isPaymentDataSubmitted:W({checkout:e,order:t})}}))),Ce=function(){var e=ph((function(e){return e.errors.applyError}),(function(e){return function(){return e}})),t=ph((function(e){return!!e.statuses.isApplying}),(function(e){return function(){return e}}));return(0,z.memoizeOne)((function(n){return void 0===n&&(n=ty),{getApplyError:e(n),isApplying:t(n)}}))}(),Se=function(){var e=ph((function(e){return e.errors.updateError}),(function(e){return function(){return e}})),t=ph((function(e){return!!e.statuses.isUpdating}),(function(e){return function(){return e}}));return(0,z.memoizeOne)((function(n){return void 0===n&&(n=G_),{getUpdateError:e(n),isUpdating:t(n)}}))}(),Ie=(K=ph((function(e){return e.data}),(function(e){return function(){return e}})),J=ph((function(e){return e.errors.sendError}),(function(e){return function(){return e}})),Q=ph((function(e){return!!e.statuses.isSending}),(function(e){return function(){return e}})),(0,z.memoizeOne)((function(e){return void 0===e&&(e=z_),{getEmail:K(e),getSendError:J(e),isSending:Q(e)}}))),be=function(){var e=ph((function(e){return e.data}),(function(e){return function(){return e}})),t=ph((function(e){return e.data}),(function(e){return function(t){return null==e?void 0:e.find((function(e){return e.region===t}))}})),n=ph((function(e){return e.errors.loadError}),(function(e){return function(){return e}})),r=ph((function(e){return e.statuses.isLoading}),(function(e){return function(){return!!e}}));return(0,z.memoizeOne)((function(i){return void 0===i&&(i=wm),{getExtensions:e(i),getExtensionByRegion:t(i),getLoadError:n(i),isLoading:r(i)}}))}();return function(e,t){void 0===t&&(t={});var n,r=X(e.billingAddress),i=$(e.cart),o=ee(e.checkoutButton),a=ne(e.countries),s=re(e.coupons),c=ie(e.customer),u=oe(e.customerStrategies),d=be(e.extensions),l=ce(e.formFields),p=ae(e.giftCertificates),h=se(e.instruments),m=ve(e.orderBillingAddress),_=ue(e.paymentMethods),y=de(e.paymentStrategies),f=le(e.pickupOptions),g=pe(e.remoteCheckout),v=he(e.consignments),w=me(e.shippingCountries),C=_e(e.shippingStrategies),S=Se(e.subscriptions),I=Ce(e.storeCredit),b=Ie(e.signInEmail),P=ye(e.consignments,i),E=fe(e.checkout,r,i,P,s,c,p),A=ge(e.order,m,s),O=we(E,A),k={billingAddress:r,cart:i,checkout:E,checkoutButton:o,config:te(e.config,e.formFields),consignments:P,countries:a,coupons:s,customer:c,customerStrategies:u,extensions:d,form:l,giftCertificates:p,instruments:h,order:A,orderBillingAddress:m,payment:O,paymentMethods:_,paymentStrategies:y,pickupOptions:f,remoteCheckout:g,shippingAddress:v,shippingCountries:w,shippingStrategies:C,signInEmail:b,subscriptions:S,storeCredit:I};return t.shouldWarnMutation?(n=k,Object.keys(n).reduce((function(e,t){return e[t]=X_(n[t]),e}),{})):k}}function ry(e,t){void 0===e&&(e={});var n,r,i=(n=new Sh,["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((function(e){n.register(e,(function(e,t){return new vh(e,t)}))})),n.register("invalid_payment_provider",(function(e){return new Te(e)})),n.register("payment_config_not_found",(function(e){return new Te(e)})),r=n,function(e){return(0,u.from)(e).pipe((0,d.catchError)((function(e){if(e instanceof Error||e.payload instanceof Error)throw e;if((n=e.payload)&&"object"==typeof n&&["body","headers","status","statusText"].every((function(e){return Object.prototype.hasOwnProperty.call(n,e)}))){var t=e.payload.body&&e.payload.body.detail;throw(0,s.__assign)((0,s.__assign)({},e),{payload:r.createError(e.payload,t)})}var n;throw e})))}),o=ny();return(0,c.createDataStore)((0,c.combineReducers)({billingAddress:kh,cart:Fh,checkout:K_,checkoutButton:Yh,config:Zh,consignments:h_,countries:Mm,coupons:tm,customer:lm,customerStrategies:ym,extensions:Cm,formFields:Em,giftCertificates:am,instruments:i_,orderBillingAddress:Vm,order:Lm,payment:Hm,paymentMethods:Wm,paymentStrategies:$m,pickupOptions:w_,remoteCheckout:d_,shippingCountries:P_,shippingStrategies:T_,signInEmail:N_,subscriptions:H_,storeCredit:x_}),e,(0,s.__assign)({actionTransformer:i,stateTransformer:function(e){return o(e)}},t))}function iy(e){"https:"!==document.location.protocol&&R().warn("The BigCommerce Checkout SDK should not be used on a non-HTTPS page"),"production"!==A()&&R().warn("Note that the development build is not optimized. To create a production build, set process.env.NODE_ENV to `production`.");var n={meta:{externalSource:e&&e.externalSource,host:null==e?void 0:e.host,locale:null==e?void 0:e.locale,variantIdentificationToken:window.checkoutVariantIdentificationToken},errors:{},statuses:{}},r=e||{},i=r.locale,s=void 0===i?"":i,c=r.shouldWarnMutation,u=void 0===c||c,d=(0,o.createRequestSender)({host:e&&e.host}),l=ry({config:n},{shouldWarnMutation:u}),p=ir(l),h=new Xn(d),m=new Vt(d),_=new F(new H(d)),y=Tn((0,a.createScriptLoader)()),f=new Br(d),v=new Lr(y,f),w=new Kn(h,new sn(m)),C=new Wr(new Jr(d)),S=new Kt(new Zt(d)),I=new Yt(m,_,S),P=ai(l),O=Gc(P,t,{useFallback:!0}),k=Mt(P),T=new la(new pa(d));return new gh(l,new g(new b(d),C),I,_,new Nt(new Ft(d),I,v),new Tr(new Rr(d),m),new xc(new Vc(d,{locale:s})),new W(new $(d)),new Ut(function(e,t,n){var r=new ce,i=(0,a.getScriptLoader)(),o=new Vt(t),s=new Yt(o,new F(new H(t)),new Kt(new Zt(t))),c=(0,xe.createFormPoster)(),u=new $t(new tn(t)),d=new wo(t),l=new Io(d,s),p=new Lr(Tn(i),new Br(t)),h=new Nt(new Ft(t),s,p),m=new Pi(new Oi(i)),_=Mt(ai(e));return r.register("googlepayadyenv2",(function(){return new jo(e,l,Yi(e,new Wi),c)})),r.register("googlepayadyenv3",(function(){return new jo(e,l,Yi(e,new Ji),c)})),r.register("amazonpay",(function(){return new Eo(e,u,l,Ci())})),r.register("braintreevisacheckout",(function(){return new Oo(e,s,u,new Ut(r,_),l,Mi(i,t),new Di(i),c)})),r.register("braintreepaypalcredit",(function(){return new Bo(e,s,h,u,m,c,window)})),r.register("chasepay",(function(){return new xo(e,u,l,new Ri(i),t,c)})),r.register("squarev2",(function(){return new $o(e,new Io(d,s))})),r.register("masterpass",(function(){return new Qo(e,u,l,new yo(i),n)})),r.register("googlepayauthorizenet",(function(){return new jo(e,l,Yi(e,new Xi),c)})),r.register("googlepaybnz",(function(){return new jo(e,l,Yi(e,new eo),c)})),r.register("googlepaybraintree",(function(){return new jo(e,l,Yi(e,new to(m)),c)})),r.register("googlepaycheckoutcom",(function(){return new jo(e,l,Yi(e,new ro(t)),c)})),r.register("googlepaycybersourcev2",(function(){return new jo(e,l,Yi(e,new oo),c)})),r.register("googlepayorbital",(function(){return new jo(e,l,Yi(e,new so),c)})),r.register("googlepaystripe",(function(){return new jo(e,l,Yi(e,new uo),c)})),r.register("googlepaystripeupe",(function(){return new jo(e,l,Yi(e,new po),c)})),r.register("googlepayworldpayaccess",(function(){return new jo(e,l,Yi(e,new mo),c)})),r.register("stripeupe",(function(){return new aa(e,new go(i),h,u,new Tr(new Rr(t),new Vt(t)))})),r.register("default",(function(){return new Vo(e,h)})),r}(l,d,s),k),new E,new ne(new ie(d)),new xp(new Hp(p,d)),w,new $t(new tn(d)),new Jc(function(e,t,n,r,i){var o=new tu(e,{defaultToken:Wc.CREDIT_CARD}),s=(0,a.getScriptLoader)(),c=new Ar,u=new nr(t),d=new g(new b(n),new Wr(new Jr(n))),l=Gc(ai(e)),p=function(e){var t=new Oi(e),n=new Pi(t),r=new Bu(n),i=new Tu;return new qu(n,r,i)}(s),h=new Vt(n),m=new sn(h),_=new Lr(r,new Br(n)),y=new Kn(new Xn(n),m),f=new qr(new Gr(n)),v=new In(Tn((0,a.createScriptLoader)())),w=new tr(u,y,c,v),C=new $t(new tn(n)),S=new wo(n),I=new F(new H(n)),P=new Kt(new Zt(n)),E=new Yt(h,I,P),A=new Io(S,E),O=new Jc(o,l,y,_),k=(0,xe.createFormPoster)(),T=Kl(k,v),M=new Yn(e),D=new ru(n);return o.register(Wc.ADYENV2_GOOGLEPAY,(function(){return new Qd(e,E,C,O,w,y,Yi(e,new Wi),new $d(e,w,new ou(s,(0,a.getStylesheetLoader)())))})),o.register(Wc.ADYENV3_GOOGLEPAY,(function(){return new Qd(e,E,C,O,w,y,Yi(e,new Ji),new tl(e,w,new su(s,(0,a.getStylesheetLoader)())))})),o.register(Wc.AFFIRM,(function(){return new lu(e,y,w,C,new pu)})),o.register(Wc.AFTERPAY,(function(){return new _u(e,m,y,w,C,S,f,new yu(s))})),o.register(Wc.AMAZONPAY,(function(){return new gu(e,O,y,w,Ci())})),o.register(Wc.AUTHORIZENET_GOOGLE_PAY,(function(){return new Qd(e,E,C,O,w,y,Yi(e,new Xi))})),o.register(Wc.BARCLAYS,(function(){return new Su(e,y,w,M,new $u(e,w,new cd(new ud(s))))})),o.register(Wc.BLUESNAPV2,(function(){return new Eu(e,y,w)})),o.register(Wc.BRAINTREE,(function(){return new Hu(e,y,w,C,p)})),o.register(Wc.BRAINTREE_GOOGLE_PAY,(function(){return new Qd(e,E,C,O,w,y,Yi(e,new to(new Pi(new Oi(s)))),void 0,new Pi(new Oi(s)))})),o.register(Wc.BRAINTREE_PAYPAL,(function(){return new Wu(e,y,w,C,p)})),o.register(Wc.BRAINTREE_VENMO,(function(){return new Ju(e,y,w,C,p)})),o.register(Wc.BRAINTREE_PAYPAL_CREDIT,(function(){return new Wu(e,y,w,C,p,!0)})),o.register(Wc.BRAINTREE_VISA_CHECKOUT,(function(){return new Qu(e,E,C,O,w,y,Mi(s,n),new Di(s))})),o.register(Wc.CBA_MPGS,(function(){return new md(e,y,w,M,C,new yd(s),i)})),o.register(Wc.CONVERGE,(function(){return new Ld(e,y,w,M,k)})),o.register(Wc.CLEARPAY,(function(){return new Rd(e,m,y,w,C,S,f,new Nd(s))})),o.register(Wc.CYBERSOURCE,(function(){return new xd(e,y,w,M,new ld(e,w,C,new cd(new ud(s))))})),o.register(Wc.CYBERSOURCEV2,(function(){return new Vd(e,y,w,M,new $u(e,w,new cd(new ud(s))))})),o.register(Wc.BNZ,(function(){return new Ou(e,y,w,M,new $u(e,w,new cd(new ud(s))))})),o.register(Wc.CYBERSOURCEV2_GOOGLE_PAY,(function(){return new Qd(e,E,C,O,w,y,Yi(e,new oo))})),o.register(Wc.BNZ_GOOGLEPAY,(function(){return new Qd(e,E,C,O,w,y,Yi(e,new eo))})),o.register(Wc.CHECKOUTCOM,(function(){return new Bd(e,y,w,M,k)})),o.register(Wc.CHECKOUTCOM_APM,(function(){return new Pd(e,y,w,M)})),o.register(Wc.CHECKOUTCOM_FAWRY,(function(){return new Ad(e,y,w,M)})),o.register(Wc.CHECKOUTCOM_GOOGLE_PAY,(function(){return new Qd(e,E,C,O,w,y,Yi(e,new ro(n)),new nl)})),o.register(Wc.CHECKOUTCOM_IDEAL,(function(){return new kd(e,y,w,M)})),o.register(Wc.CHECKOUTCOM_SEPA,(function(){return new Md(e,y,w,M)})),o.register(Wc.CHASE_PAY,(function(){return new vd(e,E,y,w,C,O,n,new Ri(s),new Tp(s))})),o.register(Wc.DIGITALRIVER,(function(){return new jd(e,C,y,w,f,new Kd(s,(0,a.getStylesheetLoader)()),d)})),o.register(Wc.KLARNA,(function(){return new cl(e,y,C,A,new ul(s))})),o.register(Wc.KLARNAV2,(function(){return new ll(e,y,A,new pl(s),new ml(n))})),o.register(Wc.HUMM,(function(){return new il(e,y,w,k,C)})),o.register(Wc.MASTERPASS,(function(){return new _l(e,y,w,new yo(s),i)})),o.register(Wc.MOLLIE,(function(){return new vl(M,e,new Cl(s),y,w)})),o.register(Wc.MONERIS,(function(){return new bl(M,e,y,w,f)})),o.register(Wc.OPY,(function(){return new Tl(e,y,C,D,w,new Nl(s))})),o.register(Wc.ORBITAL_GOOGLE_PAY,(function(){return new Qd(e,E,C,O,w,y,Yi(e,new so))})),o.register(Wc.PAYPAL,(function(){return new Fl(e,y,w,M,new ld(e,w,C,new cd(new ud(s))))})),o.register(Wc.PAYPAL_EXPRESS,(function(){return new Bl(e,y,new xl(s))})),o.register(Wc.PAYPAL_EXPRESS_CREDIT,(function(){return new Bl(e,y,new xl(s))})),o.register(Wc.PPSDK,(function(){return new Ql(e,y,np(e,y,n,T,M),new rp(n,T),new Zc("PPSDK"))})),o.register(Wc.QUADPAY,(function(){return new op(e,y,w,C,f,A,D)})),o.register(Wc.SAGE_PAY,(function(){return new ap(e,y,w,M,k)})),o.register(Wc.SQUARE,(function(){return new pp(e,E,y,w,C,O,n,new mp(s))})),o.register(Wc.STRIPE_GOOGLE_PAY,(function(){return new Qd(e,E,C,O,w,y,Yi(e,new uo))})),o.register(Wc.STRIPE_UPE_GOOGLE_PAY,(function(){return new Qd(e,E,C,O,w,y,Yi(e,new po))})),o.register(Wc.STRIPEV3,(function(){return new Op(e,C,w,y,new kp(s),f,M,i)})),o.register(Wc.STRIPE_UPE,(function(){return new vp(e,C,w,y,new go(s),f,d)})),o.register(Wc.WE_PAY,(function(){return new Mp(e,y,w,M,new Tp(s))})),o.register(Wc.WORLDPAYACCESS,(function(){return new Np(e,y,w,M)})),o.register(Wc.WORLDPAYACCESS_GOOGLE_PAY,(function(){return new Qd(e,E,C,O,w,y,Yi(e,new mo))})),o.register(Wc.ZIP,(function(){return new Fp(e,C,f,A,y,D,w)})),o}(l,p,d,y,s),O,w,v),new jp(new Wp(d)),new Jp(new Qp(d,{locale:s})),new $p(function(e,t){var n=new ce,r=new Vt(t),i=new Rr(t),o=new Tr(i,r),s=new $t(new tn(t)),c=(0,a.getScriptLoader)();return n.register("amazonpay",(function(){return new th(e,o,new $t(new tn(t)),Ci(),new $p(n))})),n.register("stripeupe",(function(){return new ih(e,new go(c),o,s)})),n.register("default",(function(){return new nh(e,o)})),n}(l,d)),new sh(new uh(d)),v,new qr(new Gr(d)),C,S,T)}function oy(e){return Object.prototype.hasOwnProperty.call(e,"cacheKey")}var ay=function(){function e(e){this._lastId=0,this._map={maps:[]},this._usedMaps=[],this._options=(0,s.__assign)({maxSize:0,isEqual:mh(),onExpire:Z.noop},e)}return e.prototype.getKey=function(){for(var e=[],t=0;t55?55:e<25?25:e}var Iy=function(){function e(e,t,n,r,i,o){this._store=e,this._checkoutActionCreator=t,this._cartRequestSender=n,this._braintreeSDKCreator=r,this._formPoster=i,this._window=o}return e.prototype.initialize=function(e){var t,n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d,l,p,_,y,f,g=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(r=e.braintreepaypal,i=e.containerId,o=e.methodId,c=(a=r||{}).messagingContainerId,u=a.onError,!o)throw new ae('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new ae('Unable to initialize payment because "options.containerId" argument is not provided.');if(!r)throw new ae('Unable to initialize payment because "options.braintreepaypal" argument is not provided.');if(!r.buyNowInitializeOptions)return[3,1];if(d=this._store.getState(),l=d.paymentMethods.getPaymentMethodOrThrow(o),!r.currencyCode)throw new ae('Unable to initialize payment because "options.braintreepaypal.currencyCode" argument is not provided.');return p=r.currencyCode,[3,3];case 1:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 2:d=s.sent(),l=d.paymentMethods.getPaymentMethodOrThrow(o),p=d.cart.getCartOrThrow().currency.code,s.label=3;case 3:if(!l.clientToken)throw new m(h.MissingPaymentMethod);return _={currency:p,intent:null===(t=l.initializationData)||void 0===t?void 0:t.intent,isCreditEnabled:null===(n=l.initializationData)||void 0===n?void 0:n.isCreditEnabled},y=function(e){g._renderPayPalComponents(e,r,i,o,Boolean(l.config.testMode))},f=function(e){return g._handleError(e,i,c,u)},this._braintreeSDKCreator.initialize(l.clientToken),[4,this._braintreeSDKCreator.getPaypalCheckout(_,y,f)];case 4:return s.sent(),[2]}}))}))},e.prototype.deinitialize=function(){return this._braintreeSDKCreator.teardown(),Promise.resolve()},e.prototype._renderPayPalComponents=function(e,t,n,r,i){var o=t.messagingContainerId;this._renderPayPalMessages(o),this._renderPayPalButton(e,t,n,r,i)},e.prototype._renderPayPalButton=function(e,t,n,r,i){var o=this,a=t.style,s=t.shouldProcessPayment,c=t.onAuthorizeError,u=this._window.paypal,d=null==u?void 0:u.FUNDING.PAYPAL;if(u&&d){var l=a?Cy(a):{},p=u.Buttons({env:i?"sandbox":"production",commit:!1,fundingSource:d,style:l,createOrder:function(){return o._setupPayment(e,t,r)},onApprove:function(t){return o._tokenizePayment(t,e,r,s,c)}});p.isEligible()&&p.render("#"+n)}else this._removeElement(n)},e.prototype._renderPayPalMessages=function(e){var t=e&&Boolean(document.getElementById(e)),n=this._window.paypal;if(n&&t){var r=this._store.getState().cart.getCartOrThrow();n.Messages({amount:r.cartAmount,placement:"cart"}).render("#"+e)}else this._removeElement(e)},e.prototype._setupPayment=function(e,t,n){var r,i;return(0,s.__awaiter)(this,void 0,void 0,(function(){var o,a,c,u,d,l,p,h,m,_,y,f;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:o=t.buyNowInitializeOptions,a=t.shippingAddress,c=t.onPaymentError,s.label=1;case 1:return s.trys.push([1,7,,8]),d=this,[4,this._createBuyNowCart({buyNowInitializeOptions:o})];case 2:return d._buyNowCart=s.sent(),this._buyNowCart?(u=this._store.getState(),[3,5]):[3,3];case 3:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 4:u=s.sent(),s.label=5;case 5:return l=u.customer.getCustomer(),p=u.paymentMethods.getPaymentMethodOrThrow(n),h=this._buyNowCart?this._buyNowCart.cartAmount:u.checkout.getCheckoutOrThrow().outstandingBalance,m=null!==(r=t.currencyCode)&&void 0!==r?r:u.config.getStoreConfigOrThrow().currency.code,_=a||(null==l?void 0:l.addresses[0]),y=_?Mo(_):void 0,[4,e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:y,amount:h,currency:m,offerCredit:!1,intent:null===(i=p.initializationData)||void 0===i?void 0:i.intent})];case 6:return[2,s.sent()];case 7:throw f=s.sent(),c&&c(f),f;case 8:return[2]}}))}))},e.prototype._createBuyNowCart=function(e){var t=e.buyNowInitializeOptions;return(0,s.__awaiter)(this,void 0,void 0,(function(){var e;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:if("function"!=typeof(null==t?void 0:t.getBuyNowCartRequestBody))return[3,4];if(!(e=t.getBuyNowCartRequestBody()))throw new m(h.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._cartRequestSender.createBuyNowCart(e)];case 2:return[2,n.sent().body];case 3:throw n.sent(),new _y;case 4:return[2]}}))}))},e.prototype._tokenizePayment=function(e,t,n,r,i){var o;return(0,s.__awaiter)(this,void 0,void 0,(function(){var a,c,u,d,l,p;return(0,s.__generator)(this,(function(h){switch(h.label){case 0:return h.trys.push([0,3,,4]),[4,this._braintreeSDKCreator.getDataCollector({paypal:!0})];case 1:return a=h.sent().deviceData,[4,t.tokenizePayment(e)];case 2:return c=h.sent(),u=c.details,d=c.nonce,l=null===(o=this._buyNowCart)||void 0===o?void 0:o.id,this._formPoster.postForm("/checkout.php",(0,s.__assign)({payment_type:"paypal",provider:n,action:r?"process_payment":"set_external_checkout",nonce:d,device_data:a,billing_address:JSON.stringify(ko(u)),shipping_address:JSON.stringify(To(u))},l&&{cart_id:l})),[2,c];case 3:throw p=h.sent(),i&&i(p),p;case 4:return[2]}}))}))},e.prototype._handleError=function(e,t,n,r){this._removeElement(t),this._removeElement(n),r&&r(e)},e.prototype._removeElement=function(e){var t=e&&document.getElementById(e);t&&t.remove()},e}();const by=Iy;var Py=function(){function e(e,t,n,r,i,o){this._store=e,this._checkoutActionCreator=t,this._cartRequestSender=n,this._braintreeSDKCreator=r,this._formPoster=i,this._window=o}return e.prototype.initialize=function(e){var t,n;return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d,l,p,_=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(r=e.braintreepaypalcredit,i=e.containerId,!(o=e.methodId))throw new ae('Unable to initialize payment because "options.methodId" argument is not provided.');if(!i)throw new ae('Unable to initialize payment because "options.containerId" argument is not provided.');if(!r)throw new ae('Unable to initialize payment because "options.braintreepaypalcredit" argument is not provided.');if(!r.buyNowInitializeOptions)return[3,1];if(a=this._store.getState(),c=a.paymentMethods.getPaymentMethodOrThrow(o),!r.currencyCode)throw new ae('Unable to initialize payment because "options.braintreepaypalcredit.currencyCode" argument is not provided.');return u=r.currencyCode,[3,3];case 1:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 2:a=s.sent(),c=a.paymentMethods.getPaymentMethodOrThrow(o),u=a.cart.getCartOrThrow().currency.code,s.label=3;case 3:if(!c.clientToken)throw new m(h.MissingPaymentMethod);return d={currency:u,intent:null===(t=c.initializationData)||void 0===t?void 0:t.intent,isCreditEnabled:null===(n=c.initializationData)||void 0===n?void 0:n.isCreditEnabled},l=function(e){return _._renderPayPalButton(e,r,i,o,Boolean(c.config.testMode))},p=function(e){return _._handleError(e,i,r.onError)},this._braintreeSDKCreator.initialize(c.clientToken),[4,this._braintreeSDKCreator.getPaypalCheckout(d,l,p)];case 4:return s.sent(),[2]}}))}))},e.prototype.deinitialize=function(){return this._braintreeSDKCreator.teardown(),Promise.resolve()},e.prototype._renderPayPalButton=function(e,t,n,r,i){var o=this,a=t.style,c=t.shouldProcessPayment,u=t.onAuthorizeError,d=this._window.paypal,l=!1;if(d){var p=[d.FUNDING.PAYLATER,d.FUNDING.CREDIT],h=a?Cy(a):{};p.forEach((function(a){var p=a===d.FUNDING.CREDIT?(0,s.__assign)({label:No.CREDIT},h):h;if(!l){var m=d.Buttons({env:i?"sandbox":"production",commit:!1,fundingSource:a,style:p,createOrder:function(){return o._setupPayment(e,t,r)},onApprove:function(t){return o._tokenizePayment(t,e,r,c,u)}});m.isEligible()&&(m.render("#"+n),l=!0)}}))}d&&l||this._removeElement(n)},e.prototype._setupPayment=function(e,t,n){var r,i;return(0,s.__awaiter)(this,void 0,void 0,(function(){var o,a,c,u,d,l,p,h,m,_,y,f;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:o=t.onPaymentError,a=t.shippingAddress,c=t.buyNowInitializeOptions,s.label=1;case 1:return s.trys.push([1,7,,8]),d=this,[4,this._createBuyNowCart({buyNowInitializeOptions:c})];case 2:return d._buyNowCart=s.sent(),this._buyNowCart?(u=this._store.getState(),[3,5]):[3,3];case 3:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 4:u=s.sent(),s.label=5;case 5:return l=u.customer.getCustomer(),p=u.paymentMethods.getPaymentMethodOrThrow(n),h=this._buyNowCart?this._buyNowCart.cartAmount:u.checkout.getCheckoutOrThrow().outstandingBalance,m=null!==(r=t.currencyCode)&&void 0!==r?r:u.config.getStoreConfigOrThrow().currency.code,_=a||(null==l?void 0:l.addresses[0]),y=_?Mo(_):void 0,[4,e.createPayment({flow:"checkout",enableShippingAddress:!0,shippingAddressEditable:!1,shippingAddressOverride:y,amount:h,currency:m,offerCredit:!0,intent:null===(i=p.initializationData)||void 0===i?void 0:i.intent})];case 6:return[2,s.sent()];case 7:throw f=s.sent(),o&&o(f),f;case 8:return[2]}}))}))},e.prototype._createBuyNowCart=function(e){var t=e.buyNowInitializeOptions;return(0,s.__awaiter)(this,void 0,void 0,(function(){var e;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:if("function"!=typeof(null==t?void 0:t.getBuyNowCartRequestBody))return[3,4];if(!(e=t.getBuyNowCartRequestBody()))throw new m(h.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._cartRequestSender.createBuyNowCart(e)];case 2:return[2,n.sent().body];case 3:throw n.sent(),new _y;case 4:return[2]}}))}))},e.prototype._tokenizePayment=function(e,t,n,r,i){var o;return(0,s.__awaiter)(this,void 0,void 0,(function(){var a,c,u,d,l,p;return(0,s.__generator)(this,(function(h){switch(h.label){case 0:return h.trys.push([0,3,,4]),[4,this._braintreeSDKCreator.getDataCollector({paypal:!0})];case 1:return a=h.sent().deviceData,[4,t.tokenizePayment(e)];case 2:return c=h.sent(),u=c.details,d=c.nonce,l=null===(o=this._buyNowCart)||void 0===o?void 0:o.id,this._formPoster.postForm("/checkout.php",(0,s.__assign)({payment_type:"paypal",provider:n,action:r?"process_payment":"set_external_checkout",nonce:d,device_data:a,billing_address:JSON.stringify(ko(u)),shipping_address:JSON.stringify(To(u))},l&&{cart_id:l})),[2,c];case 3:throw p=h.sent(),i&&i(p),p;case 4:return[2]}}))}))},e.prototype._handleError=function(e,t,n){this._removeElement(t),n&&n(e)},e.prototype._removeElement=function(e){var t=e&&document.getElementById(e);t&&t.remove()},e}();const Ey=Py;var Ay={backgroundColor:"#3D95CE",backgroundPosition:"50% 50%",backgroundSize:"80px auto",backgroundImage:'url("/app/assets/img/payment-providers/venmo-logo-white.svg")',backgroundRepeat:"no-repeat",borderRadius:"4px",cursor:"pointer",transition:"0.2s ease",minHeight:"40px",minWidth:"150px",height:"100%",width:"100%"},Oy=function(){function e(e,t,n,r,i){this._store=e,this._paymentMethodActionCreator=t,this._cartRequestSender=n,this._braintreeSDKCreator=r,this._formPoster=i,this._onError=Z.noop}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a=this;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.braintreevenmo,n=e.containerId,!(r=e.methodId))throw new ae('Unable to initialize payment because "options.methodId" argument is not provided.');return[4,this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(r))];case 1:if(i=s.sent(),!(o=i.paymentMethods.getPaymentMethodOrThrow(r)).clientToken)throw new m(h.MissingPaymentMethod);if(!n)throw new ae('Unable to initialize payment because "options.containerId" argument is not provided.');return this._onError=(null==t?void 0:t.onError)||this._handleError,this._braintreeSDKCreator.initialize(o.clientToken),[4,this._braintreeSDKCreator.getVenmoCheckout((function(e){return a._handleInitializationVenmoSuccess(e,n,null==t?void 0:t.buyNowInitializeOptions)}),(function(e){return a._handleInitializationVenmoError(e,n)}))];case 2:return s.sent(),[2]}}))}))},e.prototype.deinitialize=function(){return this._braintreeSDKCreator.teardown(),Promise.resolve()},e.prototype._handleError=function(e){throw new Error(e.message)},e.prototype._handleInitializationVenmoSuccess=function(e,t,n){return this._renderVenmoButton(e,t,n)},e.prototype._handleInitializationVenmoError=function(e,t){return this._removeVenmoContainer(t),this._onError(e)},e.prototype._removeVenmoContainer=function(e){var t=document.getElementById(e);t&&t.remove()},e.prototype._renderVenmoButton=function(e,t,n){var r=this,i=document.getElementById(t);if(!i)throw new ae("Unable to create wallet button without valid container ID.");i.setAttribute("aria-label","Venmo"),Object.assign(i.style,Ay),i.addEventListener("click",(function(){return(0,s.__awaiter)(r,void 0,void 0,(function(){var t,r=this;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:return i.setAttribute("disabled","true"),[4,this._createBuyNowCart(n)];case 1:return t=o.sent(),e.tokenize&&e.tokenize((function(e,n){return(0,s.__awaiter)(r,void 0,void 0,(function(){return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return i.removeAttribute("disabled"),e?[2,this._onError(e)]:[4,this._handlePostForm(n,null==t?void 0:t.id)];case 1:return r.sent(),[2]}}))}))})),[2]}}))}))})),i.addEventListener("mouseenter",(function(){i.style.backgroundColor="#0a7fc2"})),i.addEventListener("mouseleave",(function(){i.style.backgroundColor=Ay.backgroundColor}))},e.prototype._createBuyNowCart=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:if("function"!=typeof(null==e?void 0:e.getBuyNowCartRequestBody))return[3,4];if(!(t=e.getBuyNowCartRequestBody()))throw new m(h.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._cartRequestSender.createBuyNowCart(t)];case 2:return[2,n.sent().body];case 3:throw n.sent(),new _y;case 4:return[2]}}))}))},e.prototype._handlePostForm=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i;return(0,s.__generator)(this,(function(o){switch(o.label){case 0:return[4,this._braintreeSDKCreator.getDataCollector()];case 1:return n=o.sent().deviceData,r=e.nonce,i=e.details,this._formPoster.postForm("/checkout.php",(0,s.__assign)({nonce:r,provider:mr.BRAINTREE_VENMO,payment_type:"paypal",device_data:n,action:"set_external_checkout",billing_address:JSON.stringify(ko(i)),shipping_address:JSON.stringify(To(i))},t&&{cart_id:t})),[2]}}))}))},e}();const ky=Oy;var Ty=function(){function e(e,t,n,r,i){this._store=e,this._formPoster=t,this._checkoutActionCreator=n,this._googlePayPaymentProcessor=r,this._cartRequestSender=i}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.containerId,n=e.methodId,r=e.currencyCode,i=this._getGooglePayOptions(e),o=i.buyNowInitializeOptions,!t||!n)throw new ye('Unable to proceed because "containerId" argument is not provided.');if(a=this._store.getState(),c=a.paymentMethods.getPaymentMethod(n),u=((null==c?void 0:c.config)||{}).testMode,this._methodId=n,this._isBuyNowFlow=!!o,!this._isBuyNowFlow)return[3,2];if(!r)throw new ye('Unable to initialize payment because "options.currencyCode" argument is not provided.');return d=i.buyNowInitializeOptions,this._googlePayPaymentProcessor.updateBuyNowFlowFlag(this._isBuyNowFlow),[4,this._googlePayPaymentProcessor.initialize(this._getMethodId(),this._getGooglePayClientOptions(r,u,d))];case 1:return s.sent(),[3,5];case 2:return[4,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout())];case 3:return s.sent(),[4,this._googlePayPaymentProcessor.initialize(this._getMethodId())];case 4:s.sent(),s.label=5;case 5:return this._walletButton=this._createSignInButton(t,i,r),[2]}}))}))},e.prototype.deinitialize=function(){return this._walletButton&&this._walletButton.parentNode&&(this._walletButton.parentNode.removeChild(this._walletButton),this._walletButton=void 0),this._googlePayPaymentProcessor.deinitialize()},e.prototype._getGooglePayClientOptions=function(e,t,n){var r=this;return{environment:t?"TEST":"PRODUCTION",paymentDataCallbacks:{onPaymentDataChanged:function(t){var i=t.callbackTrigger;return(0,s.__awaiter)(r,void 0,void 0,(function(){var t,r,o,a,c;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(i!==Ni.INITIALIZE)return[2];s.label=1;case 1:return s.trys.push([1,5,,6]),t=this,[4,this._createBuyNowCart(n)];case 2:return t._buyNowCart=s.sent(),this._buyNowCart?(r=this._buyNowCart,o=r.id,a=r.cartAmount,[4,this._store.dispatch(this._checkoutActionCreator.loadCheckout(o))]):[3,4];case 3:return s.sent(),[2,{newTransactionInfo:{currencyCode:e,totalPrice:String(a),totalPriceStatus:Li.FINAL}}];case 4:return[3,6];case 5:throw c=s.sent(),new _y(c);case 6:return[2]}}))}))}}}},e.prototype._createSignInButton=function(e,t,n){var r=this,i=document.getElementById(e),o=t.buttonType,a=t.buttonColor;if(!i)throw new ye("Unable to create sign-in button without valid container ID.");var s=this._googlePayPaymentProcessor.createButton((function(e){return r._handleWalletButtonClick(e,n)}),o,a);return i.appendChild(s),s},e.prototype._getMethodId=function(){if(!this._methodId)throw new Ee(Pe.PaymentNotInitialized);return this._methodId},e.prototype._getGooglePayOptions=function(e){if(e.methodId===mr.GOOGLEPAY_ADYENV2&&e.googlepayadyenv2)return e.googlepayadyenv2;if(e.methodId===mr.GOOGLEPAY_ADYENV3&&e.googlepayadyenv3)return e.googlepayadyenv3;if(e.methodId===mr.GOOGLEPAY_AUTHORIZENET&&e.googlepayauthorizenet)return e.googlepayauthorizenet;if(e.methodId===mr.GOOGLEPAY_BNZ&&e.googlepaybnz)return e.googlepaybnz;if(e.methodId===mr.GOOGLEPAY_BRAINTREE&&e.googlepaybraintree)return e.googlepaybraintree;if(e.methodId===mr.GOOGLEPAY_CHECKOUTCOM&&e.googlepaycheckoutcom)return e.googlepaycheckoutcom;if(e.methodId===mr.GOOGLEPAY_CYBERSOURCEV2&&e.googlepaycybersourcev2)return e.googlepaycybersourcev2;if(e.methodId===mr.GOOGLEPAY_ORBITAL&&e.googlepayorbital)return e.googlepayorbital;if(e.methodId===mr.GOOGLEPAY_STRIPE&&e.googlepaystripe)return e.googlepaystripe;if(e.methodId===mr.GOOGLEPAY_STRIPEUPE&&e.googlepaystripeupe)return e.googlepaystripeupe;if(e.methodId===mr.GOOGLEPAY_WORLDPAYACCESS&&e.googlepayworldpayaccess)return e.googlepayworldpayaccess;throw new ye},e.prototype._createBuyNowCart=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:if("function"!=typeof(null==e?void 0:e.getBuyNowCartRequestBody))return[3,4];if(!(t=e.getBuyNowCartRequestBody()))throw new me(he.MissingCart);n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._cartRequestSender.createBuyNowCart(t)];case 2:return[2,n.sent().body];case 3:throw n.sent(),new _y;case 4:return[2]}}))}))},e.prototype._handleWalletButtonClick=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:e.preventDefault(),i.label=1;case 1:return i.trys.push([1,7,,8]),this._isBuyNowFlow&&t&&this._googlePayPaymentProcessor.updatePaymentDataRequest({transactionInfo:{currencyCode:t,totalPrice:"0",totalPriceStatus:Li.ESTIMATED},callbackIntents:[Fi.OFFER]}),[4,this._googlePayPaymentProcessor.displayWallet()];case 2:return n=i.sent(),[4,this._googlePayPaymentProcessor.handleSuccess(n)];case 3:return i.sent(),si(this._store.getState().cart.getCartOrThrow())>0&&n.shippingAddress?[4,this._googlePayPaymentProcessor.updateShippingAddress(n.shippingAddress)]:[3,5];case 4:i.sent(),i.label=5;case 5:return[4,this._onPaymentSelectComplete()];case 6:return i.sent(),[3,8];case 7:if((r=i.sent())&&"CANCELED"!==r.message)throw r;return[3,8];case 8:return[2]}}))}))},e.prototype._onPaymentSelectComplete=function(){var e,t=null===(e=this._buyNowCart)||void 0===e?void 0:e.id;this._formPoster.postForm("/checkout.php",(0,s.__assign)({headers:(0,s.__assign)({Accept:"text/html","Content-Type":"application/x-www-form-urlencoded"},C)},t&&{action:"set_external_checkout",provider:this._methodId,cart_id:t}))},(0,s.__decorate)([yn],e.prototype,"_handleWalletButtonClick",null),e}();const My=Ty,Dy=function(){function e(e,t,n,r){this._store=e,this._checkoutActionCreator=t,this._masterpassScriptLoader=n,this._locale=r}return e.prototype.initialize=function(e){var t=this,n=e.containerId,r=e.methodId;if(!n||!r)throw new ae('Unable to proceed because "containerId" argument is not provided.');return this._methodId=r,this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()).then((function(e){var n=e.paymentMethods.getPaymentMethod(r);if(!n||!n.initializationData.checkoutId)throw new m(h.MissingPaymentMethod);var i={useMasterpassSrc:n.initializationData.isMasterpassSrcEnabled,language:Jo(t._locale),testMode:n.config.testMode,checkoutId:n.initializationData.checkoutId};return t._masterpassScriptLoader.load(i)})).then((function(e){t._masterpassClient=e,t._signInButton=t._createSignInButton(n)}))},e.prototype.deinitialize=function(){return this._signInButton&&this._signInButton.parentNode&&(this._signInButton.removeEventListener("click",this._handleWalletButtonClick),this._signInButton.parentNode.removeChild(this._signInButton),this._signInButton=void 0),Promise.resolve()},e.prototype._createSignInButton=function(e){var t=document.getElementById(e),n=this._store.getState(),r=this._methodId?n.paymentMethods.getPaymentMethod(this._methodId):null,i=n.config.getStoreConfig();if(!t)throw new Error("Need a container to place the button");if(!r)throw new m(h.MissingPaymentMethod);if(!i)throw new ae("Unable to retrieve store configuration");var o=document.createElement("input");if(o.type="image",r.initializationData.isMasterpassSrcEnabled){var a=r.config.testMode?"sandbox.":"",s=r.initializationData.checkoutId,c=["locale="+Jo(this._locale),"paymentmethod=master,visa,amex,discover","checkoutid="+s];o.src=["https://"+a+"src.mastercard.com/assets/img/btn/src_chk_btn_126x030px.svg",c.join("&")].join("?")}else o.src="https://static.masterpass.com/dyn/img/btn/global/mp_chk_btn_160x037px.svg";return t.appendChild(o),o.addEventListener("click",this._handleWalletButtonClick),o},e.prototype._createMasterpassPayload=function(){var e=this._store.getState(),t=e.checkout.getCheckout(),n=this._methodId?e.paymentMethods.getPaymentMethod(this._methodId):null;if(!t)throw new m(h.MissingCheckout);if(!n)throw new m(h.MissingPaymentMethod);return{checkoutId:n.initializationData.checkoutId,allowedCardTypes:n.initializationData.allowedCardTypes,amount:t.cart.cartAmount.toString(),currency:t.cart.currency.code,cartId:t.cart.id,callbackUrl:Wo("cart")}},e.prototype._handleWalletButtonClick=function(){if(!this._masterpassClient)throw new Pn(bn.CheckoutButtonNotInitialized);this._masterpassClient.checkout(this._createMasterpassPayload())},(0,s.__decorate)([yn],e.prototype,"_handleWalletButtonClick",null),e}();var Ry=function(){function e(e,t,n,r,i){void 0===i&&(i=""),this._store=e,this._checkoutActionCreator=t,this._paypalScriptLoader=n,this._formPoster=r,this._host=i}return e.prototype.initialize=function(e){var t=this,n=e.paypal,r=this._store.getState(),i=this._paymentMethod=r.paymentMethods.getPaymentMethod(e.methodId);if(!n)throw new ae;if(!i)throw new m(h.MissingPaymentMethod);return this._paypalScriptLoader.loadPaypal(i.config.merchantId).then((function(r){var o,a,c;if(!i||!i.config.merchantId)throw new m(h.MissingPaymentMethod);var u=i.config.merchantId,d=i.config.testMode?"sandbox":"production",l=((o={})[d]=n.clientId,o),p=r.FUNDING.CREDIT||"credit",_=n.allowCredit?[p]:[],y=n.allowCredit?[]:[p];return r.Button.render({env:d,client:l,commit:n.shouldProcessPayment,funding:{allowed:_,disallowed:y},style:(0,s.__assign)((0,s.__assign)({shape:Lo.RECT},(0,Z.pick)(n.style,"layout","color","label","shape","tagline","fundingicons")),{size:"paypalexpress"===i.id&&"small"===(null===(a=n.style)||void 0===a?void 0:a.size)?Ro.RESPONSIVE:null===(c=n.style)||void 0===c?void 0:c.size}),payment:function(e,r){return t._setupPayment(u,r,n.onPaymentError)},onAuthorize:function(e,r){return t._tokenizePayment(e,r,n.shouldProcessPayment,n.onAuthorizeError)}},e.containerId)}))},e.prototype.deinitialize=function(){return this._paymentMethod=void 0,Promise.resolve()},e.prototype._setupPayment=function(e,t,n){var r=this;if(!t)throw new Pn(bn.CheckoutButtonNotInitialized);return this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout()).then((function(n){var i=n.cart.getCart(),o=i?i.id:"";return t.request.post(r._host+"/api/storefront/payment/paypalexpress",{merchantId:e,cartId:o},{headers:(0,s.__assign)({"X-API-INTERNAL":V},C)})})).then((function(e){return e.id})).catch((function(e){throw n&&n(e),e}))},e.prototype._tokenizePayment=function(e,t,n,r){var i=this;if(!this._paymentMethod)throw new Pn(bn.CheckoutButtonNotInitialized);if(!t)throw new Pn(bn.CheckoutButtonNotInitialized);if(!e.paymentID||!e.payerID)throw new m(h.MissingPayment);var o=this._paymentMethod.id;return t.payment.get(e.paymentID).then((function(t){i._formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:o,action:n?"process_payment":"set_external_checkout",paymentId:e.paymentID,payerId:e.payerID,payerInfo:JSON.stringify(t.payer.payer_info)})}))},e}();const zy=Ry;var Ny;!function(e){e.Subtotal="Subtotal",e.Shipping="Shipping"}(Ny||(Ny={}));var Ly=function(){function e(e,t,n){this._requestSender=e,this._paymentIntegrationService=t,this._sessionFactory=n,this._onAuthorizeCallback=Z.noop,this._subTotalLabel=Ny.Subtotal,this._shippingLabel=Ny.Shipping}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.methodId,n=e.containerId,r=e.applepay,ge(window),!t||!r)throw new me(he.MissingPaymentMethod);return i=r.buttonClassName,o=r.onPaymentAuthorize,a=r.buyNowInitializeOptions,c=r.requiresShipping,this._requiresShipping=c,this._buyNowInitializeOptions=a,this._onAuthorizeCallback=o,a?[3,2]:[4,this._paymentIntegrationService.loadDefaultCheckout()];case 1:s.sent(),s.label=2;case 2:return[4,this._paymentIntegrationService.loadPaymentMethod(t)];case 3:return s.sent(),u=this._paymentIntegrationService.getState(),this._paymentMethod=u.getPaymentMethodOrThrow(t),[4,this._paymentIntegrationService.verifyCheckoutSpamProtection()];case 4:return s.sent(),this._applePayButton=this._createButton(n,i),this._applePayButton.addEventListener("click",this._handleWalletButtonClick.bind(this)),[2,Promise.resolve()]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype._createButton=function(e,t){void 0===t&&(t="apple-pay-checkout-button");var n=document.getElementById(e);if(!n)throw new ye("Unable to create wallet button without valid container ID.");document.body.classList.add("apple-pay-supported");var r=document.createElement("div");return r.setAttribute("class",t),r.setAttribute("role","button"),r.setAttribute("aria-label","Apple Pay button"),n.appendChild(r),r},e.prototype._handleWalletButtonClick=function(e){var t;return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a,c,u,d,l,p,h,m;return(0,s.__generator)(this,(function(s){if(e.preventDefault(),!this._paymentMethod||!this._paymentMethod.initializationData)throw new me(he.MissingPaymentMethod);return this._buyNowInitializeOptions&&"function"==typeof this._buyNowInitializeOptions.getBuyNowCartRequestBody?(n=this._paymentMethod.initializationData,r=n.countryCode,i=n.currencyCode,o=n.merchantCapabilities,a=n.supportedNetworks,c=n.storeName,h=this._getRequestWithEmptyTotal(r,i,a,o),this._requiresShipping&&(null===(t=h.requiredShippingContactFields)||void 0===t||t.push("postalAddress")),m=this._sessionFactory.create(h),this._handleApplePayEvents(m,this._paymentMethod,c),m.begin()):(u=this._paymentIntegrationService.getState(),d=u.getCartOrThrow(),l=u.getStoreConfigOrThrow(),p=u.getCheckoutOrThrow(),h=this._getBaseRequest(d,p,l,this._paymentMethod),m=this._sessionFactory.create(h),this._handleApplePayEvents(m,this._paymentMethod,l.storeProfile.storeName),m.begin()),[2]}))}))},e.prototype._getRequestWithEmptyTotal=function(e,t,n,r){return{countryCode:e,currencyCode:t,supportedNetworks:n,merchantCapabilities:r,total:{label:"",amount:"0",type:"pending"},requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"]}},e.prototype._getBaseRequest=function(e,t,n,r){var i,o=n.storeProfile,a=o.storeCountryCode,s=o.storeName,c=e.currency,u=c.code,d=c.decimalPlaces,l=r.initializationData,p=l.merchantCapabilities,h=l.supportedNetworks,m=e.lineItems.physicalItems.length>0,_={requiredBillingContactFields:["postalAddress"],requiredShippingContactFields:["email","phone"],countryCode:a,currencyCode:u,merchantCapabilities:p,supportedNetworks:h,lineItems:[],total:m?{label:s,amount:""+t.grandTotal.toFixed(d),type:"pending"}:{label:s,amount:""+t.grandTotal.toFixed(d),type:"final"}};if(m)null===(i=_.requiredShippingContactFields)||void 0===i||i.push("postalAddress");else{var y=[{label:this._subTotalLabel,amount:""+t.subtotal.toFixed(d)}];t.taxes.forEach((function(e){return y.push({label:e.name,amount:""+e.amount.toFixed(d)})})),_.lineItems=y}return _},e.prototype._handleApplePayEvents=function(e,t,n){var r=this;e.onvalidatemerchant=function(n){return(0,s.__awaiter)(r,void 0,void 0,(function(){var r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this._onValidateMerchant(t,n)];case 1:return r=i.sent().body,e.completeMerchantValidation(r),[3,3];case 2:throw i.sent(),new Error("Merchant validation failed");case 3:return[2]}}))}))},this._buyNowInitializeOptions&&!this._requiresShipping&&(e.onpaymentmethodselected=function(){return(0,s.__awaiter)(r,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){switch(t.label){case 0:return[4,this._createBuyNowCart()];case 1:return t.sent(),this._handlePaymentMethodSelected(e),[2]}}))}))}),e.onshippingcontactselected=function(t){return(0,s.__awaiter)(r,void 0,void 0,(function(){return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return this._buyNowInitializeOptions&&this._requiresShipping?[4,this._createBuyNowCart()]:[3,2];case 1:r.sent(),r.label=2;case 2:return[4,this._handleShippingContactSelected(e,n,t)];case 3:return r.sent(),[2]}}))}))},e.onshippingmethodselected=function(t){return(0,s.__awaiter)(r,void 0,void 0,(function(){return(0,s.__generator)(this,(function(r){switch(r.label){case 0:return[4,this._handleShippingMethodSelected(e,n,t)];case 1:return r.sent(),[2]}}))}))},e.oncancel=function(){return(0,s.__awaiter)(r,void 0,void 0,(function(){var e;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return n.trys.push([0,3,,4]),e="/remote-checkout/"+t.id+"/signout",[4,this._requestSender.get(e)];case 1:return n.sent(),[4,this._paymentIntegrationService.loadCheckout()];case 2:return[2,n.sent()];case 3:throw n.sent(),new fe;case 4:return[2]}}))}))},e.onpaymentauthorized=function(n){return(0,s.__awaiter)(r,void 0,void 0,(function(){return(0,s.__generator)(this,(function(r){return[2,this._onPaymentAuthorized(n,e,t)]}))}))}},e.prototype._createBuyNowCart=function(){var e,t;return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:if(i.trys.push([0,3,,4]),!(n=null===(t=null===(e=this._buyNowInitializeOptions)||void 0===e?void 0:e.getBuyNowCartRequestBody)||void 0===t?void 0:t.call(e)))throw new me(he.MissingCart);return[4,this._paymentIntegrationService.createBuyNowCart(n)];case 1:return r=i.sent(),[4,this._paymentIntegrationService.loadCheckout(r.id)];case 2:return i.sent(),[3,4];case 3:throw i.sent(),new rt;case 4:return[2]}}))}))},e.prototype._handlePaymentMethodSelected=function(e){var t=this._paymentIntegrationService.getState(),n=t.getCartOrThrow(),r=t.getStoreConfigOrThrow(),i=t.getCheckoutOrThrow();if(!this._paymentMethod||!this._paymentMethod.initializationData)throw new me(he.MissingPaymentMethod);var o=this._getBaseRequest(n,i,r,this._paymentMethod);delete o.total.type,e.completePaymentMethodSelection({newTotal:o.total,newLineItems:o.lineItems})},e.prototype._handleShippingContactSelected=function(e,t,n){var r;return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u,d,l,p,h,m,_,y;return(0,s.__generator)(this,(function(f){switch(f.label){case 0:i=this._transformContactToAddress(n.shippingContact),f.label=1;case 1:return f.trys.push([1,3,,4]),[4,this._paymentIntegrationService.updateShippingAddress(i)];case 2:return f.sent(),[3,4];case 3:throw f.sent(),e.abort(),new Error("Shipping address update failed");case 4:if(o=this._paymentIntegrationService.getState(),a=o.getCartOrThrow().currency.decimalPlaces,c=o.getCheckoutOrThrow(),u=null===(r=c.consignments[0].selectedShippingOption)||void 0===r?void 0:r.id,d=c.consignments[0].availableShippingOptions,l=null==d?void 0:d.find((function(e){return e.id===u})),p=null==d?void 0:d.filter((function(e){return e.id!==u})),h=l?[{label:l.description,amount:""+l.cost.toFixed(a),detail:l.additionalDescription,identifier:l.id}]:[],p&&(0,s.__spreadArrays)(p.filter((function(e){return e.isRecommended})),p.filter((function(e){return!e.isRecommended}))).forEach((function(e){return h.push({label:e.description,amount:""+e.cost.toFixed(a),detail:e.additionalDescription,identifier:e.id})})),!(d instanceof Array))throw new Error("Shipping options not available.");if(0===d.length)return e.completeShippingContactSelection(ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,[],{type:"pending",label:t,amount:""+c.grandTotal.toFixed(a)},[]),[2];m=d.find((function(e){return e.isRecommended})),_=m?m.id:d[0].id,y=l?l.id:_,f.label=5;case 5:return f.trys.push([5,7,,8]),[4,this._updateShippingOption(y)];case 6:return f.sent(),[3,8];case 7:throw f.sent(),new Error("Shipping options update failed");case 8:return o=this._paymentIntegrationService.getState(),c=o.getCheckoutOrThrow(),e.completeShippingContactSelection({newShippingMethods:h,newTotal:{type:"final",label:t,amount:""+c.grandTotal.toFixed(a)},newLineItems:this._getUpdatedLineItems(c,a)}),[2]}}))}))},e.prototype._handleShippingMethodSelected=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:r=n.shippingMethod.identifier,s.label=1;case 1:return s.trys.push([1,3,,4]),[4,this._updateShippingOption(r)];case 2:return s.sent(),[3,4];case 3:throw s.sent(),e.abort(),new Error("Shipping option selection update failed.");case 4:return i=this._paymentIntegrationService.getState(),o=i.getCartOrThrow().currency.decimalPlaces,a=i.getCheckoutOrThrow(),e.completeShippingMethodSelection({newTotal:{type:"final",label:t,amount:""+a.grandTotal.toFixed(o)},newLineItems:this._getUpdatedLineItems(a,o)}),[2]}}))}))},e.prototype._getUpdatedLineItems=function(e,t){var n=[{label:this._subTotalLabel,amount:""+e.subtotal.toFixed(t)}];return e.taxes.forEach((function(e){return n.push({label:e.name,amount:""+e.amount.toFixed(t)})})),n.push({label:this._shippingLabel,amount:""+e.shippingCostTotal.toFixed(t)}),n},e.prototype._updateShippingOption=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){return(0,s.__generator)(this,(function(t){return[2,this._paymentIntegrationService.selectShippingOption(e)]}))}))},e.prototype._onValidateMerchant=function(e,t){return(0,s.__awaiter)(this,void 0,void 0,(function(){var n;return(0,s.__generator)(this,(function(r){return n=["validationUrl="+t.validationURL,"merchantIdentifier="+e.initializationData.merchantId,"displayName="+e.initializationData.storeName,"domainName="+window.location.hostname].join("&"),[2,this._requestSender.post((i=e.initializationData.paymentsUrl,i+"/api/public/v1/payments/applepay/validate_merchant"),{credentials:!1,headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","X-XSRF-TOKEN":null},body:n})];var i}))}))},e.prototype._onPaymentAuthorized=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a,c,u,d,l,p,h,m,_;return(0,s.__generator)(this,(function(y){switch(y.label){case 0:r=e.payment,i=r.token,o=r.billingContact,a=r.shippingContact,c=this._paymentIntegrationService.getState(),u=c.getCartOrThrow(),d=u.lineItems.physicalItems.length>0,l={methodId:n.id,paymentData:{formattedPayload:{apple_pay_token:{payment_data:i.paymentData,payment_method:i.paymentMethod,transaction_id:i.transactionIdentifier}}}},p=this._transformContactToAddress(o),h=this._transformContactToAddress(a),m=null==a?void 0:a.emailAddress,_=(null==a?void 0:a.phoneNumber)||"",y.label=1;case 1:return y.trys.push([1,7,,8]),[4,this._paymentIntegrationService.updateBillingAddress((0,s.__assign)((0,s.__assign)({},p),{email:m,phone:_}))];case 2:return y.sent(),d?[4,this._paymentIntegrationService.updateShippingAddress(h)]:[3,4];case 3:y.sent(),y.label=4;case 4:return[4,this._paymentIntegrationService.submitOrder({useStoreCredit:!1})];case 5:return y.sent(),[4,this._paymentIntegrationService.submitPayment(l)];case 6:return y.sent(),t.completePayment(ApplePaySession.STATUS_SUCCESS),[2,this._onAuthorizeCallback()];case 7:throw y.sent(),t.completePayment(ApplePaySession.STATUS_FAILURE),new Error("Payment cannot complete");case 8:return[2]}}))}))},e.prototype._transformContactToAddress=function(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:[]}},e}();const Fy=Ly,By=le((function(e){var t=e.getState().getHost;return new Fy((0,o.createRequestSender)({host:t()}),e,new ve)}),[{id:"applepay"}]);var Uy=function(){function e(e,t,n){void 0===n&&(n=window),this.paymentIntegrationService=e,this.boltScriptLoader=t,this.boltHostWindow=n}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d,l,p,h,m;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.bolt,n=e.containerId,r=e.methodId,o=(i=t||{}).buyNowInitializeOptions,a=i.style,!r)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new ye('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new ye('Unable to initialize payment because "options.bolt" argument is not provided.');if(!Boolean(o))throw new _e("Only buy now flow is implemented for Bolt button");if(!(null==o?void 0:o.storefrontApiToken)||"string"!=typeof o.storefrontApiToken)throw new ye('Unable to initialize payment because "options.storefrontApiToken" argument is not provided.');return c=this.paymentIntegrationService.getState(),u=c.getPaymentMethodOrThrow(r),d=u.initializationData,l=u.config,h=(p=d||{}).publishableKey,m=p.developerConfig,[4,this.boltScriptLoader.loadBoltClient(h,l.testMode,m,"BigCommerce",o.storefrontApiToken)];case 1:return s.sent(),this.renderButton(n,u,a),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.renderButton=function(e,t,n){var r;"function"==typeof(null===(r=this.boltHostWindow.BoltConnect)||void 0===r?void 0:r.setupProductPageCheckout)&&(this.addButtonContainer(e,t,n),this.boltHostWindow.BoltConnect.setupProductPageCheckout())},e.prototype.addButtonContainer=function(e,t,n){var r=document.getElementById(e);if(r){var i=document.createElement("div"),o=document.createElement("object");i.setAttribute("id","product-page-checkout-wrapper"),i.setAttribute("class","bolt-button-wrapper"),i.setAttribute("style","display:none"),i.setAttribute("data-tid","product-page-checkout-wrapper"),o.setAttribute("data",this.getBoltObjectData(t,n)),o.setAttribute("class","bolt-product-checkout-button"),i.append(o),r.innerHTML="",r.append(i)}},e.prototype.getBoltObjectData=function(e,t){var n=e.initializationData,r=e.config,i=n||{},o=i.publishableKey,a=i.developerConfig,s=this.boltScriptLoader.getDomainURL(!!r.testMode,a),c=this.getButtonHeight(null==t?void 0:t.size),u=this.getButtonBorderRadius(null==t?void 0:t.shape,c);return(0,ql.stringifyUrl)({url:"https://"+s+"/v1/checkout_button",query:{publishable_key:o,variant:"ppc",height:c,border_radius:u}})},e.prototype.getButtonHeight=function(e){if(e)switch(e){case Ne.Small:return 25;case Ne.Large:return 45;case Ne.Medium:default:return 40}},e.prototype.getButtonBorderRadius=function(e,t){if(e)switch(e){case Le.Pill:return t?Math.round(t/2):void 0;case Le.Rect:default:return 4}},e}();const xy=Uy,qy=le((function(e){return new xy(e,new Be((0,a.getScriptLoader)()))}),[{id:"bolt"}]);var Vy=function(){function e(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}return e.prototype.initialize=function(e){var t;return(0,s.__awaiter)(this,void 0,void 0,(function(){var n,r,i,o,a;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(n=e.paypalcommerce,r=e.containerId,i=e.methodId,o=Boolean(null==n?void 0:n.buyNowInitializeOptions),!i)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(!r)throw new ye('Unable to initialize payment because "options.containerId" argument is not provided.');if(!n)throw new ye('Unable to initialize payment because "options.paypalcommerce" argument is not provided.');if(o&&!n.currencyCode)throw new ye('Unable to initialize payment because "options.paypalcommerce.currencyCode" argument is not provided.');if(o&&"function"!=typeof(null===(t=n.buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody))throw new ye('Unable to initialize payment because "options.paypalcommerce.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');return o?[3,2]:[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:s.sent(),s.label=2;case 2:return a=o?n.currencyCode:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,[4,this.paypalCommerceIntegrationService.loadPayPalSdk(i,a,!1)];case 3:return s.sent(),this.renderButton(r,i,n),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.renderButton=function(e,t,n){var r=this,i=n.buyNowInitializeOptions,o=n.style,a=n.onComplete,c=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),u=(this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t).initializationData||{}).isHostedCheckoutEnabled,d={createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommerce")},onApprove:function(e){var n=e.orderID;return r.paypalCommerceIntegrationService.tokenizePayment(t,n)}},l={onClick:function(){return r.handleClick(i)},onCancel:function(){return r.paymentIntegrationService.loadDefaultCheckout()}},p={onShippingAddressChange:function(e){return r.onShippingAddressChange(e)},onShippingOptionsChange:function(e){return r.onShippingOptionsChange(e)},onApprove:function(e,n){return r.onHostedCheckoutApprove(e,n,t,a)}},h=(0,s.__assign)((0,s.__assign)((0,s.__assign)({fundingSource:c.FUNDING.PAYPAL,style:this.paypalCommerceIntegrationService.getValidButtonStyle(o)},d),i&&l),u&&p),m=c.Buttons(h);m.isEligible()?m.render("#"+e):this.paypalCommerceIntegrationService.removeElement(e)},e.prototype.handleClick=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return e?[4,this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e)]:[3,3];case 1:return t=n.sent(),[4,this.paymentIntegrationService.loadCheckout(t.id)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},e.prototype.onHostedCheckoutApprove=function(e,t,n,r){return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!e.orderID)throw new me(he.MissingOrderId);return i=this.paymentIntegrationService.getState(),o=i.getCartOrThrow(),[4,t.order.get()];case 1:a=s.sent(),s.label=2;case 2:return s.trys.push([2,9,,10]),c=this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(a),[4,this.paymentIntegrationService.updateBillingAddress(c)];case 3:return s.sent(),o.lineItems.physicalItems.length>0?(u=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(a),[4,this.paymentIntegrationService.updateShippingAddress(u)]):[3,6];case 4:return s.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:s.sent(),s.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return s.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,e.orderID)];case 8:return s.sent(),r&&"function"==typeof r&&r(),[2,!0];case 9:throw d=s.sent(),new Error(d);case 10:return[2]}}))}))},e.prototype.onShippingAddressChange=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:t=this.paypalCommerceIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.country_code,postalCode:e.shippingAddress.postal_code,stateOrProvinceCode:e.shippingAddress.state}),i.label=1;case 1:return i.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(t)];case 2:return i.sent(),[4,this.paymentIntegrationService.updateShippingAddress(t)];case 3:return i.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return i.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return i.sent(),[3,7];case 6:throw r=i.sent(),new Error(r);case 7:return[2]}}))}))},e.prototype.onShippingOptionsChange=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:t=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(t.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:throw n=r.sent(),new Error(n);case 5:return[2]}}))}))},e}();const Gy=Vy,Hy=le((function(e){return new Gy(e,Ct(e))}),[{id:"paypalcommerce"}]);var Yy=function(){function e(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.paypalcommercecredit,n=e.containerId,r=e.methodId,o=(i=t||{}).buyNowInitializeOptions,a=i.currencyCode,c=i.messagingContainerId,u=!!o,!r)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new ye('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new ye('Unable to initialize payment because "options.paypalcommercecredit" argument is not provided.');if(u&&!a)throw new ye('Unable to initialize payment because "options.paypalcommercecredit.currencyCode" argument is not provided.');if(u&&"function"!=typeof(null==o?void 0:o.getBuyNowCartRequestBody))throw new ye('Unable to initialize payment because "options.paypalcommercecredit.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');return u?[3,2]:[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:s.sent(),s.label=2;case 2:return d=u?a:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,[4,this.paypalCommerceIntegrationService.loadPayPalSdk(r,d,!1)];case 3:return s.sent(),this.renderButton(n,r,t),this.renderMessages(c),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.renderButton=function(e,t,n){var r=this,i=n.buyNowInitializeOptions,o=n.style,a=n.onComplete,c=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),u=(this.paymentIntegrationService.getState().getPaymentMethodOrThrow(t).initializationData||{}).isHostedCheckoutEnabled,d={createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommercecredit")},onApprove:function(e){var n=e.orderID;return r.paypalCommerceIntegrationService.tokenizePayment(t,n)}},l={onClick:function(){return r.handleClick(i)},onCancel:function(){return r.paymentIntegrationService.loadDefaultCheckout()}},p={onShippingAddressChange:function(e){return r.onShippingAddressChange(e)},onShippingOptionsChange:function(e){return r.onShippingOptionsChange(e)},onApprove:function(e,n){return r.onHostedCheckoutApprove(e,n,t,a)}},h=[c.FUNDING.PAYLATER,c.FUNDING.CREDIT],m=!1;h.forEach((function(t){if(!m){var n=(0,s.__assign)((0,s.__assign)((0,s.__assign)({fundingSource:t,style:r.paypalCommerceIntegrationService.getValidButtonStyle(o)},d),i&&l),u&&p),a=c.Buttons(n);a.isEligible()&&(a.render("#"+e),m=!0)}})),m||this.paypalCommerceIntegrationService.removeElement(e)},e.prototype.handleClick=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return e?[4,this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e)]:[3,3];case 1:return t=n.sent(),[4,this.paymentIntegrationService.loadCheckout(t.id)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},e.prototype.onHostedCheckoutApprove=function(e,t,n,r){return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!e.orderID)throw new me(he.MissingOrderId);return i=this.paymentIntegrationService.getState(),o=i.getCartOrThrow(),[4,t.order.get()];case 1:a=s.sent(),s.label=2;case 2:return s.trys.push([2,9,,10]),c=this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(a),[4,this.paymentIntegrationService.updateBillingAddress(c)];case 3:return s.sent(),o.lineItems.physicalItems.length>0?(u=this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(a),[4,this.paymentIntegrationService.updateShippingAddress(u)]):[3,6];case 4:return s.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:s.sent(),s.label=6;case 6:return[4,this.paymentIntegrationService.submitOrder({},{params:{methodId:n}})];case 7:return s.sent(),[4,this.paypalCommerceIntegrationService.submitPayment(n,e.orderID)];case 8:return s.sent(),r&&"function"==typeof r&&r(),[2,!0];case 9:throw d=s.sent(),new Error(d);case 10:return[2]}}))}))},e.prototype.onShippingAddressChange=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:t=this.paypalCommerceIntegrationService.getAddress({city:e.shippingAddress.city,countryCode:e.shippingAddress.country_code,postalCode:e.shippingAddress.postal_code,stateOrProvinceCode:e.shippingAddress.state}),i.label=1;case 1:return i.trys.push([1,6,,7]),[4,this.paymentIntegrationService.updateBillingAddress(t)];case 2:return i.sent(),[4,this.paymentIntegrationService.updateShippingAddress(t)];case 3:return i.sent(),n=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(),[4,this.paymentIntegrationService.selectShippingOption(n.id)];case 4:return i.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 5:return i.sent(),[3,7];case 6:throw r=i.sent(),new Error(r);case 7:return[2]}}))}))},e.prototype.onShippingOptionsChange=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n;return(0,s.__generator)(this,(function(r){switch(r.label){case 0:t=this.paypalCommerceIntegrationService.getShippingOptionOrThrow(e.selectedShippingOption.id),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.paymentIntegrationService.selectShippingOption(t.id)];case 2:return r.sent(),[4,this.paypalCommerceIntegrationService.updateOrder()];case 3:return r.sent(),[3,5];case 4:throw n=r.sent(),new Error(n);case 5:return[2]}}))}))},e.prototype.renderMessages=function(e){var t=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();if(e&&document.getElementById(e)){var n={amount:this.paymentIntegrationService.getState().getCartOrThrow().cartAmount,placement:"cart",style:{layout:"text"}};t.Messages(n).render("#"+e)}},e}();const jy=Yy,Wy=le((function(e){return new jy(e,Ct(e))}),[{id:"paypalcommercecredit"}]);var Ky=function(){function e(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.paypalcommercevenmo,n=e.containerId,r=e.methodId,o=(i=t||{}).buyNowInitializeOptions,a=i.currencyCode,c=!!o,!r)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new ye('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new ye('Unable to initialize payment because "options.paypalcommercevenmo" argument is not provided.');if(c&&!a)throw new ye('Unable to initialize payment because "options.paypalcommercevenmo.currencyCode" argument is not provided.');if(c&&"function"!=typeof(null==o?void 0:o.getBuyNowCartRequestBody))throw new ye('Unable to initialize payment because "options.paypalcommercevenmo.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');return c?[3,2]:[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:s.sent(),s.label=2;case 2:return u=c?a:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,[4,this.paypalCommerceIntegrationService.loadPayPalSdk(r,u,!1)];case 3:return s.sent(),this.renderButton(n,r,t),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.renderButton=function(e,t,n){var r=this,i=n.buyNowInitializeOptions,o=n.style,a=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow(),c=a.FUNDING.VENMO,u={createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommercevenmo")},onApprove:function(e){var n=e.orderID;return r.paypalCommerceIntegrationService.tokenizePayment(t,n)}},d={onClick:function(){return r.handleClick(i)},onCancel:function(){return r.paymentIntegrationService.loadDefaultCheckout()}},l=(0,s.__assign)((0,s.__assign)({fundingSource:c,style:this.getValidVenmoButtonStyles(o)},u),i&&d),p=a.Buttons(l);p.isEligible()?p.render("#"+e):this.paypalCommerceIntegrationService.removeElement(e)},e.prototype.getValidVenmoButtonStyles=function(e){var t=this.paypalCommerceIntegrationService.getValidButtonStyle(e);return t.color===st.gold?(0,s.__assign)((0,s.__assign)({},t),{color:void 0}):t},e.prototype.handleClick=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return e?[4,this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e)]:[3,3];case 1:return t=n.sent(),[4,this.paymentIntegrationService.loadCheckout(t.id)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},e}();const Jy=Ky,Zy=le((function(e){return new Jy(e,Ct(e))}),[{id:"paypalcommercevenmo"}]);var Qy=function(){function e(e,t){this.paymentIntegrationService=e,this.paypalCommerceIntegrationService=t}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r,i,o,a,c,u,d;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(t=e.paypalcommercealternativemethods,n=e.containerId,r=e.methodId,o=(i=t||{}).apm,a=i.buyNowInitializeOptions,c=i.currencyCode,u=!!a,!r)throw new ye('Unable to initialize payment because "options.methodId" argument is not provided.');if(!n)throw new ye('Unable to initialize payment because "options.containerId" argument is not provided.');if(!t)throw new ye('Unable to initialize payment because "options.paypalcommercealternativemethods" argument is not provided.');if(!o)throw new ye('Unable to initialize payment because "options.paypalcommercealternativemethods.apm" argument is not provided.');if(u&&!c)throw new ye('Unable to initialize payment because "options.paypalcommercealternativemethods.currencyCode" argument is not provided.');if(u&&"function"!=typeof(null==a?void 0:a.getBuyNowCartRequestBody))throw new ye('Unable to initialize payment because "options.paypalcommercealternativemethods.buyNowInitializeOptions.getBuyNowCartRequestBody" argument is not provided or it is not a function.');return u?[3,2]:[4,this.paymentIntegrationService.loadDefaultCheckout()];case 1:s.sent(),s.label=2;case 2:return d=u?c:this.paymentIntegrationService.getState().getCartOrThrow().currency.code,[4,this.paypalCommerceIntegrationService.loadPayPalSdk(r,d,!1)];case 3:return s.sent(),this.renderButton(n,r,t),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.renderButton=function(e,t,n){var r=this,i=n.apm,o=n.buyNowInitializeOptions,a=n.style,c=this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();if(!Object.values(c.FUNDING).includes(i))throw new ye('Unable to initialize PayPal button because "options.paypalcommercealternativemethods.apm" argument is not valid funding source.');var u={createOrder:function(){return r.paypalCommerceIntegrationService.createOrder("paypalcommercealternativemethod")},onApprove:function(e){var n=e.orderID;return r.paypalCommerceIntegrationService.tokenizePayment(t,n)}},d={onClick:function(){return r.handleClick(o)},onCancel:function(){return r.paymentIntegrationService.loadDefaultCheckout()}},l=(0,s.__assign)((0,s.__assign)({fundingSource:i,style:this.paypalCommerceIntegrationService.getValidButtonStyle(a)},u),o&&d),p=c.Buttons(l);p.isEligible()?p.render("#"+e):this.paypalCommerceIntegrationService.removeElement(e)},e.prototype.handleClick=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return e?[4,this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(e)]:[3,3];case 1:return t=n.sent(),[4,this.paymentIntegrationService.loadCheckout(t.id)];case 2:n.sent(),n.label=3;case 3:return[2]}}))}))},e}();const Xy=Qy,$y=le((function(e){return new Xy(e,Ct(e))}),[{id:"paypalcommercealternativemethods"}]);var ef,tf,nf,rf,of;!function(e){e.HORIZONTAL="horizontal",e.VERTICAL="vertical"}(ef||(ef={})),function(e){e.SMALL="small",e.MEDIUM="medium",e.LARGE="large",e.RESPONSIVE="responsive"}(tf||(tf={})),function(e){e.GOLD="gold",e.BLUE="blue",e.SIlVER="silver",e.BLACK="black"}(nf||(nf={})),function(e){e.CHECKOUT="checkout",e.PAY="pay",e.BUYNOW="buynow",e.PAYPAL="paypal",e.CREDIT="credit"}(rf||(rf={})),function(e){e.PILL="pill",e.RECT="rect"}(of||(of={}));var af=function(){function e(e,t,n){this.paymentIntegrationService=e,this.paypalExpressScriptLoader=t,this.formPoster=n}return e.prototype.initialize=function(e){return(0,s.__awaiter)(this,void 0,void 0,(function(){var t,n,r;return(0,s.__generator)(this,(function(i){switch(i.label){case 0:if(t=this.paymentIntegrationService.getState(),n=t.getPaymentMethodOrThrow(e.methodId),!e.paypal)throw new ye;if(!n.config.merchantId)throw new me(he.MissingPaymentMethod);return[4,this.paypalExpressScriptLoader.loadPaypalSDK(n.config.merchantId)];case 1:return r=i.sent(),this.renderButton(e,r),[2]}}))}))},e.prototype.deinitialize=function(){return Promise.resolve()},e.prototype.renderButton=function(e,t){var n,r=this,i=e.containerId,o=e.methodId,a=e.paypal,s=a.allowCredit,c=a.clientId,u=a.onPaymentError,d=a.shouldProcessPayment,l=a.style,p=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e.methodId);if(!p.config.merchantId)throw new me(he.MissingPaymentMethod);var h=p.config.merchantId,m=p.config.testMode?"sandbox":"production",_=((n={})[m]=c,n),y=t.FUNDING.CREDIT||"credit",f=s?[y]:[],g=s?[]:[y];return t.Button.render({env:m,client:_,commit:d,funding:{allowed:f,disallowed:g},style:this.getStyle(l),payment:function(e,t){return r.setupPayment(h,t,u)},onAuthorize:function(e,t){return r.tokenizePayment(e,o,t,d)}},i)},e.prototype.getStyle=function(e){var t=e||{},n=t.color,r=t.fundingicons,i=t.label,o=t.layout,a=t.shape,s=t.size,c=t.tagline;return{color:n,fundingicons:r,label:i,layout:o,shape:a||of.RECT,size:"small"===s?tf.RESPONSIVE:s,tagline:c}},e.prototype.setupPayment=function(e,t,n){return(0,s.__awaiter)(this,void 0,void 0,(function(){var r,i,o,a;return(0,s.__generator)(this,(function(c){switch(c.label){case 0:if(!t)throw new Ee(Pe.CheckoutButtonNotInitialized);c.label=1;case 1:return c.trys.push([1,4,,5]),[4,this.paymentIntegrationService.loadDefaultCheckout()];case 2:return r=c.sent(),i=r.getCartOrThrow().id,o=r.getHost()||"",[4,t.request.post(o+"/api/storefront/payment/paypalexpress",{merchantId:e,cartId:i},{headers:(0,s.__assign)({"X-API-INTERNAL":mt},yt)})];case 3:return[2,c.sent().id];case 4:throw a=c.sent(),n&&n(a),a;case 5:return[2]}}))}))},e.prototype.tokenizePayment=function(e,t,n,r){return(0,s.__awaiter)(this,void 0,void 0,(function(){var i,o,a;return(0,s.__generator)(this,(function(s){switch(s.label){case 0:if(!n)throw new Ee(Pe.CheckoutButtonNotInitialized);if(!e.paymentID||!e.payerID)throw new me(he.MissingPayment);return i=this.paymentIntegrationService.getState(),o=i.getPaymentMethodOrThrow(t),[4,n.payment.get(e.paymentID)];case 1:return a=s.sent(),[2,this.formPoster.postForm("/checkout.php",{payment_type:"paypal",provider:o.id,action:r?"process_payment":"set_external_checkout",paymentId:e.paymentID,payerId:e.payerID,payerInfo:JSON.stringify(a.payer.payer_info)})]}}))}))},e}();const sf=af;var cf=function(){function e(e){this.scriptLoader=e,this.window=window}return e.prototype.loadPaypalSDK=function(e){return void 0===e&&(e=""),(0,s.__awaiter)(this,void 0,void 0,(function(){var t;return(0,s.__generator)(this,(function(n){switch(n.label){case 0:return t=(0,s.__assign)({async:!0,attributes:{"data-merchant-id":e}},e&&{attributes:{"data-merchant-id":e}}),[4,this.scriptLoader.loadScript("//www.paypalobjects.com/api/checkout.min.js",t)];case 1:if(n.sent(),!this.window.paypal)throw new Re;return[2,this.window.paypal]}}))}))},e}();const uf=cf,df=le((function(e){return new sf(e,new uf((0,a.getScriptLoader)()),(0,xe.createFormPoster)())}),[{id:"paypalexpress"}]);function lf(e){var t=null!=e?e:{},n=t.host,r=t.locale,s=void 0===r?"en":r,c=ry(),u=(0,o.createRequestSender)({host:n}),d=(0,xe.createFormPoster)({host:n}),l=function(e,t){void 0===t&&(t=i);for(var n=new de,r=function(t){if(!oe(t))return"continue";for(var r=0,i=t.resolveIds;r6e5)&&e instanceof _f&&e.subtype===mf.MissingContent?(this._storage.removeItem(gf),this._storage.removeItem(ff),this._allowCookie()):Promise.reject()},(0,s.__decorate)([yn],e)}();const wf=vf;var Cf=function(){function e(e){this._options=e}return e.prototype.createFrame=function(e,t){var n=document.getElementById(t),r=(this._options||{}).timeout,i=void 0===r?6e4:r;if(!n)throw new _f("Unable to embed the iframe because the container element could not be found.",mf.MissingContainer);var o=document.createElement("iframe");return o.src=e,o.style.border="none",o.style.display="none",o.style.width="100%",o.allowPaymentRequest=!0,n.appendChild(o),this._toResizableFrame(o,i).catch((function(e){throw n.removeChild(o),e}))},e.prototype._toResizableFrame=function(e,t){return new Promise((function(r,i){var o=window.setTimeout((function(){i(new _f("Unable to embed the iframe because the content could not be loaded."))}),t),a=function(t){var o,a;if(t.origin===hn(e.src).origin&&(mn(t.data,pf.FrameError)&&(s(),i(new _f(t.data.payload.message,mf.MissingContent))),mn(t.data,pf.FrameLoaded))){e.style.display="";var c=(o={scrolling:!1,sizeWidth:!1,heightCalculationMethod:t.data.payload&&t.data.payload.contentId?"taggedElement":"lowestElement"},a=e,(0,n(780).iframeResizer)(o,a));s(),r(c[c.length-1])}},s=function(){window.removeEventListener("message",a),window.clearTimeout(o)};window.addEventListener("message",a)}))},e}();const Sf=Cf;var If="BigCommerce.EmbeddedCheckout";function bf(e){var t=hn(e.url).origin;return new wf(new Sf,new gn(t),new _n(t),new Gs({styles:e.styles&&e.styles.loadingIndicator}),(0,o.createRequestSender)(),new Zc(If),window.location,e).attach()}function Pf(e){if(e.payload&&e.payload.contentId){var t=document.getElementById(e.payload.contentId);t&&!t.hasAttribute("data-iframe-height")&&t.setAttribute("data-iframe-height","")}}function Ef(e){return"object"==typeof e&&null!==e&&"message"in e&&"type"in e}var Af=function(){function e(e,t,n,r){void 0===r&&(r={}),this._messageListener=e,this._messagePoster=t,this._untargetedMessagePoster=n,this._messageHandlers=r,this._messageListener.listen()}return e.prototype.postComplete=function(){var e={type:pf.CheckoutComplete};this._postMessage(e)},e.prototype.postError=function(e){var t={type:pf.CheckoutError,payload:this._transformError(e)};this._postMessage(t)},e.prototype.postFrameError=function(e){var t={type:pf.FrameError,payload:this._transformError(e)};this._postMessage(t,{untargeted:!0})},e.prototype.postFrameLoaded=function(e){var t={type:pf.FrameLoaded,payload:e};this._postMessage(t)},e.prototype.postLoaded=function(){var e={type:pf.CheckoutLoaded};this._postMessage(e)},e.prototype.postSignedOut=function(){var e={type:pf.SignedOut};this._postMessage(e)},e.prototype.receiveStyles=function(e){this._messageListener.addListener(yf.StyleConfigured,(function(t){var n=t.payload;e(n)}))},e.prototype._postMessage=function(e,t){if(this._notifyMessageHandlers(e),t&&t.untargeted)return this._untargetedMessagePoster.post(e);this._messagePoster.post(e)},e.prototype._notifyMessageHandlers=function(e){var t=this;Object.keys(this._messageHandlers).forEach((function(n){if(e.type===n){var r=t._messageHandlers[n];r&&r.call(null,e)}}))},e.prototype._transformError=function(e){return{message:e.message,type:Ef(e)?e.type:void 0,subtype:Ef(e)?e.subtype:void 0}},(0,s.__decorate)([yn],e)}();const Of=Af,kf=function(){function e(){}return e.prototype.postComplete=function(){},e.prototype.postError=function(){},e.prototype.postFrameError=function(){},e.prototype.postFrameLoaded=function(){},e.prototype.postLoaded=function(){},e.prototype.postSignedOut=function(){},e.prototype.receiveStyles=function(){},(0,s.__decorate)([yn],e)}();function Tf(e){var t;n(252);var r=e.parentWindow||window.parent;return window===r?new kf:new Of(new gn(e.parentOrigin),new _n(e.parentOrigin,r),new _n("*",r),((t={})[pf.FrameLoaded]=Pf,t))}const Mf=require("messageformat");var Df=n.n(Mf),Rf="en",zf="optimized_checkout",Nf=function(){function e(e,t){this._logger=t;var n=this._transformConfig(e),r=n.locale,i=n.locales,o=n.translations;this._locale=r,this._locales=i,this._translations=o,this._formatters={}}return e.prototype.mapKeys=function(e){var t=this;Object.keys(e).forEach((function(n){var r=zf+"."+e[n];t._translations[zf+"."+n]=t._translations[r]}))},e.prototype.getLocale=function(){return this._hasTranslations()?this._locale:Rf},e.prototype.translate=function(e,t){void 0===t&&(t={});var n=zf+"."+e;if("string"!=typeof this._translations[n])return this._logger.warn('Translation key "'+n+'" is missing'),n;if(!this._formatters[n]){var r=new(Df())(this._locales[n]);this._formatters[n]=r.compile(this._translations[n]||"")}return this._formatters[n](this._transformData(t))},e.prototype._transformConfig=function(e){void 0===e&&(e={});var t={defaultLocale:"",defaultTranslations:{},translations:{},locales:{},locale:e.locale||Rf},n=e.locales||{},r=this._flattenObject(e.translations||{}),i=this._flattenObject(e.defaultTranslations||{}),o=this._flattenObject(e.fallbackTranslations||{});return(0,Z.union)(Object.keys(o),Object.keys(i),Object.keys(r)).forEach((function(a){var s,c;r&&r[a]?(t.translations[a]=r[a],t.locales[a]=n[a]||t.locale):i[a]?(t.translations[a]=i[a],t.locales[a]=null!==(s=e.defaultLocale)&&void 0!==s?s:Rf):(t.translations[a]=o[a],t.locales[a]=null!==(c=e.fallbackLocale)&&void 0!==c?c:Rf)})),t},e.prototype._flattenObject=function(e,t,n){var r=this;void 0===t&&(t={}),void 0===n&&(n="");try{Object.keys(e).forEach((function(i){var o=e[i],a=n?n+"."+i:i;if((0,Z.isObject)(o))return r._flattenObject(o,t,a);t[a]=o}))}catch(e){this._logger.warn("Unable to parse object: "+e)}return t},e.prototype._transformData=function(e){return Object.keys(e).reduce((function(t,n){var r=e[n];return t[n]=null==r?"":r,t}),{})},e.prototype._hasTranslations=function(){var e=this;return Object.keys(this._locales).map((function(t){return e._locales[t]})).filter((function(t){return t.split("-")[0]===e._locale.split("-")[0]})).length>0},(0,s.__decorate)([yn],e)}();const Lf=Nf;function Ff(e){return void 0===e&&(e={}),new Lf(e,R())}var Bf=function(){function e(e){if(!e)throw new Error("Currency settings missing");var t=e.decimalPlaces,n=e.symbolLocation,r=e.symbol,i=e.thousandsSeparator,o=e.decimalSeparator;if("string"!=typeof n||"string"!=typeof r||"string"!=typeof i||"string"!=typeof o||"string"!=typeof t)throw new ae("Invalid currency settings provided");this._decimalPlaces=parseInt(t,10),this._symbolLocation=n,this._symbol=r,this._thousandsSeparator=i,this._decimalSeparator=o}return e.prototype.format=function(e){if("number"!=typeof e)throw new ae("Invalid amount provided");var t=this._formatNumber(e),n=this._formatCurrency(t);return e<0?"-"+n:n},e.prototype._formatNumber=function(e){var t=Math.abs(e),n=this._toFixed(t,this._decimalPlaces).split("."),r=n[0],i=n[1],o=void 0===i?"":i,a=r.replace(/\B(?=(\d{3})+(?!\d))/g,this._thousandsSeparator);return this._decimalPlaces<1?a:[a,o].join(this._decimalSeparator)},e.prototype._formatCurrency=function(e){return"left"===this._symbolLocation.toLowerCase()?""+this._symbol+e:""+e+this._symbol},e.prototype._toFixed=function(e,t){return(+(Math.round(+(e+"e"+t))+"e"+-t)).toFixed(t)},e}();const Uf=Bf,xf=function(){function e(e){this._storeConfig=e,this._customerFormatter=new Uf(this._storeConfig.shopperCurrency),this._storeFormatter=new Uf(this._storeConfig.currency)}return e.prototype.toCustomerCurrency=function(e){var t=this._storeConfig.shopperCurrency.exchangeRate;return this._customerFormatter.format(e*t)},e.prototype.toStoreCurrency=function(e){return this._storeFormatter.format(e)},(0,s.__decorate)([yn],e)}();function qf(e){return new xf(e)}function Vf(e){return e&&"ga"in e&&"function"==typeof e.ga}function Gf(e,t){Vf(window)&&window.ga("send",e,(0,s.__assign)((0,s.__assign)({},t),{nonInteraction:!1}))}function Hf(e){return Yf(e).length>=8096}function Yf(e){return Object.keys(e).reduce((function(t,n){var r=typeof e[n];return"string"===r||"number"===r?(0,s.__spreadArrays)(t,[n+"="+e[n]]):"object"===r&&null!==e[n]?(0,s.__spreadArrays)(t,[Yf(e[n])]):t}),[]).join("&")}var jf;!function(e){e[e.CUSTOMER=1]="CUSTOMER",e[e.SHIPPING=2]="SHIPPING",e[e.BILLING=3]="BILLING",e[e.PAYMENT=4]="PAYMENT"}(jf||(jf={}));var Wf={customer:jf.CUSTOMER,shipping:jf.SHIPPING,billing:jf.BILLING,payment:jf.PAYMENT},Kf=function(){function e(e,t,n,r){var i=(void 0===r?{}:r).checkoutSteps;if(this.checkoutService=e,this.analyticsExtraItemsManager=t,this.analytics=n,this._checkoutStarted=!1,this._completedSteps={},this._viewedSteps={},this._analyticStepOrder=["customer","shipping","billing","payment"],void 0!==i){if(i.some((function(e){return!(e in Wf)})))throw new ae("Invalid checkout steps provided. Valid values are: "+(0,Z.keys)(Wf).join(", ")+".");this._analyticStepOrder=i}}return e.prototype.trackCheckoutStarted=function(){if(!this._checkoutStarted){var e=this.getCheckout();if(e){var t=e.coupons,n=e.grandTotal,r=e.shippingCostTotal,i=e.taxTotal,o=e.cart,a=o.lineItems,s=o.discountAmount,c=o.id,u=this.analyticsExtraItemsManager.saveExtraItemsData(c,a);this.analytics.track("Checkout Started",this.getTrackingPayload({revenue:n,shipping:r,tax:i,discount:s,coupons:t,lineItems:a,extraItemsData:u})),this._checkoutStarted=!0}}},e.prototype.trackOrderComplete=function(){var e,t=this.getOrder();if(t){var n=t.isComplete,r=t.orderId,i=t.orderAmount,o=t.shippingCostTotal,a=t.taxTotal,s=t.discountAmount,c=t.coupons,u=t.lineItems,d=t.cartId;if(n){var l=this.analyticsExtraItemsManager.readExtraItemsData(d);if(null!==l){var p=null===(e=this.checkoutService.getState().data.getConfig())||void 0===e?void 0:e.checkoutSettings.features["DATA-6891.missing_orders_within_GA"],h=this.getTrackingPayload({orderId:r,revenue:i,shipping:o,tax:a,discount:s,coupons:c,extraItemsData:l,lineItems:u});if(p&&Os(window)&&Vf(window)&&Hf(h))return Gf("transaction",{"&ti":h.orderId,"&ta":h.affiliation,"&tr":h.revenue,"&ts":h.shipping,"&tt":h.tax,"&tcc":h.coupon,"&cu":h.currency}),h.products.forEach((function(e){Gf("item",{"&ti":h.orderId,"&in":e.name,"&ic":e.sku,"&iv":""+e.category,"&ip":e.price,"&iq":e.quantity})})),this.analyticsExtraItemsManager.clearExtraItemData(d);this.analytics.track("Order Completed",h),this.analyticsExtraItemsManager.clearExtraItemData(d)}}}},e.prototype.trackStepViewed=function(e){var t=this.getIdFromStep(e);t&&!this.hasStepViewed(t)&&(this.trackViewed(t),this.backfill(t))},e.prototype.trackStepCompleted=function(e){var t=this.getIdFromStep(e);t&&!this.hasStepCompleted(t)&&(this.backfill(t),this.trackCompleted(t))},e.prototype.backfill=function(e){for(var t=0,n=this._analyticStepOrder;t0?e.salePrice:e.listPrice,sku:e.sku,variant_id:e.variantId,discount:e.discountAmount,brand_name:e.brand,currency:t,category_names:(n=e,Array.isArray(n.categoryNames)?n.categoryNames:Array.isArray(n.categories)?(0,Z.flatten)(n.categories).map((function(e){return e.name})):[]),retail_price:e.retailPrice}}));return(0,s.__spreadArrays)(n,i,r).map((function(e){return(0,s.__assign)((0,s.__assign)({},e),{product_id:String(e.product_id)})}))},e.prototype._hasStepCompleted=function(e){return this._completedSteps[e]},e}();const tg=eg,ng=function(){function e(){}return e.prototype.checkoutBegin=function(){},e.prototype.orderPurchased=function(){},e.prototype.stepCompleted=function(){},e.prototype.customerEmailEntry=function(){},e.prototype.customerSuggestionInit=function(){},e.prototype.customerSuggestionExecute=function(){},e.prototype.customerPaymentMethodExecuted=function(){},e.prototype.showShippingMethods=function(){},e.prototype.selectedPaymentMethod=function(){},e.prototype.clickPayButton=function(){},e.prototype.paymentRejected=function(){},e.prototype.paymentComplete=function(){},e.prototype.exitCheckout=function(){},e}();function rg(e){return function(e){return"bodlEvents"in e}(window)?new tg(e,window.bodlEvents.checkout):new ng}})(),module.exports=r})(); //# sourceMappingURL=checkout-sdk.js.map \ No newline at end of file diff --git a/dist/checkout-sdk.js.map b/dist/checkout-sdk.js.map index 512e148509..547cf28843 100644 --- a/dist/checkout-sdk.js.map +++ b/dist/checkout-sdk.js.map @@ -1 +1 @@ -{"version":3,"file":"checkout-sdk.js","mappings":"kCAAAA,EAAOC,QAAUC,QAAQ,iB,UCAzBF,EAAOC,QAAUC,QAAQ,gD,GCCrBC,EAA2B,CAAC,EAGhC,SAASC,EAAoBC,GAE5B,IAAIC,EAAeH,EAAyBE,GAC5C,QAAqBE,IAAjBD,EACH,OAAOA,EAAaL,QAGrB,IAAID,EAASG,EAAyBE,GAAY,CAGjDJ,QAAS,CAAC,GAOX,OAHAO,EAAoBH,GAAUL,EAAQA,EAAOC,QAASG,GAG/CJ,EAAOC,OACf,CCrBAG,EAAoBK,EAAKT,IACxB,IAAIU,EAASV,GAAUA,EAAOW,WAC7B,IAAOX,EAAiB,QACxB,IAAM,EAEP,OADAI,EAAoBQ,EAAEF,EAAQ,CAAEG,EAAGH,IAC5BA,CAAM,ECLdN,EAAoBQ,EAAI,CAACX,EAASa,KACjC,IAAI,IAAIC,KAAOD,EACXV,EAAoBY,EAAEF,EAAYC,KAASX,EAAoBY,EAAEf,EAASc,IAC5EE,OAAOC,eAAejB,EAASc,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,IAE1E,ECNDX,EAAoBY,EAAI,CAACK,EAAKC,IAAUL,OAAOM,UAAUC,eAAeC,KAAKJ,EAAKC,GCClFlB,EAAoBsB,EAAKzB,IACH,oBAAX0B,QAA0BA,OAAOC,aAC1CX,OAAOC,eAAejB,EAAS0B,OAAOC,YAAa,CAAEC,MAAO,WAE7DZ,OAAOC,eAAejB,EAAS,aAAc,CAAE4B,OAAO,GAAO,E,20DCL9D,MAAM,EAA+B3B,QAAQ,+BCAvC,EAA+BA,QAAQ,8BCAvC,EAA+BA,QAAQ,SCAvC,EAA+BA,QAAQ,2BCAvC,EAA+BA,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E,EAA+B,IAAI,GACrC7iG,EACA8hG,EACA12E,EACAS,GAEEv1B,GAAa,KAAA2C,oBACbu6E,EAAc/B,GAAkBn7E,EAAYssG,GAC5Cz3E,EAAoB,IAAI,GAAkB5yC,GAC1CuqH,EAAiC,IAAI,GAA+BnmG,GAotB1E,OAltBAqD,EAASve,SACL,sBACA,WACI,WAAI,GACAlJ,EACA2yC,EACAK,EACAs3E,EACAr3E,EACAJ,EACAkN,GAAgC//C,EAAO,IAAI,IAC3C,IAAI,GACAA,EACAizC,EACA,IAAI,GAAoBh7B,GAAc,IAAA6/C,yBAX9C,IAgBRrwC,EAASve,SACL,sBACA,WACI,WAAI,GACAlJ,EACA2yC,EACAK,EACAs3E,EACAr3E,EACAJ,EACAkN,GAAgC//C,EAAO,IAAI,IAC3C,IAAI,GACAA,EACAizC,EACA,IAAI,GAAoBh7B,GAAc,IAAA6/C,yBAX9C,IAgBRrwC,EAASve,SACL,WACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAD,EACA,IAAI,GALR,IASRvrB,EAASve,SACL,aACA,WACI,WAAI,GACAlJ,EACAoqH,EACAv3E,EACAI,EACAD,EACA42E,EACAz2E,EACA,IAAI,GAAqBl7B,GAR7B,IAYRwP,EAASve,SACL,cACA,WACI,WAAI,GACAlJ,EACAsqH,EACAz3E,EACAI,EACAkF,KALJ,IASR1wB,EAASve,SACL,4BACA,WACI,WAAI,GACAlJ,EACA2yC,EACAK,EACAs3E,EACAr3E,EACAJ,EACAkN,GAAgC//C,EAAO,IAAI,IAP/C,IAWRynB,EAASve,SACL,aACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EACA,IAAI,GACA5yC,EACAizC,EACA,IAAI,GAAe,IAAI,GAAqBh7B,KARpD,IAaRwP,EAASve,SACL,eACA,WAAM,WAAI,GAA0BlJ,EAAO6yC,EAAoBI,EAAzD,IAGVxrB,EAASve,SACL,cACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAD,EACAg3E,EALJ,IASRviG,EAASve,SACL,yBACA,WACI,WAAI,GACAlJ,EACA2yC,EACAK,EACAs3E,EACAr3E,EACAJ,EACAkN,GACI//C,EACA,IAAI,GACA,IAAI,GAAoB,IAAI,GAAsBiY,WAG1Dhc,EACA,IAAI,GAAoB,IAAI,GAAsBgc,IAdtD,IAkBRwP,EAASve,SACL,qBACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAD,EACAg3E,EALJ,IASRviG,EAASve,SACL,oBACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAD,EACAg3E,EALJ,IASRviG,EAASve,SACL,4BACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAD,EACAg3E,GACA,EANJ,IAURviG,EAASve,SACL,4BACA,WACI,WAAI,GACAlJ,EACA2yC,EACAK,EACAs3E,EACAr3E,EACAJ,EACAkJ,GAA4C9jC,EAAcmM,GAC1D,IAAI,GAAyBnM,GARjC,IAYRwP,EAASve,SACL,aACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EACAI,EACA,IAAI,GAAoB/6B,GACxB0iC,EAPJ,IAWRlzB,EAASve,SACL,aACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EACA70B,EALJ,IASR0J,EAASve,SACL,aACA,WACI,WAAI,GACAlJ,EACAoqH,EACAv3E,EACAI,EACAD,EACA42E,EACAz2E,EACA,IAAI,GAAqBl7B,GAR7B,IAYRwP,EAASve,SACL,gBACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EACA,IAAI,GACA5yC,EACAizC,EACAD,EACA,IAAI,GAAe,IAAI,GAAqB/6B,KATpD,IAcRwP,EAASve,SACL,kBACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EACA,IAAI,GACA5yC,EACAizC,EACA,IAAI,GAAe,IAAI,GAAqBh7B,KARpD,IAaRwP,EAASve,SACL,QACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EACA,IAAI,GACA5yC,EACAizC,EACA,IAAI,GAAe,IAAI,GAAqBh7B,KARpD,IAaRwP,EAASve,SACL,6BACA,WACI,WAAI,GACAlJ,EACA2yC,EACAK,EACAs3E,EACAr3E,EACAJ,EACAkN,GAAgC//C,EAAO,IAAI,IAP/C,IAWRynB,EAASve,SACL,kBACA,WACI,WAAI,GACAlJ,EACA2yC,EACAK,EACAs3E,EACAr3E,EACAJ,EACAkN,GAAgC//C,EAAO,IAAI,IAP/C,IAWRynB,EAASve,SACL,gBACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EACA70B,EALJ,IASR0J,EAASve,SACL,oBACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EAJJ,IAQRnrB,EAASve,SACL,sBACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EAJJ,IAQRnrB,EAASve,SACL,2BACA,WACI,WAAI,GACAlJ,EACA2yC,EACAK,EACAs3E,EACAr3E,EACAJ,EACAkN,GACI//C,EACA,IAAI,GAAgCokB,IAExC,IAAI,GAXR,IAeRqD,EAASve,SACL,sBACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EAJJ,IAQRnrB,EAASve,SACL,qBACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EAJJ,IAQRnrB,EAASve,SACL,cACA,WACI,WAAI,GACAlJ,EACA2yC,EACAE,EACAI,EACAD,EACAs3E,EACAlmG,EACA,IAAI,GAAqBnM,GACzB,IAAI,GAAgBA,GATxB,IAaRwP,EAASve,SACL,iBACA,WACI,WAAI,GACAlJ,EACAgzC,EACAH,EACAI,EACAE,EACA,IAAI,GAAyBl7B,GAAc,IAAA6/C,wBAC3ChlB,EAPJ,IAWRrrB,EAASve,SACL,WACA,WACI,WAAI,GACAlJ,EACA6yC,EACAG,EACA62E,EACA,IAAI,GAAmB5xG,GAL3B,IASRwP,EAASve,SACL,aACA,WACI,WAAI,GACAlJ,EACA6yC,EACAg3E,EACA,IAAI,GAAqB5xG,GACzB,IAAI,GAAqBmM,GAL7B,IASRqD,EAASve,SACL,SACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAl1B,EACAi1B,EALJ,IASRvrB,EAASve,SACL,eACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACA,IAAI,GAAuBh7B,GAC3B0iC,EALJ,IASRlzB,EAASve,SACL,WACA,WACI,WAAI,GACA0pC,EACA5yC,EACA,IAAI,GAAmBiY,GACvB46B,EACAI,EALJ,IASRxrB,EAASve,SACL,YACA,WACI,WAAI,GACA0pC,EACA5yC,EACA6yC,EACAI,EACAE,EALJ,IASR1rB,EAASve,SACL,QACA,WACI,WAAI,GACAlJ,EACA6yC,EACAG,EACAu3E,EACAt3E,EACA,IAAI,GAAgBh7B,GANxB,IAURwP,EAASve,SACL,uBACA,WACI,WAAI,GACAlJ,EACA2yC,EACAK,EACAs3E,EACAr3E,EACAJ,EACAkN,GAAgC//C,EAAO,IAAI,IAP/C,IAWRynB,EAASve,SACL,WACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EACA,IAAI,GACA5yC,EACAizC,EACAD,EACA,IAAI,GAAe,IAAI,GAAqB/6B,KATpD,IAcRwP,EAASve,SACL,mBACA,WACI,WAAI,GACAlJ,EACA6yC,EACA,IAAI,GAAmB56B,GAH3B,IAORwP,EAASve,SACL,0BACA,WACI,WAAI,GACAlJ,EACA6yC,EACA,IAAI,GAAmB56B,GAH3B,IAORwP,EAASve,SACL,UACA,WACI,WAAIshH,GACAxqH,EACA6yC,EACAmoD,GACIh7F,EACA6yC,EACAzuB,EACA62E,EACAroD,GAEJ,IAAI63E,GAAermG,EAAe62E,GAClC,IAAI,GAAe,SAXvB,IAeRxzE,EAASve,SACL,YACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAD,EACAG,EACA02E,EACAU,EAPJ,IAWR9iG,EAASve,SACL,aACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EACA70B,EALJ,IASR0J,EAASve,SACL,WACA,WACI,WAAI,GACAlJ,EACA2yC,EACAE,EACAI,EACAD,EACAs3E,EACAlmG,EACA,IAAI,GAAmBnM,GAR3B,IAYRwP,EAASve,SACL,sBACA,WACI,WAAI,GACAlJ,EACA2yC,EACAK,EACAs3E,EACAr3E,EACAJ,EACAkN,GAAgC//C,EAAO,IAAI,IAP/C,IAWRynB,EAASve,SACL,0BACA,WACI,WAAI,GACAlJ,EACA2yC,EACAK,EACAs3E,EACAr3E,EACAJ,EACAkN,GAAgC//C,EAAO,IAAI,IAP/C,IAWRynB,EAASve,SACL,aACA,WACI,WAAI,GACAlJ,EACAgzC,EACAC,EACAJ,EACA,IAAI,GAAqB56B,GACzBk7B,EACAP,EACA+H,EARJ,IAYRlzB,EAASve,SACL,eACA,WACI,WAAI,GACAlJ,EACAgzC,EACAC,EACAJ,EACA,IAAI,GAAsB56B,GAC1Bk7B,EACAL,EAPJ,IAWRrrB,EAASve,SACL,WACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EACA,IAAI,GAAgB36B,GALxB,IASRwP,EAASve,SACL,mBACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EAJJ,IAQRnrB,EAASve,SACL,8BACA,WACI,WAAI,GACAlJ,EACA2yC,EACAK,EACAs3E,EACAr3E,EACAJ,EACAkN,GAAgC//C,EAAO,IAAI,IAP/C,IAWRynB,EAASve,SACL,QACA,WACI,WAAI,GACAlJ,EACAgzC,EACAG,EACA02E,EACAh3E,EACA03E,EACAt3E,EAPJ,IAWDxrB,CACX,CF3vBY,CACIznB,EACAqgC,EACAjc,EACAgvB,EACAuH,GAEJ4uE,EACA12E,EACAS,GAEJ,IAAI,GAA0B,IAAI,GAA0BlvB,IAC5D,IAAI,GACA,IAAI,GAA6BA,EAAe,CAAEu2B,OAAM,KAE5D,IAAI,GIvKG,SACX36C,EACAokB,GAEA,IAAMqD,EAAW,IAAI,GACf0hG,EAAwB,IAAI,GAAsB/kG,GAClDsmG,EAA2B,IAAI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GAAgC//C,EAAO,IAAI,IAC3CuzC,EALJ,IASR9rB,EAASve,SACL,kBACA,WACI,WAAI,GACAlJ,EACA+d,EACA40B,EACAoN,GAAgC//C,EAAO,IAAI,IAC3CuzC,EALJ,IASR9rB,EAASve,SACL,wBACA,WACI,WAAI,GACAlJ,EACA+d,EACA40B,EACAoN,GACI//C,EACA,IAAI,GAA8Bs0H,IAEtC/gF,EARJ,IAYR9rB,EAASve,SACL,0BACA,WACI,WAAI,GACAlJ,EACA+d,EACA40B,EACAoN,GACI//C,EACA,IAAI,GAAgCokB,IAExCmvB,EARJ,IAYR9rB,EAASve,SACL,4BACA,WACI,WAAI,GACAlJ,EACA+d,EACA40B,EACAoN,GAAgC//C,EAAO,IAAI,IAC3CuzC,EALJ,IASR9rB,EAASve,SACL,sBACA,WACI,WAAI,GACAlJ,EACA+d,EACA40B,EACAoN,GAAgC//C,EAAO,IAAI,IAC3CuzC,EALJ,IASR9rB,EAASve,SACL,qBACA,WACI,WAAI,GACAlJ,EACA+d,EACA40B,EACAoN,GAAgC//C,EAAO,IAAI,IAC3CuzC,EALJ,IASR9rB,EAASve,SACL,wBACA,WACI,WAAI,GACAlJ,EACA+d,EACA40B,EACAoN,GAAgC//C,EAAO,IAAI,IAC3CuzC,EALJ,IASR9rB,EAASve,SACL,eACA,WACI,WAAI,GACAlJ,EACA2yC,EACA,IAAI,GAAuB16B,GAC3B0iC,EAJJ,IAQRlzB,EAASve,SACL,kBACA,WACI,WAAI,GACAlJ,EACA2yC,EACA,IAAI,GAAmB16B,GACvB8F,EACA7H,EALJ,IASRuR,EAASve,SACL,6BACA,WACI,WAAI,GACAlJ,EACA+d,EACA40B,EACAoN,GAAgC//C,EAAO,IAAI,IAC3CuzC,EALJ,IASD9rB,CACX,CFnOY+sG,CAA6Bx0H,EAAOokB,EAAerG,EAAY48B,EAAQzkC,GACvEqzG,EACA,IAAI,GAA2B,IAAI,GAA2BnlG,KAG1E,CGnDA,IAAYqwG,IAAZ,SAAYA,GAC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G,EAAKi0G,YAE3B,IAEA,OAAO,oBAAIh1F,EAAgBsxF,EAA4BD,GAAsBvwG,KACzE,SAACC,GAAS,OAAC,gCACJA,GAAI,CACPqwG,WAAYjkF,OAAOpsB,EAAKqwG,aAFlB,GAKlB,EAEQ,YAAA4B,kBAAR,SAA0Bz4F,GACtB,OAAOlnC,KAAKg8H,gBAAgB90F,EAChC,EACJ,EAnRA,G,eCZA,wBA0BA,QAzBI,YAAA03F,cAAA,WAAuB,EAEvB,YAAAG,eAAA,WAAwB,EAExB,YAAAU,cAAA,WAAuB,EAEvB,YAAAI,mBAAA,WAA4B,EAE5B,YAAAE,uBAAA,WAAgC,EAEhC,YAAAC,0BAAA,WAAmC,EAEnC,YAAAC,8BAAA,WAAuC,EAEvC,YAAAC,oBAAA,WAA6B,EAE7B,YAAAC,sBAAA,WAA+B,EAE/B,YAAAI,eAAA,WAAwB,EAExB,YAAAC,gBAAA,WAAyB,EAEzB,YAAAC,gBAAA,WAAyB,EAEzB,YAAAC,aAAA,WAAsB,EAC1B,EA1BA,GCmBe,SAASkB,GACpBtiG,GAEA,OCtBG,SAAuB90B,GAC1B,MAAO,eAAgBA,CAC3B,CDoBQq3H,CAAcr3H,QACP,IAAI,GAAmB80B,EAAW90B,OAAOg0H,WAAWr/H,UAGxD,IAAI,EACf,C","sources":["webpack://@bigcommerce/checkout-sdk/external commonjs \"iframe-resizer\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"iframe-resizer/js/iframeResizer.contentWindow\"","webpack://@bigcommerce/checkout-sdk/webpack/bootstrap","webpack://@bigcommerce/checkout-sdk/webpack/runtime/compat get default export","webpack://@bigcommerce/checkout-sdk/webpack/runtime/define property getters","webpack://@bigcommerce/checkout-sdk/webpack/runtime/hasOwnProperty shorthand","webpack://@bigcommerce/checkout-sdk/webpack/runtime/make namespace object","webpack://@bigcommerce/checkout-sdk/external commonjs \"@bigcommerce/request-sender\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"@bigcommerce/script-loader\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"tslib\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"@bigcommerce/data-store\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"rxjs\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"rxjs/operators\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/throw-error-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/standard-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/set-prototype-of.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/missing-data-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/errors/unable-to-continue-as-guest-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/content-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/sdk-version-headers.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/error-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/error-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/get-environment.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/log/console-logger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/log/noop-logger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/log/get-default-logger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/log/create-logger.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"@bigcommerce/memoize\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/data-store/cachable-action-decorator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/data-store/is-action-options.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/data-store/cache-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/config/config-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/config/config-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/request-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/errors/checkout-not-available-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/internal-api-headers.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/config/config-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/coupon-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/coupon-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-default-includes.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-params.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"lodash\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/join-includes.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/coupon-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/gift-certificate-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/gift-certificate-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/gift-certificate-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/is-resolvable-module.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/invalid-argument-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/registry/registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/registry/resolve-id-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/to-resolvable-module.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/standard-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/set-prototype-of.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/missing-data-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/not-implemented-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/invalid-argument-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-method-cancelled-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay-session-factory.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/create-apple-pay-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-method-failed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/not-initialized-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/request-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-method-invalid-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/custom-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-method-client-unavailable-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/create-bolt-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"@bigcommerce/form-poster\"","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/is-braintree-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/paypal.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal/braintree-paypal-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal/create-braintree-paypal-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/buy-now-cart-creation-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/cart/cart-source.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/http-request/internal-api-headers.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/http-request/content-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/http-request/sdk-version-headers.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/create-paypal-commerce-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/paypal-commerce-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/create-paypal-commerce-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit/paypal-commerce-credit-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit/create-paypal-commerce-credit-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-venmo/paypal-commerce-venmo-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-venmo/create-paypal-commerce-venmo-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/create-customer-strategy-registry-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/is-spam-protection-succeeded-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-strategy-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-strategy-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/join-or-merge-includes.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/merge-includes.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/form/form-fields-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/form/form-fields-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/form/form-fields-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/apple-pay/is-apple-pay-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-comparator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/errors/cart-changed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-validator.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/cancellable-promise/cancellable-promise.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/errors/unexpected-detachment-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/detachment-observer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/mutation-observer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/url/parse-url.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/is-iframe-event.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-event-poster.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/bind-decorator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-event-listener.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/url/append-www.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/spam-protection-challenge-not-completed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/carding-protection-challenge-not-completed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/carding-protection-failed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/payment-human-verification-handler.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/not-initialized-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/spam-protection-failed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/spam-protection-not-loaded-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/google-recaptcha.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/google-recaptcha-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/create-spam-protection.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/map-from-payment-error-response.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/errors/invalid-hosted-form-config-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/errors/invalid-hosted-form-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/errors/invalid-hosted-form-value-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/hosted-field-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/iframe-content/hosted-input-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/hosted-field.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/hosted-form.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/is-vaulted-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/hosted-form-order-data-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/hosted-form-factory.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/spam-protection-not-completed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/errors/cart-consistency-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/errors/order-tax-provider-unavailable-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-request-sender.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"@bigcommerce/bigpay-client\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/create-payment-client.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/is-billing-address-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/address/map-to-internal-address.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/amount-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/map-to-internal-coupon.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/generated/checkout-button-method-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/map-to-internal-gift-certificate.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/map-to-internal-line-items.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/map-gift-certificate-to-internal-line-item.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/map-to-internal-line-item.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/map-to-internal-cart.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/promotion/map-to-discount-notifications.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/map-to-internal-customer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/iframe-content/card-expiry-formatter.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"card-validator\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/iframe-content/card-number-formatter.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/map-to-internal-order.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/map-to-internal-shipping-option.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-request-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/spam-protection-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/spam-protection-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/spam-protection-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/store-credit/store-credit-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/store-credit/store-credit-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/store-credit/store-credit-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/errors/update-subscriptions-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/is-plain-object.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/clone-result.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-integration/create-payment-integration-selectors.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-integration/default-payment-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/data-store/create-data-store-projection.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-integration/payment-integration-store-projection-factory.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-integration/create-payment-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/getShippableItemsCount.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/getLineItemsCount.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/guard.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/amazon-pay-v2/amazon-pay-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/amazon-pay-v2/amazon-pay-v2-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/errors/payment-method-client-unavailable-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/amazon-pay-v2/amazon-pay-v2-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/amazon-pay-v2/create-amazon-pay-v2-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/unsupported-browser-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-sdk-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-visacheckout-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/create-braintree-visacheckout-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/visacheckout-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/chasepay/chasepay-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/errors/remote-checkout-synchronization-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-get-first-and-last-name.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/create-googlepay-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-adyenv2-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-adyenv3-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-authorizenet-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-bnz-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-braintree-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-checkoutcom-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-cybersourcev2-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-orbital-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-stripe-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-stripe-upe-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-worldpay-access-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/masterpass/masterpass-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/stripe-upe/stripe-upe-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/not-implemented-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/amazon-pay-v2/amazon-pay-v2-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/braintree/braintree-visacheckout-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/braintree/map-to-legacy-billing-address.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/braintree/map-to-legacy-shipping-address.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/map-to-braintree-shipping-address-override.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/paypal/paypal-sdk.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/braintree/braintree-paypal-credit-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/chasepay/chasepay-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/default/default-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/googlepay/googlepay-customer-method-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/googlepay/googlepay-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/masterpass/get-callback-url.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/masterpass/masterpass-supported-locales.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/masterpass/format-locale.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/masterpass/masterpass-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/square/square-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/stripe-upe/stripe-upe.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/stripe-upe/stripe-upe-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/errors/extension-not-found-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/errors/invalid-extension-config-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-iframe.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-argument-invalid-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/is-vaulted-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/browser-info/get-browser-info.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/order-finalization-not-required-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/is-request-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-invalid-form-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-integration/src/adyenv2/adyenv2.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-integration/src/adyenv2/adyenv2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-integration/src/adyenv2/adyenv2-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-integration/src/adyenv2/create-adyenv2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/is-hosted-intrument-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-integration/src/adyenv3/adyenv3.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-integration/src/adyenv3/adyenv3-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-integration/src/adyenv3/adyenv3-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-integration/src/adyenv3/create-adyenv3-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/create-apple-pay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/util-types/guard.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/hosted-form/hosted-field-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/is-hosted-card-field-options-map.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/is-hosted-stored-card-field-options-map.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/types.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-constants.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-hosted-form.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/is-bluesnap-direct-input-validation-error-description.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-hosted-input-validator.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-name-on-card-input.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/is-array-of-allowed-props.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/create-bluesnap-direct-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-ecp-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/is-bluesnap-direct-ecp-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/create-bluesnap-direct-ecp-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-apm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/is-bluesnap-direct-provider-data.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-iframe-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/create-bluesnap-direct-apm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"local-storage-fallback\"","webpack://@bigcommerce/checkout-sdk/./packages/analytics/src/analytics-extra-items-manager.ts","webpack://@bigcommerce/checkout-sdk/./packages/analytics/src/is-analytics-step-tracker-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/is-with-account-creation.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/is-bolt-payment-data.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/create-bolt-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/is-us-bank-account-instrument-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal-ach/braintree-paypal-ach-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal-ach/create-braintree-paypal-ach-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-local-payment-methods/braintree-local-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/ui/src/loading-indicator/loading-indicator.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-local-payment-methods/create-braintree-local-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/credit-card-integration/src/credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/credit-card-integration/src/create-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/external-integration/src/external-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/external-integration/src/is-additional-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/external-integration/src/create-external-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/legacy-integration/src/legacy-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/legacy-integration/src/create-legacy-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/no-payment-integration/src/no-payment-data-required-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/no-payment-integration/src/create-no-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/offline-integration/src/offline-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/offline-integration/src/create-offline-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/payment-status-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/offsite-integration/src/offsite-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/offsite-integration/src/create-offsite-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/paypal-commerce-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/create-paypal-commerce-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit/paypal-commerce-credit-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit/create-paypal-commerce-credit-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-venmo/paypal-commerce-venmo-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-venmo/create-paypal-commerce-venmo-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/timeout-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-alternative-methods/paypal-commerce-alternative-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-alternative-methods/create-paypal-commerce-alternative-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/hosted-form/is-credit-card-form-fields.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit-card/paypal-commerce-credit-cards-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/utility/object-with-kebab-case-keys.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit-card/create-paypal-commerce-credit-cards-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/sezzle-integration/src/sezzle-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/sezzle-integration/src/create-sezzle-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-execute-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/squarev2-integration/src/squarev2-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/squarev2-integration/src/squarev2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/squarev2-integration/src/squarev2-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/squarev2-integration/src/is-squarev2-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/squarev2-integration/src/create-squarev2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/geography/country-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/geography/country-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/geography/country-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/create-payment-strategy-registry-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/errors/order-finalization-not-required-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/storage/browser-storage.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/ppsdk-payment-method.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/storefront-payment-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/adyenv2/adyenv2-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/adyenv3/adyenv3-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/errors/payment-argument-invalid-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/errors/payment-method-cancelled-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/affirm/affirm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/affirm/affirm-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/affirm/affirmJs.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/errors/order-finalization-not-completed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/afterpay/afterpay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/afterpay/afterpay-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/amazon-pay-v2/amazon-pay-v2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/credit-card/credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/barclays/barclays-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-status-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/bluesnapv2/bluesnapv2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/bnz/bnz-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/ui/src/overlay/overlay.ts","webpack://@bigcommerce/checkout-sdk/./packages/ui/src/overlay/overlay-style.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/errors/payment-invalid-form-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-payment-options.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-regular-field.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/is-braintree-form-fields-map.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-hosted-form.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"@braintree/browser-detection\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/is-credit-card-instrument-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/is-hosted-intrument-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/is-braintree-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-paypal-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-venmo-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-visacheckout-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cardinal/cardinal-three-d-secure-flow-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/is-credit-card-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cardinal/cardinal.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cardinal/cardinal-client.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cardinal/cardinal-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cardinal/cardinal-three-d-secure-flow.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/errors/payment-method-declined-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cba-mpgs/cba-mpgs.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cba-mpgs/cba-mpgs-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cba-mpgs/cba-mpgs-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/chasepay/chasepay.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/chasepay/chasepay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-response-body.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/checkoutcom-custom/checkoutcom-custom-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/checkoutcom-custom/checkoutcom-apm/checkoutcom-apm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/checkoutcom-custom/checkoutcom-sepa/checkoutcom-fawry-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/checkoutcom-custom/checkoutcom-ideal/checkoutcom-ideal-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/checkoutcom-custom/checkoutcom-sepa/checkoutcom-sepa-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/clearpay/clearpay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/clearpay/clearpay-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/converge/converge-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/credit-card-redirect/credit-card-redirect-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cybersource/cybersource-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cybersourcev2/cybersourcev2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/digitalriver/digitalriver.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/digitalriver/digitalriver-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/digitalriver/digitalriver-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/digitalriver/digitalriver-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/browser-info/get-browser-info.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-adyenv2-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-adyenv3-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-checkoutcom-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/humm/humm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/klarnav2/klarna-supported-countries.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/klarna/klarna-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/klarna/klarna-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/klarnav2/klarnav2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/klarnav2/klarnav2-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/klarnav2/klarnav2-token-updater.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/masterpass/masterpass-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/mollie/mollie-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/mollie/mollie-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/moneris/moneris-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/opy/opy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/opy/opy-payment-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/opy/opy-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/opy/opy-library.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/opy/opy-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/paypal/paypal-pro-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/paypal/paypal-express-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/paypal/paypal-script-loader.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"query-string\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/continue-handler/redirect/RedirectionState.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/ppsdk-sub-strategy-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/continue-handler/continue-handler.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/continue-handler/redirect/redirect.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/continue-handler/human-verification/human-verification.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/step-handler.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/success.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/failure.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/create-step-handler.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/ppsdk-completed-payments.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/ppsdk-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/get-ppsdk-payment-method.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/ppsdk-sub-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/initialization-strategies/card.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/initialization-strategies/none.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/sub-strategies/card-sub-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/sub-strategies/none-sub-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/create-ppsdk-sub-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/ppsdk-payment-resumer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/quadpay/quadpay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/sage-pay/sage-pay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/timeout-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/square/square-form.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/square/square-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/square/square-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/stripe-upe/stripe-upe-supported-locales.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/stripe-upe/format-locale.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/stripe-upe/stripe-upe-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/stripev3/stripev3.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/stripev3/stripev3-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/stripev3/stripev3-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/stripev3/stripev3-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/wepay/wepay-risk-client.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/wepay/wepay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/worldpayaccess/worldpayaccess-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/zip/zip-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/date-time/is-future.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/date-time/add-minutes.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-response-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/map-to-paypal-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/map-to-bank-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/map-to-card-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-country-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-country-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-country-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-strategy-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-strategy-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/strategies/amazon-pay-v2/amazon-pay-v2-shipping-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/strategies/default/default-shipping-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/strategies/stripe-upe/stripe-upe-shipping-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-request-sender.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"reselect\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/selector/with-memoized-combiner.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/selector/create-selector.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"shallowequal\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/selector/create-shallow-equal-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/error-message-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/to-single-line.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-checkout-service-error-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-store-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-store-error-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-store-status-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-checkout-selectors.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/unrecoverable-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/map-from-internal-error-response.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/request-error-factory.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/map-from-storefront-error-response.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/omit-deep.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/clear-error-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/is-equal.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/replace.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/object-set.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/array-replace.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/object-merge.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/config/config-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/config/config-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/coupon-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/coupon-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/gift-certificate-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/gift-certificate-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-strategy-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-strategy-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/form/form-fields-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/form/form-fields-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/geography/country-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/geography/country-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order-billing-address/order-billing-address-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order-billing-address/order-billing-address-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/merge-or-push.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/object-flatten.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/object-with-sorted-keys.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-country-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-country-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-strategy-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-strategy-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/store-credit/store-credit-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/create-freeze-proxy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/supported-payment-instruments.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/address/is-address-equal.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/store-credit/store-credit-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-internal-checkout-selectors.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/coupon-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-address-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order-billing-address/order-billing-address-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/config/config-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/geography/country-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-strategy-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/gift-certificate-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/form/form-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-country-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-strategy-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/store-credit/store-credit-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-checkout-store.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/create-request-error-factory.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-action-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-checkout-store-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-checkout-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/create-customer-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/create-payment-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/create-braintree-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/create-shipping-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/cache-key-maps.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/cache-key-resolver.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/selector/selector-decorator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/is-private.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-error-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-status-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/create-checkout-button-selectors.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/is-element-id.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/set-unique-element-id.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-strategy-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/errors/buy-now-cart-creation-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/amazon-pay-v2/amazon-pay-v2-button-options.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/amazon-pay-v2/errors/amazon-pay-v2-config-creation-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/amazon-pay-v2/amazon-pay-v2-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/amazon-pay-v2/amazon-pay-v2-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/braintree/get-valid-button-style.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/braintree/braintree-paypal-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/braintree/braintree-paypal-credit-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/braintree/braintree-venmo-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/googlepay/googlepay-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/masterpass/masterpass-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/paypal/paypal-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/create-apple-pay-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/create-bolt-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/paypal-commerce-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/create-paypal-commerce-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit/paypal-commerce-credit-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit/create-paypal-commerce-credit-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-venmo/paypal-commerce-venmo-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-venmo/create-paypal-commerce-venmo-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-alternative-methods/paypal-commerce-alternative-methods-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-alternative-methods/create-paypal-commerce-alternative-methods-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-express-integration/src/paypal-express-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-express-integration/src/paypal-express-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-express-integration/src/paypal-express-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-express-integration/src/create-paypal-express-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/create-checkout-button-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/create-checkout-button-registry-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/create-checkout-button-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/embedded-checkout-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/errors/invalid-login-token-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/errors/not-embeddable-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/iframe-content/embedded-content-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/embedded-checkout.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/resizable-iframe-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-resizer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/embed-checkout.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/iframe-content/handle-frame-loaded-event.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/custom-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/iframe-content/iframe-embedded-checkout-messenger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/iframe-content/noop-embedded-checkout-messenger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/iframe-content/create-embedded-checkout-messenger.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"messageformat\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/locale/language-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/locale/create-language-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/currency/currency-formatter.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/currency/currency-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/currency/create-currency-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/analytics/analytics-tracker-ga.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/analytics/analytics-step-tracker.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/analytics/noop-step-tracker.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/analytics/create-step-tracker.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/bodl/analytics-steps.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/bodl/bodl-emitter-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/bodl/noop-bodl-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/bodl/create-bodl-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/bodl/is-bodl-enabled.ts"],"sourcesContent":["module.exports = require(\"iframe-resizer\");","module.exports = require(\"iframe-resizer/js/iframeResizer.contentWindow\");","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@bigcommerce/request-sender\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@bigcommerce/script-loader\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"tslib\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@bigcommerce/data-store\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"rxjs\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"rxjs/operators\");","import { Action, createErrorAction } from '@bigcommerce/data-store';\nimport { concat, Observable, of, throwError } from 'rxjs';\n\nexport default function throwErrorAction(\n type: TType,\n error?: TPayload,\n meta?: TMeta,\n): Observable> {\n if (isErrorAction(error)) {\n return concat(of(error), throwError(createErrorAction(type, error.payload, meta)));\n }\n\n return throwError(createErrorAction(type, error, meta));\n}\n\nfunction isErrorAction(action: any): action is Action {\n return action && action.type && action.error;\n}\n","import { setPrototypeOf } from '../../utility';\n\nimport CustomError from './custom-error';\n\n/**\n * This error type should not be constructed directly. It is a base class for\n * all custom errors thrown in this library.\n */\nexport default abstract class StandardError extends Error implements CustomError {\n name = 'StandardError';\n type = 'standard';\n\n constructor(message?: string) {\n super(message || 'An unexpected error has occurred.');\n\n setPrototypeOf(this, new.target.prototype);\n\n if (typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(this, new.target);\n } else {\n this.stack = new Error(this.message).stack;\n }\n }\n}\n","export default function setPrototypeOf(object: any, prototype: object) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(object, prototype);\n } else {\n object.__proto__ = prototype;\n }\n\n return object;\n}\n","import StandardError from './standard-error';\n\nexport enum MissingDataErrorType {\n MissingBillingAddress,\n MissingCart,\n MissingCheckout,\n MissingConsignments,\n MissingCustomer,\n MissingCheckoutConfig,\n MissingOrder,\n MissingOrderConfig,\n MissingOrderId,\n MissingPayment,\n MissingPaymentId,\n MissingPaymentInstrument,\n MissingPaymentMethod,\n MissingPaymentRedirectUrl,\n MissingPaymentStatus,\n MissingPaymentToken,\n MissingShippingAddress,\n}\n\n/**\n * Throw this error when data that is expected to exist is missing. Usually it\n * is due to the fact that certain data has not been retrieved from or saved to\n * the server yet. And such data is required to perform certain actions.\n */\nexport default class MissingDataError extends StandardError {\n constructor(public subtype: MissingDataErrorType) {\n super(getErrorMessage(subtype));\n\n this.name = 'MissingDataError';\n this.type = 'missing_data';\n }\n}\n\nfunction getErrorMessage(type: MissingDataErrorType): string {\n switch (type) {\n case MissingDataErrorType.MissingBillingAddress:\n return 'Unable to proceed because billing address data is unavailable.';\n\n case MissingDataErrorType.MissingCart:\n return 'Unable to proceed because cart data is unavailable.';\n\n case MissingDataErrorType.MissingConsignments:\n return 'Unable to proceed because consignments data is unavailable.';\n\n case MissingDataErrorType.MissingCheckout:\n return 'Unable to proceed because checkout data is unavailable.';\n\n case MissingDataErrorType.MissingCustomer:\n return 'Unable to proceed because customer data is unavailable.';\n\n case MissingDataErrorType.MissingCheckoutConfig:\n case MissingDataErrorType.MissingOrderConfig:\n return 'Unable to proceed because configuration data is unavailable.';\n\n case MissingDataErrorType.MissingOrder:\n return 'Unable to proceed because order data is unavailable.';\n\n case MissingDataErrorType.MissingOrderId:\n return 'Unable to proceed because order ID is unavailable or not generated yet.';\n\n case MissingDataErrorType.MissingPayment:\n return 'Unable to proceed because payment data is unavailable.';\n\n case MissingDataErrorType.MissingPaymentToken:\n return 'Unable to proceed because the token required to submit a payment is missing.';\n\n case MissingDataErrorType.MissingPaymentMethod:\n return 'Unable to proceed because payment method data is unavailable or not properly configured.';\n\n case MissingDataErrorType.MissingShippingAddress:\n return 'Unable to proceed because shipping address data is unavailable.';\n\n default:\n return 'Unable to proceed because the required data is unavailable.';\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Checkout } from '../checkout';\n\nexport enum BillingAddressActionType {\n UpdateBillingAddressRequested = 'UPDATE_BILLING_ADDRESS_REQUESTED',\n UpdateBillingAddressSucceeded = 'UPDATE_BILLING_ADDRESS_SUCCEEDED',\n UpdateBillingAddressFailed = 'UPDATE_BILLING_ADDRESS_FAILED',\n\n ContinueAsGuestRequested = 'CONTINUE_AS_GUEST_REQUESTED',\n ContinueAsGuestSucceeded = 'CONTINUE_AS_GUEST_SUCCEEDED',\n ContinueAsGuestFailed = 'CONTINUE_AS_GUEST_FAILED',\n}\n\nexport type BillingAddressAction = ContinueAsGuestAction | UpdateBillingAddressAction;\n\nexport type UpdateBillingAddressAction =\n | UpdateBillingAddressRequested\n | UpdateBillingAddressSucceeded\n | UpdateBillingAddressFailed;\n\nexport type ContinueAsGuestAction =\n | ContinueAsGuestRequested\n | ContinueAsGuestSucceeded\n | ContinueAsGuestFailed;\n\nexport interface UpdateBillingAddressRequested extends Action {\n type: BillingAddressActionType.UpdateBillingAddressRequested;\n}\n\nexport interface UpdateBillingAddressSucceeded extends Action {\n type: BillingAddressActionType.UpdateBillingAddressSucceeded;\n}\n\nexport interface UpdateBillingAddressFailed extends Action {\n type: BillingAddressActionType.UpdateBillingAddressFailed;\n}\n\nexport interface ContinueAsGuestRequested extends Action {\n type: BillingAddressActionType.ContinueAsGuestRequested;\n}\n\nexport interface ContinueAsGuestSucceeded extends Action {\n type: BillingAddressActionType.ContinueAsGuestSucceeded;\n}\n\nexport interface ContinueAsGuestFailed extends Action {\n type: BillingAddressActionType.ContinueAsGuestFailed;\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when a shopper tries to sign in as a guest but\n * they are already signed in as a registered customer.\n */\nexport default class UnableToContinueAsGuestError extends StandardError {\n constructor(message?: string) {\n super(\n message || 'Unable to continue as a guest because the customer is already signed in.',\n );\n\n this.name = 'UnableToContinueAsGuestError';\n this.type = 'unable_to_continue_as_guest';\n }\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Response } from '@bigcommerce/request-sender';\nimport { concat, defer, empty, merge, Observable, Observer, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { Checkout, InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\nimport { GuestCredentials } from '../customer';\nimport { SubscriptionsActionCreator, UpdateSubscriptionsAction } from '../subscription';\n\nimport { BillingAddressUpdateRequestBody } from './billing-address';\nimport {\n BillingAddressActionType,\n ContinueAsGuestAction,\n UpdateBillingAddressAction,\n} from './billing-address-actions';\nimport { UnableToContinueAsGuestError } from './errors';\n\nimport { BillingAddressRequestSender } from '.';\n\nexport default class BillingAddressActionCreator {\n constructor(\n private _requestSender: BillingAddressRequestSender,\n private _subscriptionActionCreator: SubscriptionsActionCreator,\n ) {}\n\n continueAsGuest(\n credentials: GuestCredentials,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const customer = state.customer.getCustomer();\n\n if (customer && !customer.isGuest) {\n throw new UnableToContinueAsGuestError();\n }\n\n const billingAddress = state.billingAddress.getBillingAddress();\n\n let billingAddressRequestBody: Partial;\n\n if (!billingAddress) {\n billingAddressRequestBody = credentials;\n } else {\n const { country, ...existingBillingAddressRequestBody } = billingAddress;\n\n billingAddressRequestBody = {\n ...existingBillingAddressRequestBody,\n ...credentials,\n };\n }\n\n return merge(\n concat(\n of(createAction(BillingAddressActionType.ContinueAsGuestRequested)),\n defer(async () => {\n const { body } = await this._createOrUpdateBillingAddress(\n checkout.id,\n billingAddressRequestBody,\n options,\n );\n\n return createAction(\n BillingAddressActionType.ContinueAsGuestSucceeded,\n body,\n );\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(BillingAddressActionType.ContinueAsGuestFailed, error),\n ),\n ),\n this._updateCustomerConsent(credentials, options),\n );\n };\n }\n\n updateAddress(\n address: Partial,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(createAction(BillingAddressActionType.UpdateBillingAddressRequested));\n\n const billingAddress = state.billingAddress.getBillingAddress();\n\n // If email is not present in the address provided by the client, then\n // fall back to the stored email as it could have been set separately\n // using a convenience method. We can't rely on billingAddress having\n // an ID to consider that there's a preexisting email, as billingAddress\n // object from Order doesn't have an ID.\n const billingAddressRequestBody = {\n ...address,\n email:\n typeof address.email === 'undefined' && billingAddress\n ? billingAddress.email\n : address.email,\n };\n\n if (billingAddress && billingAddress.id) {\n billingAddressRequestBody.id = billingAddress.id;\n }\n\n this._createOrUpdateBillingAddress(checkout.id, billingAddressRequestBody, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n BillingAddressActionType.UpdateBillingAddressSucceeded,\n body,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n BillingAddressActionType.UpdateBillingAddressFailed,\n response,\n ),\n );\n });\n });\n }\n\n private _updateCustomerConsent(\n { email, acceptsAbandonedCartEmails, acceptsMarketingNewsletter }: GuestCredentials,\n options?: RequestOptions,\n ): Observable {\n if (\n (acceptsAbandonedCartEmails === undefined || acceptsAbandonedCartEmails === null) &&\n (acceptsMarketingNewsletter === undefined || acceptsMarketingNewsletter === null)\n ) {\n return empty();\n }\n\n return this._subscriptionActionCreator.updateSubscriptions(\n {\n email,\n acceptsMarketingNewsletter: acceptsMarketingNewsletter || false,\n acceptsAbandonedCartEmails: acceptsAbandonedCartEmails || false,\n },\n options,\n );\n }\n\n private _createOrUpdateBillingAddress(\n checkoutId: string,\n address: Partial,\n options?: RequestOptions,\n ): Promise> {\n if (!address.id) {\n return this._requestSender.createAddress(checkoutId, address, options);\n }\n\n return this._requestSender.updateAddress(checkoutId, address, options);\n }\n}\n","enum ContentType {\n Json = 'application/json',\n JsonV1 = 'application/vnd.bc.v1+json',\n}\n\nexport default ContentType;\n","export const SDK_VERSION_HEADERS = { 'X-Checkout-SDK-Version': LIBRARY_VERSION };\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { AddressRequestBody } from '../address';\nimport { Checkout } from '../checkout';\nimport { ContentType, RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nimport { BillingAddressUpdateRequestBody } from './billing-address';\n\nconst DEFAULT_PARAMS = {\n include: [\n 'cart.lineItems.physicalItems.options',\n 'cart.lineItems.digitalItems.options',\n 'customer',\n 'promotions.banners',\n ].join(','),\n};\n\nexport default class BillingAddressRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n createAddress(\n checkoutId: string,\n address: Partial,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/billing-address`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, {\n body: address,\n params: DEFAULT_PARAMS,\n headers,\n timeout,\n });\n }\n\n updateAddress(\n checkoutId: string,\n address: Partial,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const { id, ...body } = address;\n const url = `/api/storefront/checkouts/${checkoutId}/billing-address/${id}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.put(url, { params: DEFAULT_PARAMS, body, headers, timeout });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nexport enum ErrorActionType {\n ClearError = 'CLEAR_ERROR',\n}\n\nexport type ErrorAction = ClearErrorAction;\n\nexport interface ClearErrorAction extends Action {\n type: ErrorActionType.ClearError;\n payload: Error;\n}\n","import { ClearErrorAction, ErrorActionType } from './error-actions';\n\nexport default class ErrorActionCreator {\n clearError(error: Error): ClearErrorAction {\n return {\n type: ErrorActionType.ClearError,\n payload: error,\n };\n }\n}\n","export default function getEnvironment(): string {\n try {\n return process.env.NODE_ENV || 'development';\n } catch (e) {\n return 'development';\n }\n}\n","import Logger from './logger';\n\nexport default class ConsoleLogger implements Logger {\n constructor(private _console?: Console) {}\n\n log(...messages: any[]): void {\n this._logToConsole('log', ...messages);\n }\n\n info(...messages: any[]): void {\n this._logToConsole('info', ...messages);\n }\n\n warn(...messages: any[]): void {\n this._logToConsole('warn', ...messages);\n }\n\n error(...messages: any[]): void {\n this._logToConsole('error', ...messages);\n }\n\n debug(...messages: any[]): void {\n this._logToConsole('debug', ...messages);\n }\n\n private _logToConsole(type: keyof Console, ...messages: any[]): void {\n if (!this._console || !this._console[type]) {\n return;\n }\n\n this._console[type].call(this._console, ...messages);\n }\n}\n","import Logger from './logger';\n\nexport default class NoopLogger implements Logger {\n log(): void {}\n\n info(): void {}\n\n warn(): void {}\n\n error(): void {}\n\n debug(): void {}\n}\n","import { getEnvironment } from '../utility';\n\nimport createLogger from './create-logger';\nimport Logger from './logger';\n\nconst logger = createLogger(getEnvironment() !== 'test');\n\nexport default function getDefaultLogger(): Logger {\n return logger;\n}\n","import ConsoleLogger from './console-logger';\nimport Logger from './logger';\nimport NoopLogger from './noop-logger';\n\nexport default function createLogger(isEnabled = true): Logger {\n if (!isEnabled) {\n return new NoopLogger();\n }\n\n return new ConsoleLogger(console);\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@bigcommerce/memoize\");","import cacheAction from './cache-action';\nimport isActionOptions from './is-action-options';\n\nexport default function cachableActionDecorator any>(\n _: object,\n key: string,\n descriptor: TypedPropertyDescriptor,\n): TypedPropertyDescriptor {\n const memoizedMethods = new WeakMap();\n\n function decorateMethod(this: object, method: TMethod): TMethod {\n return ((...args: any[]) => {\n const lastArg = args[args.length - 1];\n const { useCache } = isActionOptions(lastArg) ? lastArg : { useCache: false };\n\n if (!useCache) {\n return method.call(this, ...args);\n }\n\n const instanceMethods = memoizedMethods.get(this) || {};\n\n if (!memoizedMethods.get(this)) {\n memoizedMethods.set(this, instanceMethods);\n }\n\n if (!instanceMethods[key]) {\n instanceMethods[key] = cacheAction(method);\n }\n\n return instanceMethods[key].call(this, ...args);\n }) as TMethod;\n }\n\n return {\n get() {\n if (typeof descriptor.value !== 'function') {\n throw new Error('Decorator should be used in functions');\n }\n\n const value = decorateMethod.call(this, descriptor.value);\n\n Object.defineProperty(this, key, { ...descriptor, value });\n\n return value;\n },\n };\n}\n","import ActionOptions from './action-options';\n\nexport default function isActionOptions(param: any): param is ActionOptions {\n return param && typeof param.useCache === 'boolean';\n}\n","import { Action, ThunkAction } from '@bigcommerce/data-store';\nimport { memoize } from '@bigcommerce/memoize';\nimport { from, Observable } from 'rxjs';\nimport { shareReplay } from 'rxjs/operators';\n\nexport default function cacheAction(fn: TFunction): TFunction {\n function decoratedFn(this: any, ...args: any[]) {\n const action = fn.call(this, ...args);\n\n if (action instanceof Observable) {\n return from(action).pipe(shareReplay());\n }\n\n if (typeof action === 'function') {\n return memoize((store) => from(action(store)).pipe(shareReplay()));\n }\n\n return action;\n }\n\n return memoize(decoratedFn as TFunction);\n}\n\ntype CreateActionFn = (...args: any[]) => Observable | ThunkAction | Action;\n","import { Action } from '@bigcommerce/data-store';\n\nimport Config from './config';\n\nexport enum ConfigActionType {\n LoadConfigRequested = 'LOAD_CONFIG_REQUESTED',\n LoadConfigSucceeded = 'LOAD_CONFIG_SUCCEEDED',\n LoadConfigFailed = 'LOAD_CONFIG_FAILED',\n}\n\nexport type LoadConfigAction =\n | LoadConfigRequestedAction\n | LoadConfigSucceededAction\n | LoadConfigFailedAction;\n\nexport interface LoadConfigRequestedAction extends Action {\n type: ConfigActionType.LoadConfigRequested;\n}\n\nexport interface LoadConfigSucceededAction extends Action {\n type: ConfigActionType.LoadConfigSucceeded;\n}\n\nexport interface LoadConfigFailedAction extends Action {\n type: ConfigActionType.LoadConfigFailed;\n}\n","import { createAction, createErrorAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { ActionOptions, cachableAction } from '../common/data-store';\nimport { RequestOptions } from '../common/http-request';\n\nimport { ConfigActionType, LoadConfigAction } from './config-actions';\n\nimport { ConfigRequestSender } from '.';\n\nexport default class ConfigActionCreator {\n constructor(private _configRequestSender: ConfigRequestSender) {}\n\n @cachableAction\n loadConfig(options?: RequestOptions & ActionOptions): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(createAction(ConfigActionType.LoadConfigRequested));\n\n this._configRequestSender\n .loadConfig(options)\n .then((response) => {\n observer.next(\n createAction(ConfigActionType.LoadConfigSucceeded, response.body),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(createErrorAction(ConfigActionType.LoadConfigFailed, response));\n });\n });\n }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport StandardError from './standard-error';\n\nconst DEFAULT_RESPONSE = {\n body: {},\n headers: {},\n status: 0,\n};\n\n/**\n * Throw this error if we are unable to make a request to the server. It wraps\n * any server response into a JS error object.\n */\nexport default class RequestError extends StandardError {\n body: TBody | {};\n headers: { [key: string]: any };\n errors: Array<{ code: string; message?: string }>;\n status: number;\n\n constructor(\n response?: Response,\n {\n message,\n errors,\n }: {\n message?: string;\n errors?: Array<{ code: string; message?: string }>;\n } = {},\n ) {\n const { body, headers, status } = response || DEFAULT_RESPONSE;\n\n super(message || 'An unexpected error has occurred.');\n\n this.name = 'RequestError';\n this.type = 'request';\n this.body = body;\n this.headers = headers;\n this.status = status;\n this.errors = errors || [];\n }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { InternalErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RequestError } from '../../common/error/errors';\n\n/**\n * Throw this error when we are unable to retrieve a checkout object from the\n * server using the provided ID. It could be because the shopper does not have\n * permission to view the object, or the ID itself is invalid.\n */\nexport default class CheckoutNotAvailableError extends RequestError {\n constructor(response: Response) {\n super(response, { message: response.body.title });\n\n this.name = 'CheckoutNotAvailableError';\n this.type = 'checkout_not_available';\n }\n}\n","export const INTERNAL_USE_ONLY =\n 'This API endpoint is for internal use only and may change in the future';\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { CheckoutNotAvailableError } from '../checkout/errors';\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport Config from './config';\n\nexport default class ConfigRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n loadConfig({ timeout, params }: RequestOptions = {}): Promise> {\n const url = '/api/storefront/checkout-settings';\n\n return this._requestSender\n .get(url, {\n timeout,\n headers: {\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n params,\n })\n .catch((error) => {\n if (error.status >= 400 && error.status < 500) {\n throw new CheckoutNotAvailableError(error);\n }\n\n throw error;\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Checkout } from '../checkout';\nimport { RequestError } from '../common/error/errors';\n\nexport enum CouponActionType {\n ApplyCouponRequested = 'APPLY_COUPON_REQUESTED',\n ApplyCouponSucceeded = 'APPLY_COUPON_SUCCEEDED',\n ApplyCouponFailed = 'APPLY_COUPON_FAILED',\n\n RemoveCouponRequested = 'REMOVE_COUPON_REQUESTED',\n RemoveCouponSucceeded = 'REMOVE_COUPON_SUCCEEDED',\n RemoveCouponFailed = 'REMOVE_COUPON_FAILED',\n}\n\nexport type CouponAction = ApplyCouponAction | RemoveCouponAction;\n\nexport type ApplyCouponAction =\n | ApplyCouponRequestedAction\n | ApplyCouponSucceededAction\n | ApplyCouponFailedAction;\n\nexport type RemoveCouponAction =\n | RemoveCouponRequestedAction\n | RemoveCouponSucceededAction\n | RemoveCouponFailedAction;\n\nexport interface ApplyCouponRequestedAction extends Action {\n type: CouponActionType.ApplyCouponRequested;\n}\n\nexport interface ApplyCouponSucceededAction extends Action {\n type: CouponActionType.ApplyCouponSucceeded;\n}\n\nexport interface ApplyCouponFailedAction extends Action> {\n type: CouponActionType.ApplyCouponFailed;\n}\n\nexport interface RemoveCouponRequestedAction extends Action {\n type: CouponActionType.RemoveCouponRequested;\n}\n\nexport interface RemoveCouponSucceededAction extends Action {\n type: CouponActionType.RemoveCouponSucceeded;\n}\n\nexport interface RemoveCouponFailedAction extends Action {\n type: CouponActionType.RemoveCouponFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\n\nimport {\n ApplyCouponAction,\n CouponAction,\n CouponActionType,\n RemoveCouponAction,\n} from './coupon-actions';\nimport CouponRequestSender from './coupon-request-sender';\n\nexport default class CouponActionCreator {\n constructor(private _couponRequestSender: CouponRequestSender) {}\n\n applyCoupon(\n code: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(createAction(CouponActionType.ApplyCouponRequested));\n\n this._couponRequestSender\n .applyCoupon(checkout.id, code, options)\n .then(({ body }) => {\n observer.next(createAction(CouponActionType.ApplyCouponSucceeded, body));\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(CouponActionType.ApplyCouponFailed, response),\n );\n });\n });\n }\n\n removeCoupon(\n code: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(createAction(CouponActionType.RemoveCouponRequested));\n\n this._couponRequestSender\n .removeCoupon(checkout.id, code, options)\n .then(({ body }) => {\n observer.next(createAction(CouponActionType.RemoveCouponSucceeded, body));\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(CouponActionType.RemoveCouponFailed, response),\n );\n });\n });\n }\n}\n","const CHECKOUT_DEFAULT_INCLUDES = [\n 'cart.lineItems.physicalItems.options',\n 'cart.lineItems.digitalItems.options',\n 'customer',\n 'customer.customerGroup',\n 'payments',\n 'promotions.banners',\n];\n\nexport default CHECKOUT_DEFAULT_INCLUDES;\n","export enum CheckoutIncludes {\n AvailableShippingOptions = 'consignments.availableShippingOptions',\n PhysicalItemsCategoryNames = 'cart.lineItems.physicalItems.categoryNames',\n DigitalItemsCategoryNames = 'cart.lineItems.digitalItems.categoryNames',\n}\n\nexport default interface CheckoutParams {\n include?: CheckoutIncludes[] | CheckoutIncludeParam;\n}\n\nexport type CheckoutIncludeParam = {\n [key in CheckoutIncludes]?: boolean;\n};\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"lodash\");","import { uniq } from 'lodash';\n\nexport default function joinIncludes(includes: T[]): string {\n return uniq(includes).join(',');\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Checkout, CHECKOUT_DEFAULT_INCLUDES, CheckoutIncludes } from '../checkout';\nimport {\n ContentType,\n joinIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nexport default class CouponRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n applyCoupon(\n checkoutId: string,\n couponCode: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/coupons`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes([\n ...CHECKOUT_DEFAULT_INCLUDES,\n CheckoutIncludes.AvailableShippingOptions,\n ]),\n },\n body: { couponCode },\n });\n }\n\n removeCoupon(\n checkoutId: string,\n couponCode: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/coupons/${couponCode}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.delete(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes([\n ...CHECKOUT_DEFAULT_INCLUDES,\n CheckoutIncludes.AvailableShippingOptions,\n ]),\n },\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Checkout } from '../checkout';\nimport { RequestError } from '../common/error/errors';\n\nexport enum GiftCertificateActionType {\n ApplyGiftCertificateRequested = 'APPLY_GIFT_CERTIFICATE_REQUESTED',\n ApplyGiftCertificateSucceeded = 'APPLY_GIFT_CERTIFICATE_SUCCEEDED',\n ApplyGiftCertificateFailed = 'APPLY_GIFT_CERTIFICATE_FAILED',\n\n RemoveGiftCertificateRequested = 'REMOVE_GIFT_CERTIFICATE_REQUESTED',\n RemoveGiftCertificateSucceeded = 'REMOVE_GIFT_CERTIFICATE_SUCCEEDED',\n RemoveGiftCertificateFailed = 'REMOVE_GIFT_CERTIFICATE_FAILED',\n}\n\nexport type GiftCertificateAction = ApplyGiftCertificateAction | RemoveGiftCertificateAction;\n\nexport type ApplyGiftCertificateAction =\n | ApplyGiftCertificateRequestedAction\n | ApplyGiftCertificateSucceededAction\n | ApplyGiftCertificateFailedAction;\n\nexport type RemoveGiftCertificateAction =\n | RemoveGiftCertificateRequestedAction\n | RemoveGiftCertificateSucceededAction\n | RemoveGiftCertificateFailedAction;\n\nexport interface ApplyGiftCertificateRequestedAction extends Action {\n type: GiftCertificateActionType.ApplyGiftCertificateRequested;\n}\n\nexport interface ApplyGiftCertificateSucceededAction extends Action {\n type: GiftCertificateActionType.ApplyGiftCertificateSucceeded;\n}\n\nexport interface ApplyGiftCertificateFailedAction\n extends Action> {\n type: GiftCertificateActionType.ApplyGiftCertificateFailed;\n}\n\nexport interface RemoveGiftCertificateRequestedAction extends Action {\n type: GiftCertificateActionType.RemoveGiftCertificateRequested;\n}\n\nexport interface RemoveGiftCertificateSucceededAction extends Action {\n type: GiftCertificateActionType.RemoveGiftCertificateSucceeded;\n}\n\nexport interface RemoveGiftCertificateFailedAction\n extends Action> {\n type: GiftCertificateActionType.RemoveGiftCertificateFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\n\nimport {\n ApplyGiftCertificateAction,\n GiftCertificateActionType,\n RemoveGiftCertificateAction,\n} from './gift-certificate-actions';\n\nimport { GiftCertificateRequestSender } from '.';\n\nexport default class GiftCertificateActionCreator {\n constructor(private _giftCertificateRequestSender: GiftCertificateRequestSender) {}\n\n applyGiftCertificate(\n giftCertificate: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(\n createAction(GiftCertificateActionType.ApplyGiftCertificateRequested),\n );\n\n this._giftCertificateRequestSender\n .applyGiftCertificate(checkout.id, giftCertificate, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n GiftCertificateActionType.ApplyGiftCertificateSucceeded,\n body,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n GiftCertificateActionType.ApplyGiftCertificateFailed,\n response,\n ),\n );\n });\n });\n }\n\n removeGiftCertificate(\n giftCertificate: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(\n createAction(GiftCertificateActionType.RemoveGiftCertificateRequested),\n );\n\n this._giftCertificateRequestSender\n .removeGiftCertificate(checkout.id, giftCertificate, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n GiftCertificateActionType.RemoveGiftCertificateSucceeded,\n body,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n GiftCertificateActionType.RemoveGiftCertificateFailed,\n response,\n ),\n );\n });\n });\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Checkout, CHECKOUT_DEFAULT_INCLUDES } from '../checkout';\nimport {\n ContentType,\n joinIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nexport default class GiftCertificateRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n applyGiftCertificate(\n checkoutId: string,\n giftCertificateCode: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/gift-certificates`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n },\n body: { giftCertificateCode },\n });\n }\n\n removeGiftCertificate(\n checkoutId: string,\n giftCertificateCode: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/gift-certificates/${giftCertificateCode}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.delete(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n },\n });\n }\n}\n","import ResolvableModule from './resolvable-module';\n\nexport default function isResolvableModule(\n module: TModule,\n): module is ResolvableModule {\n return 'resolveIds' in module;\n}\n","import StandardError from './standard-error';\n\n/**\n * This error should be thrown when a method is unable to proceed because the\n * caller has not provided all the arguments according to their requirements,\n * i.e.: if an argument is missing or it is not the expected data type.\n */\nexport default class InvalidArgumentError extends StandardError {\n constructor(message?: string) {\n super(message || 'Invalid arguments have been provided.');\n\n this.name = 'InvalidArgumentError';\n this.type = 'invalid_argument';\n }\n}\n","import { InvalidArgumentError } from '../error/errors';\n\nimport Factory from './factory';\n\nexport default class Registry {\n private _factories: { [key: string]: Factory };\n private _instances: { [key: string]: T };\n private _defaultToken: string;\n private _useFallback: string | boolean;\n private _tokenResolver: (token: string, registeredTokens: string[]) => string | undefined;\n\n constructor(options?: RegistryOptions) {\n this._factories = {};\n this._instances = {};\n this._defaultToken = options?.defaultToken ?? 'default';\n this._useFallback = options?.useFallback ?? true;\n this._tokenResolver = options?.tokenResolver ?? ((token) => token);\n }\n\n get(token?: K, cacheToken?: string): T {\n try {\n return this._getInstance(\n token || this._defaultToken,\n cacheToken || token || this._defaultToken,\n );\n } catch (error) {\n if (!this._useFallback) {\n throw error;\n }\n\n return this._getInstance(this._defaultToken, cacheToken || this._defaultToken);\n }\n }\n\n register(token: K, factory: Factory): void {\n if (this._hasFactory(token)) {\n throw new InvalidArgumentError(`'${token}' is already registered.`);\n }\n\n this._factories[token] = factory;\n }\n\n protected _hasFactory(token: string): boolean {\n return !!this._factories[token];\n }\n\n private _hasInstance(token: string): boolean {\n return !!this._instances[token];\n }\n\n private _getInstance(token: string, cacheToken: string): T {\n if (!this._hasInstance(cacheToken)) {\n const resolvedToken = this._tokenResolver(token, Object.keys(this._factories));\n const factory = resolvedToken && this._factories[resolvedToken];\n\n if (!factory) {\n throw new InvalidArgumentError(`'${token}' is not registered.`);\n }\n\n this._instances[cacheToken] = factory();\n }\n\n return this._instances[cacheToken];\n }\n}\n\nexport interface RegistryOptions {\n defaultToken?: string;\n useFallback?: boolean;\n tokenResolver?(token: string, registeredTokens: string[]): string | undefined;\n}\n","import { getDefaultLogger } from '../log';\nimport { getEnvironment } from '../utility';\n\nimport Factory from './factory';\nimport Registry from './registry';\n\nexport default class ResolveIdRegistry {\n private _registry: Registry;\n\n constructor(private _useFallback = false) {\n this._registry = new Registry({\n tokenResolver: this._resolveToken.bind(this),\n useFallback: this._useFallback,\n });\n }\n\n get(resolveId: TToken): TType {\n return this._registry.get(this._encodeToken(resolveId));\n }\n\n register(resolveId: TToken, factory: Factory): void {\n this._registry.register(this._encodeToken(resolveId), factory);\n }\n\n private _encodeToken(resolveId: TToken): string {\n return btoa(JSON.stringify(resolveId));\n }\n\n private _decodeToken(token: string): TToken {\n return JSON.parse(atob(token));\n }\n\n private _resolveToken(token: string, registeredTokens: string[]): string | undefined {\n const query = this._decodeToken(token);\n\n const results: Array<{ token: string; matches: number; default: boolean }> = [];\n\n registeredTokens.forEach((registeredToken) => {\n const resolverId = this._decodeToken(registeredToken);\n\n const result = { token: registeredToken, matches: 0, default: false };\n\n for (const [key, value] of Object.entries(resolverId)) {\n if (key in query && query[key] !== value) {\n result.matches = 0;\n break;\n }\n\n if (key in query && query[key] === value) {\n result.matches++;\n }\n\n if (key === 'default' && value === true) {\n result.default = true;\n }\n }\n\n results.push(result);\n });\n\n const matchedResults = results\n .sort((a, b) => b.matches - a.matches)\n .filter((result) => result.matches > 0);\n\n if (matchedResults.length > 1 && matchedResults[0].matches === matchedResults[1].matches) {\n if (getEnvironment() === 'development') {\n getDefaultLogger().warn(\n 'The provided query matches at least two strategies with the same specificity. This warning can be resolved by making their resolve ID more specific.',\n );\n }\n }\n\n const matched = matchedResults[0];\n\n if (matched && matched.token) {\n return matched.token;\n }\n\n if (this._useFallback) {\n const defaultToken = results.find((result) => result.default)?.token;\n\n if (defaultToken) {\n return defaultToken;\n }\n }\n\n throw new Error('Unable to resolve to a registered token with the provided token.');\n }\n}\n","import ResolvableModule from './resolvable-module';\n\nexport default function toResolvableModule(\n module: TModule,\n resolveIds: TIdentifier[],\n): ResolvableModule {\n return Object.assign(module, { resolveIds });\n}\n","import CustomError from './custom-error';\nimport setPrototypeOf from './set-prototype-of';\n\n/**\n * This error type should not be constructed directly. It is a base class for\n * all custom errors thrown in this library.\n */\nexport default abstract class StandardError extends Error implements CustomError {\n name = 'StandardError';\n type = 'standard';\n\n constructor(message?: string) {\n super(message || 'An unexpected error has occurred.');\n\n setPrototypeOf(this, new.target.prototype);\n\n if (typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(this, new.target);\n } else {\n this.stack = new Error(this.message).stack;\n }\n }\n}\n","export default function setPrototypeOf(object: any, prototype: object) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(object, prototype);\n } else {\n object.__proto__ = prototype;\n }\n\n return object;\n}\n","import StandardError from './standard-error';\n\nexport enum MissingDataErrorType {\n MissingBillingAddress,\n MissingCart,\n MissingCheckout,\n MissingConsignments,\n MissingCustomer,\n MissingCheckoutConfig,\n MissingOrder,\n MissingOrderConfig,\n MissingOrderId,\n MissingPayment,\n MissingPaymentId,\n MissingPaymentInstrument,\n MissingPaymentMethod,\n MissingPaymentRedirectUrl,\n MissingPaymentStatus,\n MissingPaymentToken,\n MissingShippingAddress,\n}\n\n/**\n * Throw this error when data that is expected to exist is missing. Usually it\n * is due to the fact that certain data has not been retrieved from or saved to\n * the server yet. And such data is required to perform certain actions.\n */\nexport default class MissingDataError extends StandardError {\n constructor(public subtype: MissingDataErrorType) {\n super(getErrorMessage(subtype));\n\n this.name = 'MissingDataError';\n this.type = 'missing_data';\n }\n}\n\nfunction getErrorMessage(type: MissingDataErrorType): string {\n switch (type) {\n case MissingDataErrorType.MissingBillingAddress:\n return 'Unable to proceed because billing address data is unavailable.';\n\n case MissingDataErrorType.MissingCart:\n return 'Unable to proceed because cart data is unavailable.';\n\n case MissingDataErrorType.MissingConsignments:\n return 'Unable to proceed because consignments data is unavailable.';\n\n case MissingDataErrorType.MissingCheckout:\n return 'Unable to proceed because checkout data is unavailable.';\n\n case MissingDataErrorType.MissingCustomer:\n return 'Unable to proceed because customer data is unavailable.';\n\n case MissingDataErrorType.MissingCheckoutConfig:\n case MissingDataErrorType.MissingOrderConfig:\n return 'Unable to proceed because configuration data is unavailable.';\n\n case MissingDataErrorType.MissingOrder:\n return 'Unable to proceed because order data is unavailable.';\n\n case MissingDataErrorType.MissingOrderId:\n return 'Unable to proceed because order ID is unavailable or not generated yet.';\n\n case MissingDataErrorType.MissingPayment:\n return 'Unable to proceed because payment data is unavailable.';\n\n case MissingDataErrorType.MissingPaymentToken:\n return 'Unable to proceed because the token required to submit a payment is missing.';\n\n case MissingDataErrorType.MissingPaymentMethod:\n return 'Unable to proceed because payment method data is unavailable or not properly configured.';\n\n case MissingDataErrorType.MissingShippingAddress:\n return 'Unable to proceed because shipping address data is unavailable.';\n\n default:\n return 'Unable to proceed because the required data is unavailable.';\n }\n}\n","import StandardError from './standard-error';\n\n/**\n * Throw this error if we try to call a method that is only a stub and has not\n * been fully implemented.\n */\nexport default class NotImplementedError extends StandardError {\n constructor(message?: string) {\n super(message || 'Not implemented.');\n\n this.name = 'NotImplementedError';\n this.type = 'not_implemented';\n }\n}\n","import StandardError from './standard-error';\n\n/**\n * This error should be thrown when a method is unable to proceed because the\n * caller has not provided all the arguments according to their requirements,\n * i.e.: if an argument is missing or it is not the expected data type.\n */\nexport default class InvalidArgumentError extends StandardError {\n constructor(message?: string) {\n super(message || 'Invalid arguments have been provided.');\n\n this.name = 'InvalidArgumentError';\n this.type = 'invalid_argument';\n }\n}\n","import StandardError from './standard-error';\n\n/**\n * This error should be thrown when the payment flow is cancelled. It could be\n * due to a deliberate user interaction, i.e.: the user clicks on a cancel\n * button which dismisses the payment modal.\n */\nexport default class PaymentMethodCancelledError extends StandardError {\n constructor(message?: string) {\n super(message || 'Payment process was cancelled.');\n\n this.name = 'PaymentMethodCancelledError';\n this.type = 'payment_cancelled';\n }\n}\n","interface ApplePayWindow extends Window {\n ApplePaySession: ApplePaySession;\n}\n\nfunction isApplePayWindow(window: Window): window is ApplePayWindow {\n return 'ApplePaySession' in window;\n}\n\nexport function assertApplePayWindow(window: Window): asserts window is ApplePayWindow {\n if (!isApplePayWindow(window)) {\n throw new Error('Apple pay is not supported');\n }\n}\n\nexport default class ApplePaySessionFactory {\n create(request: ApplePayJS.ApplePayPaymentRequest): ApplePaySession {\n assertApplePayWindow(window);\n\n return new ApplePaySession(1, request);\n }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\nimport { noop } from 'lodash';\n\nimport {\n AddressRequestBody,\n Cart,\n Checkout,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotImplementedError,\n Payment,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n ShippingOption,\n StoreConfig,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithApplePayCustomerInitializeOptions } from './apple-pay-customer-initialize-options';\nimport ApplePaySessionFactory, { assertApplePayWindow } from './apple-pay-session-factory';\n\nconst validationEndpoint = (bigPayEndpoint: string) =>\n `${bigPayEndpoint}/api/public/v1/payments/applepay/validate_merchant`;\n\nenum DefaultLabels {\n Subtotal = 'Subtotal',\n Shipping = 'Shipping',\n}\n\nfunction isShippingOptions(options: ShippingOption[] | undefined): options is ShippingOption[] {\n return options instanceof Array;\n}\n\nexport default class ApplePayCustomerStrategy implements CustomerStrategy {\n private _paymentMethod?: PaymentMethod;\n private _applePayButton?: HTMLElement;\n private _onAuthorizeCallback = noop;\n private _onError = noop;\n private _subTotalLabel: string = DefaultLabels.Subtotal;\n private _shippingLabel: string = DefaultLabels.Shipping;\n\n constructor(\n private _requestSender: RequestSender,\n private _paymentIntegrationService: PaymentIntegrationService,\n private _sessionFactory: ApplePaySessionFactory,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithApplePayCustomerInitializeOptions,\n ): Promise {\n const { methodId, applepay } = options;\n\n assertApplePayWindow(window);\n\n if (!methodId || !applepay) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n container,\n shippingLabel,\n subtotalLabel,\n onError = noop,\n onPaymentAuthorize,\n } = applepay;\n\n this._shippingLabel = shippingLabel || DefaultLabels.Shipping;\n this._subTotalLabel = subtotalLabel || DefaultLabels.Subtotal;\n this._onAuthorizeCallback = onPaymentAuthorize;\n this._onError = onError;\n\n await this._paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this._paymentIntegrationService.getState();\n\n this._paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n await this._paymentIntegrationService.verifyCheckoutSpamProtection();\n\n this._applePayButton = this._createButton(container);\n this._applePayButton.addEventListener('click', this._handleWalletButtonClick.bind(this));\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via Apple, the shopper must click on \"Apple Pay\" button.',\n );\n }\n\n signOut(): Promise {\n throw new NotImplementedError('Need to do signout via apple.');\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n private _createButton(containerId: string): HTMLElement {\n const container = document.getElementById(containerId);\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to create sign-in button without valid container ID.',\n );\n }\n\n const button = document.createElement('button');\n\n button.setAttribute('type', 'button');\n button.setAttribute('aria-label', 'Apple Pay');\n container.appendChild(button);\n\n return button;\n }\n\n private _handleWalletButtonClick(event: Event) {\n event.preventDefault();\n\n const state = this._paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const config = state.getStoreConfigOrThrow();\n const checkout = state.getCheckoutOrThrow();\n\n if (!this._paymentMethod || !this._paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const request = this._getBaseRequest(cart, checkout, config, this._paymentMethod);\n const applePaySession = this._sessionFactory.create(request);\n\n this._handleApplePayEvents(applePaySession, this._paymentMethod, config);\n\n applePaySession.begin();\n }\n\n private _getBaseRequest(\n cart: Cart,\n checkout: Checkout,\n config: StoreConfig,\n paymentMethod: PaymentMethod,\n ): ApplePayJS.ApplePayPaymentRequest {\n const {\n storeProfile: { storeCountryCode, storeName },\n } = config;\n const {\n currency: { code, decimalPlaces },\n } = cart;\n\n const {\n initializationData: { merchantCapabilities, supportedNetworks },\n } = paymentMethod;\n\n const requiresShipping = cart.lineItems.physicalItems.length > 0;\n const total: ApplePayJS.ApplePayLineItem = requiresShipping\n ? {\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n type: 'pending',\n }\n : {\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n type: 'final',\n };\n\n const request: ApplePayJS.ApplePayPaymentRequest = {\n requiredBillingContactFields: ['postalAddress'],\n requiredShippingContactFields: ['email', 'phone'],\n countryCode: storeCountryCode,\n currencyCode: code,\n merchantCapabilities,\n supportedNetworks,\n lineItems: [],\n total,\n };\n\n if (requiresShipping) {\n request.requiredShippingContactFields?.push('postalAddress');\n } else {\n const lineItems: ApplePayJS.ApplePayLineItem[] = [\n {\n label: this._subTotalLabel,\n amount: `${checkout.subtotal.toFixed(decimalPlaces)}`,\n },\n ];\n\n checkout.taxes.forEach((tax) =>\n lineItems.push({\n label: tax.name,\n amount: `${tax.amount.toFixed(decimalPlaces)}`,\n }),\n );\n\n request.lineItems = lineItems;\n }\n\n return request;\n }\n\n private _handleApplePayEvents(\n applePaySession: ApplePaySession,\n paymentMethod: PaymentMethod,\n config: StoreConfig,\n ) {\n applePaySession.onvalidatemerchant = async (event) => {\n try {\n const { body: merchantSession } = await this._onValidateMerchant(\n paymentMethod,\n event,\n );\n\n applePaySession.completeMerchantValidation(merchantSession);\n } catch (err) {\n this._onError(err);\n }\n };\n\n applePaySession.onshippingcontactselected = async (event) =>\n this._handleShippingContactSelected(applePaySession, config, event);\n\n applePaySession.onshippingmethodselected = async (event) =>\n this._handleShippingMethodSelected(applePaySession, config, event);\n\n applePaySession.oncancel = async () => {\n try {\n const url = `/remote-checkout/${paymentMethod.id}/signout`;\n\n await this._requestSender.get(url);\n\n return await this._paymentIntegrationService.loadCheckout();\n } catch (error) {\n return this._onError(new PaymentMethodCancelledError());\n }\n };\n\n applePaySession.onpaymentauthorized = async (event) =>\n this._onPaymentAuthorized(event, applePaySession, paymentMethod);\n }\n\n private async _handleShippingContactSelected(\n applePaySession: ApplePaySession,\n config: StoreConfig,\n event: ApplePayJS.ApplePayShippingContactSelectedEvent,\n ) {\n const shippingAddress = this._transformContactToAddress(event.shippingContact);\n\n try {\n await this._paymentIntegrationService.updateShippingAddress(shippingAddress);\n } catch (error) {\n applePaySession.abort();\n\n return this._onError(error);\n }\n\n const {\n storeProfile: { storeName },\n } = config;\n let state = this._paymentIntegrationService.getState();\n const {\n currency: { decimalPlaces },\n } = state.getCartOrThrow();\n let checkout = state.getCheckoutOrThrow();\n const selectionShippingOptionId = checkout.consignments[0].selectedShippingOption?.id;\n const availableOptions = checkout.consignments[0].availableShippingOptions;\n const selectedOption = availableOptions?.find(({ id }) => id === selectionShippingOptionId);\n const unselectedOptions = availableOptions?.filter(\n (option) => option.id !== selectionShippingOptionId,\n );\n const shippingOptions: ApplePayJS.ApplePayShippingMethod[] = selectedOption\n ? [\n {\n label: selectedOption.description,\n amount: `${selectedOption.cost.toFixed(decimalPlaces)}`,\n detail: selectedOption.additionalDescription,\n identifier: selectedOption.id,\n },\n ]\n : [];\n\n if (unselectedOptions) {\n [\n ...unselectedOptions.filter((option) => option.isRecommended),\n ...unselectedOptions.filter((option) => !option.isRecommended),\n ].forEach((option) =>\n shippingOptions.push({\n label: option.description,\n amount: `${option.cost.toFixed(decimalPlaces)}`,\n detail: option.additionalDescription,\n identifier: option.id,\n }),\n );\n }\n\n if (!isShippingOptions(availableOptions)) {\n throw new Error('Shipping options not available.');\n }\n\n if (availableOptions.length === 0) {\n applePaySession.completeShippingContactSelection(\n ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,\n [],\n {\n type: 'pending',\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n },\n [],\n );\n\n return;\n }\n\n const recommendedOption = availableOptions.find((option) => option.isRecommended);\n\n const optionId = recommendedOption ? recommendedOption.id : availableOptions[0].id;\n const selectedOptionId = selectedOption ? selectedOption.id : optionId;\n\n try {\n await this._updateShippingOption(selectedOptionId);\n } catch (error) {\n return this._onError(error);\n }\n\n state = this._paymentIntegrationService.getState();\n checkout = state.getCheckoutOrThrow();\n\n applePaySession.completeShippingContactSelection({\n newShippingMethods: shippingOptions,\n newTotal: {\n type: 'final',\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n },\n newLineItems: this._getUpdatedLineItems(checkout, decimalPlaces),\n });\n }\n\n private async _handleShippingMethodSelected(\n applePaySession: ApplePaySession,\n config: StoreConfig,\n event: ApplePayJS.ApplePayShippingMethodSelectedEvent,\n ) {\n const {\n storeProfile: { storeName },\n } = config;\n const {\n shippingMethod: { identifier: optionId },\n } = event;\n\n try {\n await this._updateShippingOption(optionId);\n } catch (error) {\n applePaySession.abort();\n\n return this._onError(error);\n }\n\n const state = this._paymentIntegrationService.getState();\n const {\n currency: { decimalPlaces },\n } = state.getCartOrThrow();\n const checkout = state.getCheckoutOrThrow();\n\n applePaySession.completeShippingMethodSelection({\n newTotal: {\n type: 'final',\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n },\n newLineItems: this._getUpdatedLineItems(checkout, decimalPlaces),\n });\n }\n\n private _getUpdatedLineItems(\n checkout: Checkout,\n decimalPlaces: number,\n ): ApplePayJS.ApplePayLineItem[] {\n const lineItems: ApplePayJS.ApplePayLineItem[] = [\n {\n label: this._subTotalLabel,\n amount: `${checkout.subtotal.toFixed(decimalPlaces)}`,\n },\n ];\n\n checkout.taxes.forEach((tax) =>\n lineItems.push({\n label: tax.name,\n amount: `${tax.amount.toFixed(decimalPlaces)}`,\n }),\n );\n lineItems.push({\n label: this._shippingLabel,\n amount: `${checkout.shippingCostTotal.toFixed(decimalPlaces)}`,\n });\n\n return lineItems;\n }\n\n private async _updateShippingOption(optionId: string) {\n return this._paymentIntegrationService.selectShippingOption(optionId);\n }\n\n private async _onValidateMerchant(\n paymentData: PaymentMethod,\n event: ApplePayJS.ApplePayValidateMerchantEvent,\n ) {\n const body = [\n `validationUrl=${event.validationURL}`,\n `merchantIdentifier=${paymentData.initializationData.merchantId}`,\n `displayName=${paymentData.initializationData.storeName}`,\n `domainName=${window.location.hostname}`,\n ].join('&');\n\n return this._requestSender.post(\n validationEndpoint(paymentData.initializationData.paymentsUrl),\n {\n credentials: false,\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'X-XSRF-TOKEN': null,\n },\n body,\n },\n );\n }\n\n private async _onPaymentAuthorized(\n event: ApplePayJS.ApplePayPaymentAuthorizedEvent,\n applePaySession: ApplePaySession,\n paymentMethod: PaymentMethod,\n ) {\n const { token, billingContact, shippingContact } = event.payment;\n const state = this._paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const requiresShipping = cart.lineItems.physicalItems.length > 0;\n const payment: Payment = {\n methodId: paymentMethod.id,\n paymentData: {\n formattedPayload: {\n apple_pay_token: {\n payment_data: token.paymentData,\n payment_method: token.paymentMethod,\n transaction_id: token.transactionIdentifier,\n },\n },\n },\n };\n\n const transformedBillingAddress = this._transformContactToAddress(billingContact);\n const transformedShippingAddress = this._transformContactToAddress(shippingContact);\n const emailAddress = shippingContact?.emailAddress;\n const phone = shippingContact?.phoneNumber || '';\n\n try {\n await this._paymentIntegrationService.updateBillingAddress({\n ...transformedBillingAddress,\n email: emailAddress,\n phone,\n });\n\n if (requiresShipping) {\n await this._paymentIntegrationService.updateShippingAddress(\n transformedShippingAddress,\n );\n }\n\n await this._paymentIntegrationService.submitOrder({\n useStoreCredit: false,\n });\n\n await this._paymentIntegrationService.submitPayment(payment);\n applePaySession.completePayment(ApplePaySession.STATUS_SUCCESS);\n\n return this._onAuthorizeCallback();\n } catch (error) {\n applePaySession.completePayment(ApplePaySession.STATUS_FAILURE);\n\n return this._onError(error);\n }\n }\n\n private _transformContactToAddress(\n contact?: ApplePayJS.ApplePayPaymentContact,\n ): AddressRequestBody {\n return {\n firstName: contact?.givenName || '',\n lastName: contact?.familyName || '',\n city: contact?.locality || '',\n company: '',\n address1: (contact?.addressLines && contact.addressLines[0]) || '',\n address2: (contact?.addressLines && contact.addressLines[1]) || '',\n postalCode: contact?.postalCode || '',\n countryCode: contact?.countryCode || '',\n phone: contact?.phoneNumber || '',\n stateOrProvince: contact?.administrativeArea || '',\n stateOrProvinceCode: contact?.administrativeArea || '',\n customFields: [],\n };\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ApplePayCustomerStrategy from './apple-pay-customer-strategy';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst createApplePayCustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new ApplePayCustomerStrategy(\n createRequestSender({ host: getHost() }),\n paymentIntegrationService,\n new ApplePaySessionFactory(),\n );\n};\n\nexport default toResolvableModule(createApplePayCustomerStrategy, [{ id: 'applepay' }]);\n","import StandardError from './standard-error';\n\n/**\n * This error should be thrown when a payment method experiences some kind of\n * failure (i.e.: its client library returns a rejected promise). And there is\n * no other error type that is more specific than this one.\n */\nexport default class PaymentMethodFailedError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Unable to proceed because the client library of a payment method has thrown an unexpected error.',\n );\n\n this.name = 'PaymentMethodFailedError';\n this.type = 'payment_method_client_invalid';\n }\n}\n","import StandardError from './standard-error';\n\nexport enum NotInitializedErrorType {\n CheckoutButtonNotInitialized,\n CustomerNotInitialized,\n PaymentNotInitialized,\n ShippingNotInitialized,\n SpamProtectionNotInitialized,\n}\n\n/**\n * Throw this error if a method requires a certain initialization call to be\n * made first. Some objects can be constructed but they cannot be used until a\n * separate initialization call is made.\n */\nexport default class NotInitializedError extends StandardError {\n constructor(public subtype: NotInitializedErrorType) {\n super(getErrorMessage(subtype));\n\n this.name = 'NotInitializedError';\n this.type = 'not_initialized';\n }\n}\n\nfunction getErrorMessage(type: NotInitializedErrorType): string {\n switch (type) {\n case NotInitializedErrorType.CustomerNotInitialized:\n return 'Unable to proceed because the customer step of checkout has not been initialized.';\n\n case NotInitializedErrorType.PaymentNotInitialized:\n return 'Unable to proceed because the payment step of checkout has not been initialized.';\n\n case NotInitializedErrorType.ShippingNotInitialized:\n return 'Unable to proceed because the shipping step of checkout has not been initialized.';\n\n case NotInitializedErrorType.SpamProtectionNotInitialized:\n return 'Unable to proceed because the checkout spam protection has not been initialized.';\n\n default:\n return 'Unable to proceed because the required component has not been initialized.';\n }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport StandardError from './standard-error';\n\nconst DEFAULT_RESPONSE = {\n body: {},\n headers: {},\n status: 0,\n};\n\n/**\n * Throw this error if we are unable to make a request to the server. It wraps\n * any server response into a JS error object.\n */\nexport default class RequestError extends StandardError {\n body: TBody | {};\n headers: { [key: string]: any };\n errors: Array<{ code: string; message?: string }>;\n status: number;\n\n constructor(\n response?: Response,\n {\n message,\n errors,\n }: {\n message?: string;\n errors?: Array<{ code: string; message?: string }>;\n } = {},\n ) {\n const { body, headers, status } = response || DEFAULT_RESPONSE;\n\n super(message || 'An unexpected error has occurred.');\n\n this.name = 'RequestError';\n this.type = 'request';\n this.body = body;\n this.headers = headers;\n this.status = status;\n this.errors = errors || [];\n }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport RequestError from './request-error';\n\n/**\n * Throw this error if we are unable to successfully submit a server request\n * using a payment method because the method has invalid configuration or is in\n * an invalid state.\n */\nexport default class PaymentMethodInvalidError extends RequestError {\n constructor(response?: Response) {\n super(response, {\n message: 'There is a problem processing your payment. Please try again later.',\n });\n\n this.name = 'PaymentMethodInvalidError';\n this.type = 'payment_method_invalid';\n }\n}\n","import { noop } from 'rxjs';\n\nimport {\n CheckoutPaymentMethodExecutedOptions,\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n isCustomError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodFailedError,\n PaymentMethodInvalidError,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BoltCheckout, BoltHostWindow, BoltInitializationData } from './bolt';\nimport { WithBoltCustomerInitializeOptions } from './bolt-customer-initialize-options';\nimport BoltScriptLoader from './bolt-script-loader';\n\nexport default class BoltCustomerStrategy implements CustomerStrategy {\n private boltHostWindow: BoltHostWindow = window;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private boltScriptLoader: BoltScriptLoader,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithBoltCustomerInitializeOptions,\n ): Promise {\n const { methodId, bolt } = options;\n const { onInit } = bolt || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const paymentMethod: PaymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId);\n\n if (!paymentMethod.initializationData?.publishableKey) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { developerConfig, publishableKey } = paymentMethod.initializationData;\n\n await this.boltScriptLoader.loadBoltClient(\n publishableKey,\n paymentMethod.config.testMode,\n developerConfig,\n );\n\n if (onInit && typeof onInit === 'function') {\n const email = this.getCustomerEmail();\n const hasBoltAccount = await this.hasBoltAccount(email);\n\n onInit(hasBoltAccount, email);\n }\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n\n return Promise.resolve();\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n\n return Promise.resolve();\n }\n\n async executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n const {\n continueWithCheckoutCallback = noop,\n checkoutPaymentMethodExecuted,\n methodId,\n } = options || {};\n const email = this.getCustomerEmail();\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n if (typeof continueWithCheckoutCallback !== 'function') {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"continueWithCheckoutCallback\" argument is not provided and it must be a function.',\n );\n }\n\n if (!email) {\n continueWithCheckoutCallback();\n\n return;\n }\n\n return this.openBoltCheckoutModalOrThrow(\n email,\n methodId,\n continueWithCheckoutCallback,\n checkoutPaymentMethodExecuted,\n );\n }\n\n private async openBoltCheckoutModalOrThrow(\n email: string,\n methodId: string,\n continueWithCheckoutCallback: () => void,\n checkoutPaymentMethodExecuted?: (payload: CheckoutPaymentMethodExecutedOptions) => void,\n ): Promise {\n const boltClient = this.getBoltClientOrThrow();\n const paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethod(methodId);\n\n try {\n if (paymentMethod?.initializationData?.embeddedOneClickEnabled) {\n const hasBoltAccount = await this.hasBoltAccount(email);\n\n if (hasBoltAccount) {\n const callbacks = {\n close: () => {\n continueWithCheckoutCallback();\n },\n };\n\n await boltClient.openCheckout(email, callbacks);\n } else {\n continueWithCheckoutCallback();\n }\n\n if (typeof checkoutPaymentMethodExecuted === 'function') {\n checkoutPaymentMethodExecuted({ hasBoltAccount });\n }\n } else {\n continueWithCheckoutCallback();\n }\n } catch (error) {\n if (\n isCustomError(error) &&\n error.name !== 'MissingDataError' &&\n error.name !== 'NotInitializedError'\n ) {\n throw new PaymentMethodFailedError(error.message);\n }\n\n throw error;\n }\n }\n\n private getBoltClientOrThrow(): BoltCheckout {\n const boltClient = this.boltHostWindow.BoltCheckout;\n\n if (!boltClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return boltClient;\n }\n\n private async hasBoltAccount(email: string) {\n const boltClient = this.getBoltClientOrThrow();\n\n try {\n return await boltClient.hasBoltAccount(email);\n } catch {\n throw new PaymentMethodInvalidError();\n }\n }\n\n private getCustomerEmail() {\n const state = this.paymentIntegrationService.getState();\n const customer = state.getCustomer();\n const billingAddress = state.getBillingAddress();\n\n return customer?.email || billingAddress?.email || '';\n }\n}\n","export default interface CustomError extends Error {\n message: string;\n type: string;\n subtype?: string;\n}\n\nexport function isCustomError(error: any): error is CustomError {\n return (\n typeof error.message === 'string' &&\n typeof error.type === 'string' &&\n (typeof error.subtype === 'string' || !error.subtype) &&\n error instanceof Error\n );\n}\n","import StandardError from './standard-error';\n\n/**\n * This error should be thrown when the client library of a payment method fails\n * to load, or for some reason, it is inaccessible.\n */\nexport default class PaymentMethodClientUnavailableError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Unable to proceed because the client library of a payment method is not loaded or ready to be used.',\n );\n\n this.name = 'PaymentMethodClientUnavailableError';\n this.type = 'payment_method_client_unavailable';\n }\n}\n","import {\n BuyNowCartRequestBody,\n NonceInstrument,\n PaymentMethod,\n WithAccountCreation,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport interface BoltHostWindow extends Window {\n BoltCheckout?: BoltCheckout;\n BoltConnect?: BoltConnect;\n Bolt?(publicKey: string): BoltEmbedded;\n}\n\nexport interface BoltCheckout {\n configure(cart: BoltCart, hints: Record, callbacks?: BoltCallbacks): BoltClient;\n hasBoltAccount(email: string): Promise;\n getTransactionReference(): Promise;\n openCheckout(email: string, callbacks?: BoltOpenCheckoutCallbacks): Promise;\n setClientCustomCallbacks(callbacks: BoltCallbacks): void;\n setOrderId(orderId: number): Promise;\n}\n\nexport interface BoltConnect {\n setupProductPageCheckout?(): void;\n}\n\nexport interface BoltOpenCheckoutCallbacks {\n close?(): void;\n}\n\nexport interface BoltEmbeddedOptions {\n styles: { backgroundColor: string };\n renderSeparateFields?: boolean;\n}\n\nexport interface BoltEmbedded {\n create(name: string, options?: BoltEmbeddedOptions): BoltEmbededField;\n}\n\nexport interface BoltEmbededField {\n mount(element: string): void;\n unmount(): void;\n tokenize(): Promise;\n}\n\nexport interface BoltDeveloperModeParams {\n developerMode: BoltDeveloperMode;\n developerDomain: string;\n}\n\nexport enum BoltDeveloperMode {\n SandboxMode = 'bolt_sandbox',\n StagingMode = 'bolt_staging',\n DevelopmentMode = 'bolt_development',\n}\n\nexport interface BoltClient {\n open(): void;\n}\n\nexport interface BoltCart {\n orderToken: string;\n}\n\nexport interface BoltCallbacks {\n check?(): boolean;\n onCheckoutStart?(): void;\n onPaymentSubmit?(): void;\n success(transaction: BoltTransaction, callback: () => void): void;\n close?(): void;\n}\n\nexport interface BoltTransaction {\n id: string;\n type: string;\n processor: string;\n date: number;\n reference: string;\n status: string;\n authorization: BoltAuthorization;\n}\n\nexport interface BoltAuthorization {\n status: string;\n reason: string;\n}\n\nexport interface BoltEmbeddedTokenize {\n bin: string;\n expiration: string;\n last4: string;\n postal_code?: string;\n token: string;\n token_type: string;\n}\n\nexport interface BoltPaymentMethod extends PaymentMethod {\n initializationData?: BoltInitializationData;\n}\n\nexport interface BoltInitializationData {\n publishableKey: string;\n developerConfig: BoltDeveloperModeParams;\n embeddedOneClickEnabled: boolean;\n}\n\nexport type BoltPaymentData = WithAccountCreation & NonceInstrument;\n\nexport interface BoltBuyNowInitializeOptions {\n storefrontApiToken?: string;\n getBuyNowCartRequestBody(): BuyNowCartRequestBody;\n}\n\nexport enum StyleButtonSize {\n Small = 'small',\n Medium = 'medium',\n Large = 'large',\n}\n\nexport enum StyleButtonShape {\n Pill = 'pill',\n Rect = 'rect',\n}\n\nexport interface BoltButtonStyleOptions {\n shape?: StyleButtonShape;\n size?: StyleButtonSize;\n}\n","import { LoadScriptOptions, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n InvalidArgumentError,\n PaymentMethodClientUnavailableError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n BoltCheckout,\n BoltDeveloperMode,\n BoltDeveloperModeParams,\n BoltEmbedded,\n BoltHostWindow,\n} from './bolt';\n\nexport default class BoltScriptLoader {\n constructor(\n private scriptLoader: ScriptLoader,\n public boltHostWindow: BoltHostWindow = window,\n ) {}\n\n async loadBoltClient(\n publishableKey?: string,\n testMode?: boolean,\n developerModeParams?: BoltDeveloperModeParams,\n cartId?: string,\n storefrontApiToken?: string,\n ): Promise {\n if (this.boltHostWindow.BoltCheckout) {\n return this.boltHostWindow.BoltCheckout;\n }\n\n if (!publishableKey) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"publishableKey\" argument is not provided.',\n );\n }\n\n await this.scriptLoader.loadScript(\n `//${this.getDomainURL(!!testMode, developerModeParams)}/connect-bigcommerce.js`,\n this.getScriptOptions('bolt-connect', publishableKey, cartId, storefrontApiToken),\n );\n await this.scriptLoader.loadScript(\n `//${this.getDomainURL(!!testMode, developerModeParams)}/track.js`,\n this.getScriptOptions('bolt-track', publishableKey),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!this.boltHostWindow.BoltCheckout) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.boltHostWindow.BoltCheckout;\n }\n\n async loadBoltEmbedded(\n publishableKey: string,\n testMode?: boolean,\n developerModeParams?: BoltDeveloperModeParams,\n ): Promise {\n const options: LoadScriptOptions = {\n async: true,\n attributes: {\n id: 'bolt-embedded',\n },\n };\n\n await this.scriptLoader.loadScript(\n `//${this.getDomainURL(!!testMode, developerModeParams)}/embed.js`,\n options,\n );\n\n if (!this.boltHostWindow.Bolt) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.boltHostWindow.Bolt(publishableKey);\n }\n\n getDomainURL(testMode: boolean, developerModeParams?: BoltDeveloperModeParams): string {\n if (!testMode) {\n return 'connect.bolt.com';\n }\n\n if (developerModeParams) {\n switch (developerModeParams.developerMode) {\n case BoltDeveloperMode.StagingMode:\n return 'connect-staging.bolt.com';\n\n case BoltDeveloperMode.DevelopmentMode:\n return `connect.${developerModeParams.developerDomain}`;\n }\n }\n\n return 'connect-sandbox.bolt.com';\n }\n\n private getScriptOptions(\n id: string,\n publishableKey: string,\n cartId?: string,\n storefrontApiToken?: string,\n ): LoadScriptOptions {\n return {\n async: true,\n attributes: {\n id,\n 'data-publishable-key': publishableKey,\n ...(cartId && { 'data-shopping-cart-id': cartId }),\n ...(storefrontApiToken && { 'data-storefront-api-token': storefrontApiToken }),\n },\n };\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BoltCustomerStrategy from './bolt-customer-strategy';\nimport BoltScriptLoader from './bolt-script-loader';\n\nconst createBoltCustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new BoltCustomerStrategy(\n paymentIntegrationService,\n new BoltScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createBoltCustomerStrategy, [{ id: 'bolt' }]);\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@bigcommerce/form-poster\");","import { PaypalAuthorizeData, PaypalButtonOptions, PaypalButtonRender, PaypalSDK } from './paypal';\nimport {\n BraintreeLocalMethods,\n LocalPaymentInstance,\n} from './braintree-local-payment-methods/braintree-local-methods-options';\n\n/**\n *\n * Constants\n *\n */\nexport enum BraintreeEnv {\n Sandbox = 'sandbox',\n Production = 'production',\n}\n\n/**\n *\n * Common\n *\n */\nexport interface BraintreeModuleCreator<\n TInstance,\n TOptions = BraintreeModuleCreatorConfig,\n TError = BraintreeError,\n> {\n create(\n config: TOptions,\n callback?: (error: TError, instance: TInstance) => void,\n ): Promise;\n}\n\nexport interface BraintreeModuleCreatorConfig {\n client?: BraintreeClient;\n authorization?: string;\n}\n\nexport interface BraintreeModule {\n teardown(): Promise;\n}\n\nexport interface BraintreeSDK {\n client?: BraintreeClientCreator;\n dataCollector?: BraintreeDataCollectorCreator;\n // googlePayment?: GooglePayCreator; // TODO: should be added in future migration\n hostedFields?: BraintreeHostedFieldsCreator;\n paypal?: BraintreePaypalCreator;\n paypalCheckout?: BraintreePaypalCheckoutCreator;\n threeDSecure?: BraintreeThreeDSecureCreator;\n venmo?: BraintreeVenmoCheckoutCreator;\n // visaCheckout?: BraintreeVisaCheckoutCreator; // TODO: should be added in future migration\n usBankAccount?: BraintreeBankAccountCreator;\n localPayment?: BraintreeLocalPayment;\n}\n\nexport interface BraintreeLocalPayment {\n VERSION: string;\n create(\n config: BraintreeLocalPaymentCreateConfig,\n callback: BraintreeLocalPaymentCallback,\n ): BraintreeLocalMethods;\n}\n\nexport type BraintreeLocalPaymentCallback = (\n localPaymentError: string,\n localPaymentInstance: LocalPaymentInstance,\n) => void;\n\nexport interface BraintreeLocalPaymentCreateConfig {\n client: BraintreeClient;\n merchantAccountId: string;\n}\n\nexport interface BraintreeInitializationData {\n intent?: 'authorize' | 'order' | 'sale';\n isCreditEnabled?: boolean;\n}\n\nexport interface BraintreePaypalRequest {\n amount: string | number;\n billingAgreementDescription?: string;\n currency?: string;\n displayName?: string;\n enableShippingAddress: true;\n flow: 'checkout' | 'vault';\n intent?: 'authorize' | 'order' | 'sale';\n landingPageType?: 'login' | 'billing';\n locale?: string;\n offerCredit?: boolean;\n shippingAddressEditable?: boolean;\n shippingAddressOverride?: BraintreeShippingAddressOverride;\n useraction?: 'commit';\n}\n\nexport interface BraintreeShippingAddressOverride {\n line1: string;\n line2?: string;\n city: string;\n state: string;\n postalCode: string;\n countryCode: string;\n phone?: string;\n recipientName?: string;\n}\n\nexport interface BraintreeTokenizePayload {\n nonce: string;\n type: 'PaypalAccount' | 'VenmoAccount';\n details: BraintreeDetails;\n creditFinancingOffered?: {\n totalCost: {\n value: string;\n currency: string;\n };\n term: number;\n monthlyPayment: {\n value: string;\n currency: string;\n };\n totalInsterest: {\n value: string;\n currency: string;\n };\n payerAcceptance: boolean;\n cartAmountImmutable: boolean;\n };\n}\n\nexport interface BraintreeDetails {\n username?: string;\n email?: string;\n payerId?: string;\n firstName?: string;\n lastName?: string;\n countryCode?: string;\n phone?: string;\n shippingAddress?: BraintreeShippingAddress;\n billingAddress?: BraintreeAddress;\n}\n\nexport interface BraintreeAddress {\n line1: string;\n line2: string;\n city: string;\n state: string;\n postalCode: string;\n countryCode: string;\n}\n\nexport interface BraintreeShippingAddress extends BraintreeAddress {\n recipientName: string;\n}\n\nexport interface BraintreeVerifyPayload {\n nonce: string;\n details: {\n cardType: string;\n lastFour: string;\n lastTwo: string;\n };\n description: string;\n liabilityShiftPossible: boolean;\n liabilityShifted: boolean;\n}\n\nexport interface BraintreeError extends Error {\n type: 'CUSTOMER' | 'MERCHANT' | 'NETWORK' | 'INTERNAL' | 'UNKNOWN';\n code: string;\n details?: unknown;\n}\n\n/**\n *\n * Braintree Client\n *\n */\nexport type BraintreeClientCreator = BraintreeModuleCreator;\n\nexport interface BraintreeClient {\n request(payload: BraintreeRequestData): Promise;\n getVersion(): string | void;\n}\n\nexport interface BraintreeRequestData {\n data: {\n creditCard: {\n billingAddress?: {\n countryCodeAlpha2: string;\n locality: string;\n countryName: string;\n postalCode: string;\n streetAddress: string;\n };\n cardholderName: string;\n cvv?: string;\n expirationDate: string;\n number: string;\n options: {\n validate: boolean;\n };\n };\n };\n endpoint: string;\n method: string;\n}\n\nexport interface BraintreeTokenizeResponse {\n creditCards: Array<{ nonce: string }>;\n}\n\n/**\n *\n * Braintree Data Collector\n *\n */\nexport type BraintreeDataCollectorCreator = BraintreeModuleCreator<\n BraintreeDataCollector,\n BraintreeDataCollectorCreatorConfig\n>;\n\nexport interface BraintreeDataCollectorCreatorConfig extends BraintreeModuleCreatorConfig {\n kount?: boolean;\n paypal?: boolean;\n}\n\nexport interface BraintreeDataCollector extends BraintreeModule {\n deviceData?: string;\n}\n\n/**\n *\n * Braintree Google Pay\n *\n */\nexport interface BraintreeGooglePayThreeDSecure {\n verifyCard(options: BraintreeGooglePayThreeDSecureOptions): Promise;\n}\n\nexport interface BraintreeGooglePayThreeDSecureOptions {\n nonce: string;\n amount: number;\n showLoader?: boolean;\n onLookupComplete(data: BraintreeThreeDSecureVerificationData, next: () => void): void;\n}\n\n/**\n *\n * Braintree Hosted Fields\n *\n */\nexport type BraintreeHostedFieldsCreator = BraintreeModuleCreator<\n BraintreeHostedFields,\n BraintreeHostedFieldsCreatorConfig\n>;\n\nexport interface BraintreeHostedFields {\n teardown(): Promise;\n tokenize(\n options?: BraintreeHostedFieldsTokenizeOptions,\n ): Promise;\n on(eventName: string, callback: (event: BraintreeHostedFieldsState) => void): void;\n}\n\nexport interface BraintreeHostedFieldsCreatorConfig extends BraintreeModuleCreatorConfig {\n fields: {\n number?: BraintreeHostedFieldOption;\n expirationDate?: BraintreeHostedFieldOption;\n expirationMonth?: BraintreeHostedFieldOption;\n expirationYear?: BraintreeHostedFieldOption;\n cvv?: BraintreeHostedFieldOption;\n postalCode?: BraintreeHostedFieldOption;\n };\n styles?: {\n input?: { [key: string]: string };\n '.invalid'?: { [key: string]: string };\n '.valid'?: { [key: string]: string };\n ':focus'?: { [key: string]: string };\n };\n}\n\nexport interface BraintreeHostedFieldOption {\n container: string | HTMLElement;\n placeholder?: string;\n type?: string;\n formatInput?: boolean;\n maskInput?: boolean | { character?: string; showLastFour?: string };\n select?: boolean | { options?: string[] };\n maxCardLength?: number;\n maxlength?: number;\n minlength?: number;\n prefill?: string;\n rejectUnsupportedCards?: boolean;\n supportedCardBrands?: { [key: string]: boolean };\n}\n\nexport interface BraintreeHostedFieldsState {\n cards: BraintreeHostedFieldsCard[];\n emittedBy: string;\n fields: {\n number?: BraintreeHostedFieldsFieldData;\n expirationDate?: BraintreeHostedFieldsFieldData;\n expirationMonth?: BraintreeHostedFieldsFieldData;\n expirationYear?: BraintreeHostedFieldsFieldData;\n cvv?: BraintreeHostedFieldsFieldData;\n postalCode?: BraintreeHostedFieldsFieldData;\n };\n}\n\nexport interface BraintreeHostedFieldsCard {\n type: string;\n niceType: string;\n code: { name: string; size: number };\n}\n\nexport interface BraintreeHostedFieldsFieldData {\n container: HTMLElement;\n isFocused: boolean;\n isEmpty: boolean;\n isPotentiallyValid: boolean;\n isValid: boolean;\n}\n\nexport interface BraintreeHostedFieldsTokenizeOptions {\n vault?: boolean;\n fieldsToTokenize?: string[];\n cardholderName?: string;\n billingAddress?: BraintreeBillingAddressRequestData;\n}\n\nexport interface BraintreeHostedFieldsTokenizePayload {\n nonce: string;\n details: {\n bin: string;\n cardType: string;\n expirationMonth: string;\n expirationYear: string;\n lastFour: string;\n lastTwo: string;\n };\n description: string;\n type: string;\n binData: {\n commercial: string;\n countryOfIssuance: string;\n debit: string;\n durbinRegulated: string;\n healthcare: string;\n issuingBank: string;\n payroll: string;\n prepaid: string;\n productId: string;\n };\n}\n\nexport interface BraintreeBillingAddressRequestData {\n postalCode?: string;\n firstName?: string;\n lastName?: string;\n company?: string;\n streetAddress?: string;\n extendedAddress?: string;\n locality?: string;\n region?: string;\n countryCodeNumeric?: string;\n countryCodeAlpha2?: string;\n countryCodeAlpha3?: string;\n countryName?: string;\n}\n\nexport interface BraintreeHostedFormError extends BraintreeError {\n details?: {\n invalidFieldKeys?: string[];\n };\n}\n\n/**\n *\n * Braintree 3D Secure\n *\n */\nexport type BraintreeThreeDSecureCreator = BraintreeModuleCreator<\n BraintreeThreeDSecure,\n BraintreeThreeDSecureCreatorConfig\n>;\n\nexport interface BraintreeThreeDSecure extends BraintreeModule {\n verifyCard(options: BraintreeThreeDSecureOptions): Promise;\n cancelVerifyCard(): Promise;\n}\n\nexport interface BraintreeThreeDSecureCreatorConfig extends BraintreeModuleCreatorConfig {\n version?: number;\n}\n\nexport interface BraintreeThreeDSecureOptions {\n nonce: string;\n amount: number;\n challengeRequested: boolean;\n showLoader?: boolean;\n addFrame(error: Error | undefined, iframe: HTMLIFrameElement): void;\n removeFrame(): void;\n onLookupComplete(data: BraintreeThreeDSecureVerificationData, next: () => void): void;\n}\n\ninterface BraintreeThreeDSecureVerificationData {\n lookup: {\n threeDSecureVersion: string;\n };\n paymentMethod: BraintreeVerifyPayload;\n requiresUserAuthentication: boolean;\n threeDSecureInfo: {\n liabilityShiftPossible: boolean;\n liabilityShifted: boolean;\n };\n}\n\n/**\n *\n * Braintree PayPal\n *\n */\nexport type BraintreePaypalCreator = BraintreeModuleCreator;\n\nexport interface BraintreePaypal {\n closeWindow(): void;\n focusWindow(): void;\n tokenize(options: BraintreePaypalRequest): Promise;\n Buttons?(options: PaypalButtonOptions): PaypalButtonRender;\n}\n\n/**\n *\n * Braintree PayPal Checkout\n *\n */\nexport type BraintreePaypalCheckoutCreator = BraintreeModuleCreator;\n\nexport interface BraintreePaypalCheckout {\n loadPayPalSDK(\n config: BraintreePaypalSdkCreatorConfig,\n callback: (instance: BraintreePaypalCheckout) => void,\n ): void;\n createPayment(options: BraintreePaypalRequest): Promise;\n teardown(): Promise;\n tokenizePayment(options: PaypalAuthorizeData): Promise;\n}\n\nexport interface BraintreePaypalSdkCreatorConfig {\n components?: string;\n currency?: string;\n intent?: string;\n isCreditEnabled?: boolean;\n}\n\n/**\n *\n * Braintree Venmo\n *\n */\nexport type BraintreeVenmoCheckoutCreator = BraintreeModuleCreator<\n BraintreeVenmoCheckout,\n BraintreeVenmoCreatorConfig\n>;\n\nexport interface BraintreeVenmoCheckout extends BraintreeModule {\n tokenize(callback: (error: BraintreeError, payload: BraintreeTokenizePayload) => void): void;\n isBrowserSupported(): boolean;\n}\n\nexport interface BraintreeVenmoCreatorConfig extends BraintreeModuleCreatorConfig {\n allowDesktop: boolean;\n paymentMethodUsage: string;\n}\n\n/**\n *\n * Braintree Visa Checkout\n *\n */\n// TODO: should be added in future migration\n// export type BraintreeVisaCheckoutCreator = BraintreeModuleCreator;\n\n// export interface BraintreeVisaCheckout extends BraintreeModule {\n// tokenize(payment: VisaCheckoutPaymentSuccessPayload): Promise;\n// createInitOptions(options: Partial): VisaCheckoutInitOptions;\n// }\n\n/**\n *\n * Braintree US Bank Account\n *\n */\n\nexport interface BankAccountSuccessPayload {\n accountNumber: string;\n routingNumber: string;\n ownershipType: string;\n accountType: string;\n firstName?: string;\n lastName?: string;\n businessName?: string;\n billingAddress: {\n streetAddress: string;\n extendedAddress: string;\n locality: string;\n region: string;\n postalCode: string;\n };\n}\n\nexport type BraintreeBankAccountCreator = BraintreeModuleCreator;\n\nexport interface BraintreeBankAccount extends BraintreeModule {\n tokenize(payload: {\n bankDetails: BankAccountSuccessPayload;\n mandateText: string;\n }): Promise<{ nonce: string; details: BraintreeDetails }>;\n}\n\n/**\n *\n * Other\n *\n */\nexport interface BraintreeHostWindow extends Window {\n braintree?: BraintreeSDK;\n paypal?: PaypalSDK;\n}\n","import { BraintreeError } from './braintree';\n\nexport default function isBraintreeError(error: unknown): error is BraintreeError {\n return Boolean(\n typeof error === 'object' &&\n error !== null &&\n ('type' in error || 'message' in error || 'code' in error),\n );\n}\n","// the PayPal side of things uses uppercase keys instead of camel case\n\n/**\n *\n * PayPal constants\n *\n */\nexport const PAYPAL_COMPONENTS = ['buttons', 'messages'];\n\nexport enum PaypalButtonStyleLayoutOption {\n HORIZONTAL = 'horizontal',\n VERTICAL = 'vertical',\n}\n\nexport enum PaypalButtonStyleSizeOption {\n SMALL = 'small',\n MEDIUM = 'medium',\n LARGE = 'large',\n RESPONSIVE = 'responsive',\n}\n\nexport enum PaypalButtonStyleColorOption {\n GOLD = 'gold',\n BLUE = 'blue',\n SIlVER = 'silver',\n BLACK = 'black',\n}\n\nexport enum PaypalButtonStyleLabelOption {\n CHECKOUT = 'checkout',\n PAY = 'pay',\n BUYNOW = 'buynow',\n PAYPAL = 'paypal',\n CREDIT = 'credit',\n}\n\nexport enum PaypalButtonStyleShapeOption {\n PILL = 'pill',\n RECT = 'rect',\n}\n\n/**\n *\n * PayPal interfaces\n *\n */\nexport interface PaypalSDK {\n Button: PaypalButton;\n checkout: PaypalExpressCheckout;\n FUNDING: PaypalFundingTypeList;\n Buttons(options: PaypalButtonOptions): PaypalButtonRender;\n Messages(options: MessagingOptions): MessagingRender;\n}\n\nexport interface PaypalButton {\n render(options: PaypalButtonOptions, container: string): void;\n}\n\nexport interface PaypalExpressCheckout {\n initXO(): void;\n startFlow(url: string): void;\n closeFlow(): void;\n setup(merchantId: string, options: PaypalExpressCheckoutOptions): void;\n}\n\nexport interface PaypalExpressCheckoutOptions {\n button: string;\n environment: string;\n}\n\nexport interface MessagingOptions {\n amount: number;\n placement: string;\n}\n\nexport interface MessagingRender {\n render(container: string): void;\n}\n\nexport interface PaypalButtonOptions {\n env?: string;\n commit?: boolean;\n style?: PaypalStyleOptions;\n funding?: PaypalFundingType;\n fundingSource?: string;\n client?: PaypalClientToken;\n payment?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onAuthorize?(data: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n createOrder?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onApprove?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n}\n\nexport interface PaypalStyleOptions {\n layout?: PaypalButtonStyleLayoutOption;\n size?: PaypalButtonStyleSizeOption;\n color?: PaypalButtonStyleColorOption;\n label?: PaypalButtonStyleLabelOption;\n shape?: PaypalButtonStyleShapeOption;\n tagline?: boolean;\n fundingicons?: boolean;\n height?: number;\n}\n\nexport interface PaypalClientToken {\n production?: string;\n sandbox?: string;\n}\n\nexport interface PaypalFundingType {\n allowed?: string[];\n disallowed?: string[];\n}\n\nexport interface PaypalActions {\n payment: PaypalPaymentActions;\n request: PaypalRequestActions;\n}\n\nexport interface PaypalButtonRender {\n render(container: string): void;\n isEligible(): boolean;\n}\n\nexport interface PaypalAuthorizeData {\n payerId: string;\n paymentId?: string;\n billingToken?: string;\n payerID?: string;\n paymentID?: string;\n}\n\nexport interface PaypalFundingTypeList {\n CARD?: string;\n CREDIT?: string;\n PAYPAL?: string;\n PAYLATER?: string;\n}\n\nexport interface PaypalPaymentActions {\n get(id: string): Promise;\n}\n\nexport interface PaypalRequestActions {\n post(url: string, payload?: object, options?: object): Promise<{ id: string }>;\n}\n","import {\n Address,\n LegacyAddress,\n NotInitializedError,\n NotInitializedErrorType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n BraintreeBankAccount,\n BraintreeClient,\n BraintreeDataCollector,\n BraintreeDetails,\n BraintreeEnv,\n BraintreeError,\n BraintreeHostWindow,\n BraintreeModule,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeShippingAddressOverride,\n} from './braintree';\nimport BraintreeScriptLoader from './braintree-script-loader';\nimport isBraintreeError from './is-braintree-error';\nimport { PAYPAL_COMPONENTS } from './paypal';\nimport {\n BraintreeLocalMethods,\n GetLocalPaymentInstance,\n LocalPaymentInstance,\n} from './braintree-local-payment-methods/braintree-local-methods-options';\n\nexport default class BraintreeIntegrationService {\n private client?: Promise;\n private clientToken?: string;\n private dataCollectors: {\n default?: BraintreeDataCollector;\n paypal?: BraintreeDataCollector;\n } = {};\n private paypalCheckout?: BraintreePaypalCheckout;\n private usBankAccount?: Promise;\n private braintreeLocalMethods?: BraintreeLocalMethods;\n\n constructor(\n private braintreeScriptLoader: BraintreeScriptLoader,\n private braintreeHostWindow: BraintreeHostWindow,\n ) {}\n\n initialize(clientToken: string) {\n this.clientToken = clientToken;\n }\n\n async getClient(): Promise {\n if (!this.clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!this.client) {\n const clientCreator = await this.braintreeScriptLoader.loadClient();\n\n this.client = clientCreator.create({ authorization: this.clientToken });\n }\n\n return this.client;\n }\n\n async getPaypalCheckout(\n config: Partial,\n onSuccess: (instance: BraintreePaypalCheckout) => void,\n onError: (error: BraintreeError) => void,\n ): Promise {\n const client = await this.getClient();\n const paypalCheckout = await this.braintreeScriptLoader.loadPaypalCheckout();\n\n const paypalCheckoutConfig = { client };\n const paypalCheckoutCallback = (\n error: BraintreeError | undefined,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n if (error) {\n return onError(error);\n }\n\n const paypalSdkLoadCallback = () => onSuccess(braintreePaypalCheckout);\n const paypalSdkLoadConfig = {\n currency: config.currency,\n ...(config.isCreditEnabled && { 'enable-funding': 'paylater' }),\n components: PAYPAL_COMPONENTS.toString(),\n intent: config.intent,\n };\n\n if (!this.braintreeHostWindow.paypal) {\n braintreePaypalCheckout.loadPayPalSDK(paypalSdkLoadConfig, paypalSdkLoadCallback);\n } else {\n onSuccess(braintreePaypalCheckout);\n }\n };\n\n this.paypalCheckout = await paypalCheckout.create(\n paypalCheckoutConfig,\n paypalCheckoutCallback,\n );\n\n return this.paypalCheckout;\n }\n\n async loadBraintreeLocalMethods(\n getLocalPaymentInstance: GetLocalPaymentInstance,\n merchantAccountId: string,\n ) {\n const client = await this.getClient();\n const braintreeLocalMethods = await this.braintreeScriptLoader.loadBraintreeLocalMethods();\n\n if (!this.braintreeLocalMethods) {\n this.braintreeLocalMethods = braintreeLocalMethods.create(\n {\n client,\n merchantAccountId,\n },\n (localPaymentErr: string, localPaymentInstance: LocalPaymentInstance) => {\n if (localPaymentErr) {\n throw new Error(localPaymentErr);\n }\n getLocalPaymentInstance(localPaymentInstance);\n },\n );\n }\n\n return this.braintreeLocalMethods;\n }\n\n async getUsBankAccount() {\n if (!this.usBankAccount) {\n const client = await this.getClient();\n const usBankAccount = await this.braintreeScriptLoader.loadUsBankAccount();\n\n this.usBankAccount = usBankAccount.create({ client });\n }\n\n return this.usBankAccount;\n }\n\n async getDataCollector(options?: { paypal: boolean }): Promise {\n const cacheKey = options?.paypal ? 'paypal' : 'default';\n let cached = this.dataCollectors[cacheKey];\n\n if (!cached) {\n try {\n const client = await this.getClient();\n const dataCollector = await this.braintreeScriptLoader.loadDataCollector();\n\n cached = await dataCollector.create({ client, kount: true, ...options });\n } catch (error) {\n if (isBraintreeError(error) && error.code === 'DATA_COLLECTOR_KOUNT_NOT_ENABLED') {\n cached = {\n deviceData: undefined,\n teardown: () => Promise.resolve(),\n };\n } else {\n throw error;\n }\n }\n\n this.dataCollectors[cacheKey] = cached;\n }\n\n return cached;\n }\n\n getBraintreeEnv(isTestMode = false): BraintreeEnv {\n return isTestMode ? BraintreeEnv.Sandbox : BraintreeEnv.Production;\n }\n\n mapToBraintreeShippingAddressOverride(address: Address): BraintreeShippingAddressOverride {\n return {\n recipientName: `${address.firstName} ${address.lastName}`,\n line1: address.address1,\n line2: address.address2,\n city: address.city,\n state: address.stateOrProvinceCode,\n postalCode: address.postalCode,\n countryCode: address.countryCode,\n phone: address.phone,\n };\n }\n\n mapToLegacyShippingAddress(details: BraintreeDetails): Partial {\n const { email, phone, shippingAddress } = details;\n const recipientName = shippingAddress?.recipientName || '';\n const [firstName, lastName] = recipientName.split(' ');\n\n return {\n email,\n first_name: firstName || '',\n last_name: lastName || '',\n phone_number: phone,\n address_line_1: shippingAddress?.line1,\n address_line_2: shippingAddress?.line2,\n city: shippingAddress?.city,\n state: shippingAddress?.state,\n country_code: shippingAddress?.countryCode,\n postal_code: shippingAddress?.postalCode,\n };\n }\n\n mapToLegacyBillingAddress(details: BraintreeDetails): Partial {\n const { billingAddress, email, firstName, lastName, phone, shippingAddress } = details;\n\n const address = billingAddress || shippingAddress;\n\n return {\n email,\n first_name: firstName,\n last_name: lastName,\n phone_number: phone,\n address_line_1: address?.line1,\n address_line_2: address?.line2,\n city: address?.city,\n state: address?.state,\n country_code: address?.countryCode,\n postal_code: address?.postalCode,\n };\n }\n\n removeElement(elementId?: string): void {\n const element = elementId && document.getElementById(elementId);\n\n if (element) {\n element.remove();\n }\n }\n\n async getSessionId(): Promise {\n const { deviceData } = await this.getDataCollector();\n\n return deviceData;\n }\n\n async teardown(): Promise {\n await this.teardownModule(this.dataCollectors.default);\n await this.teardownModule(this.dataCollectors.paypal);\n this.dataCollectors = {};\n\n await this.teardownModule(this.paypalCheckout);\n this.paypalCheckout = undefined;\n\n // TODO: should be added in future migrations\n\n // await this.teardownModule(this._3ds);\n // this._3ds = undefined;\n\n // await this.teardownModule(this._googlePay);\n // this._googlePay = undefined;\n\n // await this.teardownModule(this._venmoCheckout);\n // this._venmoCheckout = undefined;\n\n // await this.teardownModule(this._visaCheckout);\n // this._visaCheckout = undefined;\n }\n\n private teardownModule(module?: BraintreeModule) {\n return module ? module.teardown() : Promise.resolve();\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n BraintreeBankAccountCreator,\n BraintreeClientCreator,\n BraintreeDataCollectorCreator,\n BraintreeHostWindow,\n BraintreePaypalCheckoutCreator,\n} from './braintree';\n\nconst VERSION = '3.81.0';\n\nexport default class BraintreeScriptLoader {\n constructor(\n private scriptLoader: ScriptLoader,\n private braintreeHostWindow: BraintreeHostWindow,\n ) {}\n\n async loadClient(): Promise {\n await this.scriptLoader.loadScript(\n `//js.braintreegateway.com/web/${VERSION}/js/client.min.js`,\n );\n\n if (!this.braintreeHostWindow.braintree?.client) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.braintreeHostWindow.braintree.client;\n }\n\n async loadPaypalCheckout(): Promise {\n await this.scriptLoader.loadScript(\n `//js.braintreegateway.com/web/${VERSION}/js/paypal-checkout.min.js`,\n );\n\n if (!this.braintreeHostWindow.braintree?.paypalCheckout) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.braintreeHostWindow.braintree.paypalCheckout;\n }\n\n async loadBraintreeLocalMethods() {\n await this.scriptLoader.loadScript(\n `//js.braintreegateway.com/web/${VERSION}/js/local-payment.min.js`,\n );\n\n if (!this.braintreeHostWindow.braintree?.localPayment) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.braintreeHostWindow.braintree.localPayment;\n }\n\n async loadDataCollector(): Promise {\n await this.scriptLoader.loadScript(\n `//js.braintreegateway.com/web/${VERSION}/js/data-collector.min.js`,\n );\n\n if (!this.braintreeHostWindow.braintree?.dataCollector) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.braintreeHostWindow.braintree.dataCollector;\n }\n\n async loadUsBankAccount(): Promise {\n await this.scriptLoader.loadScript(\n `//js.braintreegateway.com/web/${VERSION}/js/us-bank-account.min.js`,\n );\n\n if (\n !this.braintreeHostWindow.braintree ||\n !this.braintreeHostWindow.braintree.usBankAccount\n ) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.braintreeHostWindow.braintree.usBankAccount;\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n RequestOptions,\n StandardError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n BraintreeError,\n BraintreeHostWindow,\n BraintreeInitializationData,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeTokenizePayload,\n} from '../braintree';\nimport BraintreeIntegrationService from '../braintree-integration-service';\nimport isBraintreeError from '../is-braintree-error';\nimport { PaypalAuthorizeData } from '../paypal';\n\nimport BraintreePaypalCustomerInitializeOptions, {\n WithBraintreePaypalCustomerInitializeOptions,\n} from './braintree-paypal-customer-options';\n\nexport default class BraintreePaypalCustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private formPoster: FormPoster,\n private braintreeIntegrationService: BraintreeIntegrationService,\n private braintreeHostWindow: BraintreeHostWindow,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithBraintreePaypalCustomerInitializeOptions,\n ): Promise {\n const { braintreepaypal, methodId } = options;\n const { container, buttonHeight, onError } = braintreepaypal || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!braintreepaypal) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypal\" argument is not provided.`,\n );\n }\n\n if (!container) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypal.container\" argument is not provided.`,\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod: PaymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const currencyCode = state.getCartOrThrow().currency.code;\n const paypalCheckoutOptions: Partial = {\n currency: currencyCode,\n intent: paymentMethod.initializationData?.intent,\n isCreditEnabled: paymentMethod.initializationData?.isCreditEnabled,\n };\n\n const paypalCheckoutSuccessCallback = (\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n this.renderPayPalButton(\n braintreePaypalCheckout,\n braintreepaypal,\n container,\n methodId,\n Boolean(paymentMethod.config.testMode),\n buttonHeight,\n );\n };\n const paypalCheckoutErrorCallback = (error: BraintreeError) =>\n this.handleError(error, container, onError);\n\n this.braintreeIntegrationService.initialize(paymentMethod.clientToken);\n await this.braintreeIntegrationService.getPaypalCheckout(\n paypalCheckoutOptions,\n paypalCheckoutSuccessCallback,\n paypalCheckoutErrorCallback,\n );\n }\n\n async deinitialize(): Promise {\n await this.braintreeIntegrationService.teardown();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n private renderPayPalButton(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypal: BraintreePaypalCustomerInitializeOptions,\n containerId: string,\n methodId: string,\n testMode: boolean,\n buttonHeight = 40,\n ): void {\n const { paypal } = this.braintreeHostWindow;\n const fundingSource = paypal?.FUNDING.PAYPAL;\n\n if (paypal && fundingSource) {\n const paypalButtonRender = paypal.Buttons({\n env: this.braintreeIntegrationService.getBraintreeEnv(testMode),\n commit: false,\n fundingSource,\n style: {\n height: buttonHeight,\n },\n createOrder: () =>\n this.setupPayment(braintreePaypalCheckout, braintreepaypal, methodId),\n onApprove: (authorizeData: PaypalAuthorizeData) =>\n this.tokenizePayment(\n authorizeData,\n braintreePaypalCheckout,\n methodId,\n braintreepaypal,\n ),\n });\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${containerId}`);\n }\n } else {\n this.braintreeIntegrationService.removeElement(containerId);\n }\n }\n\n private async setupPayment(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypal: BraintreePaypalCustomerInitializeOptions,\n methodId: string,\n ): Promise {\n try {\n await this.paymentIntegrationService.loadDefaultCheckout();\n\n const state = this.paymentIntegrationService.getState();\n const amount = state.getCheckoutOrThrow().outstandingBalance;\n const currency = state.getCartOrThrow().currency.code;\n const customer = state.getCustomer();\n const paymentMethod: PaymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const address = customer?.addresses[0];\n const shippingAddressOverride = address\n ? this.braintreeIntegrationService.mapToBraintreeShippingAddressOverride(address)\n : undefined;\n\n return await braintreePaypalCheckout.createPayment({\n flow: 'checkout',\n enableShippingAddress: true,\n shippingAddressEditable: false,\n shippingAddressOverride,\n amount,\n currency,\n offerCredit: false,\n intent: paymentMethod.initializationData?.intent,\n });\n } catch (error) {\n const { container, onError } = braintreepaypal;\n\n this.handleError(error, container, onError);\n }\n }\n\n private async tokenizePayment(\n authorizeData: PaypalAuthorizeData,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n methodId: string,\n braintreepaypal: BraintreePaypalCustomerInitializeOptions,\n ): Promise {\n try {\n const { deviceData } = await this.braintreeIntegrationService.getDataCollector({\n paypal: true,\n });\n const tokenizePayload = await braintreePaypalCheckout.tokenizePayment(authorizeData);\n const { details, nonce } = tokenizePayload;\n const billingAddress =\n this.braintreeIntegrationService.mapToLegacyBillingAddress(details);\n const shippingAddress =\n this.braintreeIntegrationService.mapToLegacyShippingAddress(details);\n\n this.formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n provider: methodId,\n action: 'set_external_checkout',\n nonce,\n device_data: deviceData,\n billing_address: JSON.stringify(billingAddress),\n shipping_address: JSON.stringify(shippingAddress),\n });\n\n return tokenizePayload;\n } catch (error) {\n const { container, onError } = braintreepaypal;\n\n this.handleError(error, container, onError);\n }\n }\n\n private handleError(\n error: unknown,\n buttonContainerId: string,\n onErrorCallback?: (error: BraintreeError | StandardError) => void,\n ): void {\n this.braintreeIntegrationService.removeElement(buttonContainerId);\n\n if (onErrorCallback && isBraintreeError(error)) {\n onErrorCallback(error);\n } else {\n throw error;\n }\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BraintreeHostWindow } from '../braintree';\nimport BraintreeIntegrationService from '../braintree-integration-service';\nimport BraintreeScriptLoader from '../braintree-script-loader';\n\nimport BraintreePaypalCustomerStrategy from './braintree-paypal-customer-strategy';\n\nconst createBraintreePaypalCustomerStrategy: CustomerStrategyFactory<\n BraintreePaypalCustomerStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n braintreeHostWindow,\n );\n\n return new BraintreePaypalCustomerStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeIntegrationService,\n braintreeHostWindow,\n );\n};\n\nexport default toResolvableModule(createBraintreePaypalCustomerStrategy, [\n { id: 'braintreepaypal' },\n]);\n","import StandardError from './standard-error';\n\n/**\n * This error should be thrown when a shopper tries to sign in as a guest but\n * they are already signed in as a registered customer.\n */\nexport default class BuyNowCartCreationError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'An unexpected error has occurred during buy now cart creation process. Please try again later.',\n );\n\n this.name = 'BuyNowCartCreationError';\n this.type = 'buy_now_cart_creation_error';\n }\n}\n","export enum CartSource {\n BuyNow = 'BUY_NOW',\n}\n","import {\n BuyNowCartRequestBody,\n HostedInstrument,\n ShippingOption,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\n/**\n *\n * PayPal Commerce Funding sources\n *\n */\nexport type FundingType = string[];\nexport type EnableFundingType = FundingType | string;\n\nexport interface PayPalCommerceSDKFunding {\n CARD: string;\n PAYPAL: string;\n CREDIT: string;\n PAYLATER: string;\n OXXO: string;\n SEPA: string;\n VENMO: string;\n}\n\n/**\n *\n * PayPal Commerce SDK\n *\n */\nexport interface PayPalSDK {\n FUNDING: PayPalCommerceSDKFunding;\n HostedFields: {\n isEligible(): boolean;\n render(data: PayPalCommerceHostedFieldsRenderOptions): Promise;\n };\n Buttons(options: PayPalCommerceButtonsOptions): PayPalCommerceButtons;\n PaymentFields(options: PayPalCommercePaymentFieldsOptions): PayPalCommercePaymentFields;\n Messages(options: PayPalCommerceMessagesOptions): PayPalCommerceMessages;\n}\n\nexport interface PayPalCommerceScriptParams {\n 'client-id'?: string;\n 'merchant-id'?: string;\n 'buyer-country'?: string;\n 'disable-funding'?: FundingType;\n 'enable-funding'?: EnableFundingType;\n 'data-client-token'?: string;\n 'data-partner-attribution-id'?: string;\n currency?: string;\n commit?: boolean;\n intent?: PayPalCommerceIntent;\n components?: ComponentsScriptType;\n}\n\nexport enum PayPalCommerceIntent {\n AUTHORIZE = 'authorize',\n CAPTURE = 'capture',\n}\n\nexport type ComponentsScriptType = Array<\n 'buttons' | 'funding-eligibility' | 'hosted-fields' | 'messages' | 'payment-fields'\n>;\n\nexport interface PayPalCommerceHostWindow extends Window {\n paypal?: PayPalSDK;\n paypalLoadScript?(options: PayPalCommerceScriptParams): Promise<{ paypal: PayPalSDK }>;\n}\n\n/**\n *\n * PayPal Commerce Initialization Data\n *\n */\nexport interface PayPalCommerceInitializationData {\n attributionId?: string;\n availableAlternativePaymentMethods: FundingType;\n buttonStyle?: PayPalButtonStyleOptions;\n buyerCountry?: string;\n clientId: string;\n clientToken?: string;\n enabledAlternativePaymentMethods: FundingType;\n isDeveloperModeApplicable?: boolean;\n intent?: PayPalCommerceIntent;\n isHostedCheckoutEnabled?: boolean;\n isPayPalCreditAvailable?: boolean;\n isVenmoEnabled?: boolean;\n merchantId?: string;\n orderId?: string;\n shouldRenderFields?: boolean;\n}\n\n/**\n *\n * PayPal Commerce BuyNow\n *\n */\nexport interface PayPalBuyNowInitializeOptions {\n getBuyNowCartRequestBody(): BuyNowCartRequestBody;\n}\n\n/**\n *\n * PayPal Commerce Hosted Fields\n *\n */\nexport interface PayPalCommerceHostedFieldsRenderOptions {\n fields?: {\n number?: PayPalCommerceHostedFieldOption;\n cvv?: PayPalCommerceHostedFieldOption;\n expirationDate?: PayPalCommerceHostedFieldOption;\n };\n paymentsSDK?: boolean;\n styles?: {\n input?: { [key: string]: string };\n '.invalid'?: { [key: string]: string };\n '.valid'?: { [key: string]: string };\n ':focus'?: { [key: string]: string };\n };\n createOrder(): Promise;\n}\n\nexport interface PayPalCommerceHostedFieldOption {\n selector: string;\n placeholder?: string;\n}\n\nexport interface PayPalCommerceHostedFields {\n submit(\n options?: PayPalCommerceHostedFieldsSubmitOptions,\n ): Promise;\n getState(): PayPalCommerceHostedFieldsState;\n on(eventName: string, callback: (event: PayPalCommerceHostedFieldsState) => void): void;\n}\n\nexport interface PayPalCommerceHostedFieldsSubmitOptions {\n contingencies?: Array<'3D_SECURE'>;\n cardholderName?: string;\n}\n\nexport interface PayPalCommerceHostedFieldsApprove {\n orderId: string;\n liabilityShift?: 'POSSIBLE' | 'NO' | 'UNKNOWN';\n}\n\nexport interface PayPalCommerceHostedFieldsState {\n cards: PayPalCommerceHostedFieldsCard[];\n emittedBy: string;\n fields: {\n number?: PayPalCommerceHostedFieldsFieldData;\n expirationDate?: PayPalCommerceHostedFieldsFieldData;\n expirationMonth?: PayPalCommerceHostedFieldsFieldData;\n expirationYear?: PayPalCommerceHostedFieldsFieldData;\n cvv?: PayPalCommerceHostedFieldsFieldData;\n postalCode?: PayPalCommerceHostedFieldsFieldData;\n };\n}\n\nexport interface PayPalCommerceHostedFieldsCard {\n type: string;\n niceType: string;\n code: {\n name: string;\n size: number;\n };\n}\n\nexport interface PayPalCommerceHostedFieldsFieldData {\n container: HTMLElement;\n isFocused: boolean;\n isEmpty: boolean;\n isPotentiallyValid: boolean;\n isValid: boolean;\n}\n\n/**\n *\n * PayPal Commerce Buttons\n *\n */\nexport interface PayPalCommerceButtons {\n render(id: string): void;\n close(): void;\n isEligible(): boolean;\n}\n\nexport interface PayPalCommerceButtonsOptions {\n experience?: string;\n style?: PayPalButtonStyleOptions;\n fundingSource: string;\n createOrder(): Promise;\n onApprove(\n data: ApproveCallbackPayload,\n actions: ApproveCallbackActions,\n ): Promise | void;\n onComplete?(data: CompleteCallbackDataPayload): Promise;\n onClick?(data: ClickCallbackPayload, actions: ClickCallbackActions): Promise;\n onError?(error: Error): void;\n onCancel?(): void;\n onShippingAddressChange?(data: ShippingAddressChangeCallbackPayload): Promise;\n onShippingOptionsChange?(data: ShippingOptionChangeCallbackPayload): Promise;\n}\n\nexport interface ClickCallbackPayload {\n fundingSource: string;\n}\n\nexport interface ClickCallbackActions {\n reject(): void;\n resolve(): void;\n}\n\nexport interface ShippingAddressChangeCallbackPayload {\n orderId: string;\n shippingAddress: PayPalAddress;\n}\n\nexport interface PayPalAddress {\n city: string;\n country_code: string;\n postal_code: string;\n state: string;\n}\n\nexport interface ShippingOptionChangeCallbackPayload {\n orderId: string;\n selectedShippingOption: PayPalSelectedShippingOption;\n}\n\nexport interface PayPalSelectedShippingOption {\n amount: {\n currency_code: string;\n value: string;\n };\n id: string;\n label: string;\n selected: boolean;\n type: string;\n}\n\nexport interface ApproveCallbackPayload {\n orderID?: string;\n}\n\nexport interface ApproveCallbackActions {\n order: {\n get: () => Promise;\n };\n}\n\nexport interface PayPalOrderDetails {\n payer: {\n name: {\n given_name: string;\n surname: string;\n };\n email_address: string;\n address: PayPalOrderAddress;\n };\n purchase_units: Array<{\n shipping: {\n address: PayPalOrderAddress;\n };\n }>;\n}\n\nexport interface PayPalOrderAddress {\n address_line_1: string;\n admin_area_2: string;\n admin_area_1?: string;\n postal_code: string;\n country_code: string;\n}\n\nexport interface CompleteCallbackDataPayload {\n intent: string;\n orderID: string;\n}\n\nexport enum StyleButtonLabel {\n paypal = 'paypal',\n checkout = 'checkout',\n buynow = 'buynow',\n pay = 'pay',\n installment = 'installment',\n}\n\nexport enum StyleButtonColor {\n gold = 'gold',\n blue = 'blue',\n silver = 'silver',\n black = 'black',\n white = 'white',\n}\n\nexport enum StyleButtonShape {\n pill = 'pill',\n rect = 'rect',\n}\n\nexport interface PayPalButtonStyleOptions {\n color?: StyleButtonColor;\n shape?: StyleButtonShape;\n height?: number;\n label?: StyleButtonLabel;\n}\n\n/**\n *\n * PayPal Commerce Payment fields\n *\n */\nexport interface PayPalCommercePaymentFields {\n render(id: string): void;\n}\n\nexport interface PayPalCommercePaymentFieldsOptions {\n style?: PayPalCommerceFieldsStyleOptions;\n fundingSource: string;\n fields: {\n name?: {\n value?: string;\n };\n email?: {\n value?: string;\n };\n };\n}\n\nexport interface PayPalCommerceFieldsStyleOptions {\n variables?: {\n fontFamily?: string;\n fontSizeBase?: string;\n fontSizeSm?: string;\n fontSizeM?: string;\n fontSizeLg?: string;\n textColor?: string;\n colorTextPlaceholder?: string;\n colorBackground?: string;\n colorInfo?: string;\n colorDanger?: string;\n borderRadius?: string;\n borderColor?: string;\n borderWidth?: string;\n borderFocusColor?: string;\n spacingUnit?: string;\n };\n rules?: {\n [key: string]: any;\n };\n}\n\n/**\n *\n * PayPalCommerce Messages\n *\n */\nexport interface PayPalCommerceMessages {\n render(id: string): void;\n}\n\nexport interface PayPalCommerceMessagesOptions {\n amount: number;\n placement: string;\n style?: PayPalCommerceMessagesStyleOptions;\n fundingSource?: string;\n}\n\nexport interface PayPalCommerceMessagesStyleOptions {\n layout?: string;\n}\n\n/**\n *\n * Other\n *\n */\nexport enum NonInstantAlternativePaymentMethods {\n OXXO = 'oxxo',\n}\n\nexport interface PayPalOrderData {\n orderId: string;\n approveUrl: string;\n}\n\nexport interface PayPalUpdateOrderRequestBody {\n availableShippingOptions?: ShippingOption[];\n cartId: string;\n selectedShippingOption?: ShippingOption;\n}\n\nexport interface PayPalCreateOrderRequestBody extends HostedInstrument, VaultedInstrument {\n cartId: string;\n}\n\nexport enum PayPalOrderStatus {\n Approved = 'APPROVED',\n Created = 'CREATED',\n PayerActionRequired = 'PAYER_ACTION_REQUIRED',\n}\n\nexport interface PayPalOrderStatusData {\n status: PayPalOrderStatus;\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { isNil, omitBy } from 'lodash';\n\nimport {\n BillingAddressRequestBody,\n BuyNowCartCreationError,\n Cart,\n CartSource,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethodClientUnavailableError,\n RequestError,\n ShippingOption,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceRequestSender from './paypal-commerce-request-sender';\nimport PayPalCommerceScriptLoader from './paypal-commerce-script-loader';\nimport {\n PayPalButtonStyleOptions,\n PayPalBuyNowInitializeOptions,\n PayPalCommerceInitializationData,\n PayPalCreateOrderRequestBody,\n PayPalOrderDetails,\n PayPalOrderStatus,\n PayPalSDK,\n StyleButtonColor,\n StyleButtonLabel,\n StyleButtonShape,\n} from './paypal-commerce-types';\n\nexport default class PayPalCommerceIntegrationService {\n private paypalSdk?: PayPalSDK;\n\n constructor(\n private formPoster: FormPoster,\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceRequestSender: PayPalCommerceRequestSender,\n private paypalCommerceScriptLoader: PayPalCommerceScriptLoader,\n ) {}\n\n /**\n *\n * PayPalSDK methods\n *\n */\n async loadPayPalSdk(\n methodId: string,\n providedCurrencyCode?: string,\n initializesOnCheckoutPage?: boolean,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n const currencyCode = providedCurrencyCode || state.getCartOrThrow().currency.code;\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n this.paypalSdk = await this.paypalCommerceScriptLoader.getPayPalSDK(\n paymentMethod,\n currencyCode,\n initializesOnCheckoutPage,\n );\n\n return this.paypalSdk;\n }\n\n getPayPalSdkOrThrow(): PayPalSDK {\n if (!this.paypalSdk) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.paypalSdk;\n }\n\n /**\n *\n * Buy Now cart creation methods\n *\n */\n async createBuyNowCartOrThrow(\n buyNowInitializeOptions: PayPalBuyNowInitializeOptions,\n ): Promise {\n const cartRequestBody = buyNowInitializeOptions.getBuyNowCartRequestBody();\n\n if (!cartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n return await this.paymentIntegrationService.createBuyNowCart(cartRequestBody);\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n\n /**\n *\n * Order methods\n *\n */\n async createOrder(\n providerId: string,\n requestBody?: Partial,\n ): Promise {\n const cartId = this.paymentIntegrationService.getState().getCartOrThrow().id;\n\n const { orderId } = await this.paypalCommerceRequestSender.createOrder(providerId, {\n cartId,\n ...requestBody,\n });\n\n return orderId;\n }\n\n async updateOrder(): Promise {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const consignment = state.getConsignmentsOrThrow()[0];\n\n try {\n await this.paypalCommerceRequestSender.updateOrder({\n availableShippingOptions: consignment.availableShippingOptions,\n cartId: cart.id,\n selectedShippingOption: consignment.selectedShippingOption,\n });\n } catch (_error) {\n throw new RequestError();\n }\n }\n\n async getOrderStatus(): Promise {\n try {\n const { status } = await this.paypalCommerceRequestSender.getOrderStatus();\n\n return status;\n } catch (_error) {\n throw new RequestError();\n }\n }\n\n /**\n *\n * Payment submitting and tokenizing methods\n *\n */\n tokenizePayment(methodId: string, orderId?: string): void {\n const cart = this.paymentIntegrationService.getState().getCartOrThrow();\n\n if (!orderId) {\n throw new MissingDataError(MissingDataErrorType.MissingOrderId);\n }\n\n return this.formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n action: 'set_external_checkout',\n provider: methodId,\n order_id: orderId,\n ...(cart.source === CartSource.BuyNow && { cart_id: cart.id }),\n });\n }\n\n async submitPayment(methodId: string, orderId: string): Promise {\n const paymentData = {\n formattedPayload: {\n vault_payment_instrument: null,\n set_as_default_stored_instrument: null,\n device_info: null,\n method_id: methodId,\n paypal_account: {\n order_id: orderId,\n },\n },\n };\n\n await this.paymentIntegrationService.submitPayment({ methodId, paymentData });\n }\n\n /**\n *\n * Shipping options methods\n *\n */\n getShippingOptionOrThrow(selectedShippingOptionId?: string): ShippingOption {\n const state = this.paymentIntegrationService.getState();\n const consignment = state.getConsignmentsOrThrow()[0];\n\n const availableShippingOptions = consignment.availableShippingOptions || [];\n\n const recommendedShippingOption = availableShippingOptions.find(\n (option) => option.isRecommended,\n );\n\n const selectedShippingOption = selectedShippingOptionId\n ? availableShippingOptions.find((option) => option.id === selectedShippingOptionId)\n : availableShippingOptions.find(\n (option) => option.id === consignment.selectedShippingOption?.id,\n );\n\n const shippingOptionToSelect =\n selectedShippingOption || recommendedShippingOption || availableShippingOptions[0];\n\n if (!shippingOptionToSelect) {\n throw new Error(\"Your order can't be shipped to this address\");\n }\n\n return shippingOptionToSelect;\n }\n\n /**\n *\n * Address transforming methods\n *\n */\n getAddress(address?: Partial): BillingAddressRequestBody {\n return {\n firstName: address?.firstName || '',\n lastName: address?.lastName || '',\n email: address?.email || '',\n phone: '',\n company: '',\n address1: address?.address1 || '',\n address2: '',\n city: address?.city || '',\n countryCode: address?.countryCode || '',\n postalCode: address?.postalCode || '',\n stateOrProvince: '',\n stateOrProvinceCode: address?.stateOrProvinceCode || '',\n customFields: [],\n };\n }\n\n getBillingAddressFromOrderDetails({ payer }: PayPalOrderDetails): BillingAddressRequestBody {\n return this.getAddress({\n firstName: payer.name.given_name,\n lastName: payer.name.surname,\n email: payer.email_address,\n address1: payer.address.address_line_1,\n city: payer.address.admin_area_2,\n countryCode: payer.address.country_code,\n postalCode: payer.address.postal_code,\n stateOrProvinceCode: payer.address.admin_area_1,\n });\n }\n\n getShippingAddressFromOrderDetails(\n orderDetails: PayPalOrderDetails,\n ): BillingAddressRequestBody {\n const { payer, purchase_units } = orderDetails;\n const shippingAddress = purchase_units[0]?.shipping?.address || {};\n\n return this.getAddress({\n firstName: payer.name.given_name,\n lastName: payer.name.surname,\n email: payer.email_address,\n address1: shippingAddress.address_line_1,\n city: shippingAddress.admin_area_2,\n countryCode: shippingAddress.country_code,\n postalCode: shippingAddress.postal_code,\n stateOrProvinceCode: shippingAddress.admin_area_1,\n });\n }\n\n /**\n *\n * Buttons style methods\n *\n */\n getValidButtonStyle(style?: PayPalButtonStyleOptions): PayPalButtonStyleOptions {\n const { color, height, label, shape } = style || {};\n\n const validStyles = {\n color: color && StyleButtonColor[color] ? color : undefined,\n height: this.getValidHeight(height),\n label: label && StyleButtonLabel[label] ? label : undefined,\n shape: shape && StyleButtonShape[shape] ? shape : undefined,\n };\n\n return omitBy(validStyles, isNil);\n }\n\n getValidHeight(height?: number): number {\n const defaultHeight = 40;\n const minHeight = 25;\n const maxHeight = 55;\n\n if (!height || typeof height !== 'number') {\n return defaultHeight;\n }\n\n if (height > maxHeight) {\n return maxHeight;\n }\n\n if (height < minHeight) {\n return minHeight;\n }\n\n return height;\n }\n\n /**\n *\n * Utils methods\n *\n */\n removeElement(elementId?: string): void {\n const element = elementId && document.getElementById(elementId);\n\n if (element) {\n element.remove();\n }\n }\n}\n","export const INTERNAL_USE_ONLY =\n 'This API endpoint is for internal use only and may change in the future';\n","enum ContentType {\n Json = 'application/json',\n JsonV1 = 'application/vnd.bc.v1+json',\n}\n\nexport default ContentType;\n","export const SDK_VERSION_HEADERS = { 'X-Checkout-SDK-Version': LIBRARY_VERSION };\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n SDK_VERSION_HEADERS,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n PayPalCreateOrderRequestBody,\n PayPalOrderData,\n PayPalOrderStatusData,\n PayPalUpdateOrderRequestBody,\n} from './paypal-commerce-types';\n\nexport default class PayPalCommerceRequestSender {\n constructor(private requestSender: RequestSender) {}\n\n async createOrder(\n providerId: string,\n requestBody: Partial,\n ): Promise {\n const url = `/api/storefront/payment/${providerId}`;\n const body = requestBody;\n const headers = {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n 'Content-Type': ContentType.Json,\n ...SDK_VERSION_HEADERS,\n };\n\n const res = await this.requestSender.post(url, { headers, body });\n\n return res.body;\n }\n\n // TODO: add response type interface Promise in another task\n async updateOrder(requestBody: PayPalUpdateOrderRequestBody) {\n const url = `/api/storefront/initialization/paypalcommerce`;\n const body = requestBody;\n const headers = {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n 'Content-Type': ContentType.Json,\n ...SDK_VERSION_HEADERS,\n };\n\n const res = await this.requestSender.put(url, { headers, body });\n\n return res.body;\n }\n\n async getOrderStatus(): Promise {\n const url = '/api/storefront/initialization/paypalcommerce';\n const headers = {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n 'Content-Type': ContentType.Json,\n ...SDK_VERSION_HEADERS,\n };\n\n const res = await this.requestSender.get(url, { headers });\n\n return res.body;\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n MissingDataError,\n MissingDataErrorType,\n PaymentMethod,\n PaymentMethodClientUnavailableError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n FundingType,\n PayPalCommerceHostWindow,\n PayPalCommerceInitializationData,\n PayPalCommerceScriptParams,\n PayPalSDK,\n} from './paypal-commerce-types';\n\nconst PAYPAL_SDK_VERSION = '5.0.5';\n\nexport default class PayPalCommerceScriptLoader {\n private window: PayPalCommerceHostWindow;\n private paypalSdk?: PayPalSDK;\n\n constructor(private scriptLoader: ScriptLoader) {\n this.window = window;\n }\n\n async getPayPalSDK(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n initializesOnCheckoutPage?: boolean,\n ): Promise {\n if (!this.paypalSdk) {\n this.paypalSdk = await this.loadPayPalSDK(\n this.getPayPalSdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n initializesOnCheckoutPage,\n ),\n );\n }\n\n return this.paypalSdk;\n }\n\n private async loadPayPalSDK(\n paypalSdkScriptConfig: PayPalCommerceScriptParams,\n ): Promise {\n if (!this.window.paypalLoadScript) {\n const scriptSrc = `https://unpkg.com/@paypal/paypal-js@${PAYPAL_SDK_VERSION}/dist/iife/paypal-js.min.js`;\n\n await this.scriptLoader.loadScript(scriptSrc, { async: true, attributes: {} });\n\n if (!this.window.paypalLoadScript) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n await this.window.paypalLoadScript(paypalSdkScriptConfig);\n\n if (!this.window.paypal) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.paypal;\n }\n\n private getPayPalSdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n initializesOnCheckoutPage = true,\n ): PayPalCommerceScriptParams {\n const { id, clientToken, initializationData } = paymentMethod;\n\n if (!initializationData?.clientId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n intent,\n clientId,\n merchantId,\n buyerCountry,\n attributionId,\n isVenmoEnabled,\n isHostedCheckoutEnabled,\n isPayPalCreditAvailable,\n isDeveloperModeApplicable,\n availableAlternativePaymentMethods = [],\n enabledAlternativePaymentMethods = [],\n } = initializationData;\n\n const commit = isHostedCheckoutEnabled || initializesOnCheckoutPage;\n\n const shouldEnableCard = id === 'paypalcommercecreditcards';\n const enableCardFunding = shouldEnableCard ? ['card'] : [];\n const disableCardFunding = !shouldEnableCard ? ['card'] : [];\n\n const enableCreditFunding = isPayPalCreditAvailable ? ['credit', 'paylater'] : [];\n const disableCreditFunding = !isPayPalCreditAvailable ? ['credit', 'paylater'] : [];\n\n const shouldEnableAPMs = initializesOnCheckoutPage || !commit;\n const enableVenmoFunding = shouldEnableAPMs && isVenmoEnabled ? ['venmo'] : [];\n const disableVenmoFunding = !shouldEnableAPMs || !isVenmoEnabled ? ['venmo'] : [];\n const enableAPMsFunding = shouldEnableAPMs ? enabledAlternativePaymentMethods : [];\n const disableAPMsFunding = shouldEnableAPMs\n ? availableAlternativePaymentMethods.filter(\n (apm: string) => !enabledAlternativePaymentMethods.includes(apm),\n )\n : availableAlternativePaymentMethods;\n\n const disableFunding: FundingType = [\n ...disableCardFunding,\n ...disableCreditFunding,\n ...disableVenmoFunding,\n ...disableAPMsFunding,\n ];\n const enableFunding: FundingType = [\n ...enableCardFunding,\n ...enableCreditFunding,\n ...enableVenmoFunding,\n ...enableAPMsFunding,\n ];\n\n return {\n 'client-id': clientId,\n 'data-partner-attribution-id': attributionId,\n 'data-client-token': clientToken,\n 'merchant-id': merchantId,\n 'enable-funding': enableFunding.length > 0 ? enableFunding : undefined,\n 'disable-funding': disableFunding.length > 0 ? disableFunding : undefined,\n commit,\n components: ['buttons', 'hosted-fields', 'messages', 'payment-fields'],\n currency: currencyCode,\n intent,\n ...(isDeveloperModeApplicable && { 'buyer-country': buyerCountry }),\n };\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n PayPalCommerceIntegrationService,\n PayPalCommerceRequestSender,\n PayPalCommerceScriptLoader,\n} from './index';\n\nconst createPayPalCommerceIntegrationService = (\n paymentIntegrationService: PaymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new PayPalCommerceIntegrationService(\n createFormPoster(),\n paymentIntegrationService,\n new PayPalCommerceRequestSender(createRequestSender({ host: getHost() })),\n new PayPalCommerceScriptLoader(getScriptLoader()),\n );\n};\n\nexport default createPayPalCommerceIntegrationService;\n","import { noop } from 'lodash';\n\nimport {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceCustomerInitializeOptions, {\n WithPayPalCommerceCustomerInitializeOptions,\n} from './paypal-commerce-customer-initialize-options';\n\nexport default class PayPalCommerceCustomerStrategy implements CustomerStrategy {\n private onError = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithPayPalCommerceCustomerInitializeOptions,\n ): Promise {\n const { paypalcommerce, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!paypalcommerce) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerce\" argument is not provided.`,\n );\n }\n\n if (!paypalcommerce.container) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerce.container\" argument is not provided.`,\n );\n }\n\n this.onError = paypalcommerce.onError || noop;\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.renderButton(methodId, paypalcommerce);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n\n return Promise.resolve();\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n\n return Promise.resolve();\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n private renderButton(\n methodId: string,\n paypalcommerce: PayPalCommerceCustomerInitializeOptions,\n ): void {\n const { container, onComplete } = paypalcommerce;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled } = paymentMethod.initializationData || {};\n\n const defaultCallbacks = {\n createOrder: () => this.paypalCommerceIntegrationService.createOrder('paypalcommerce'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const hostedCheckoutCallbacks = {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(data, actions, methodId, onComplete),\n };\n\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(),\n ...defaultCallbacks,\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n };\n\n const paypalButton = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButton.isEligible()) {\n paypalButton.render(`#${container}`);\n } else {\n this.paypalCommerceIntegrationService.removeElement(container);\n }\n }\n\n private async onHostedCheckoutApprove(\n data: ApproveCallbackPayload,\n actions: ApproveCallbackActions,\n methodId: string,\n onComplete?: () => void,\n ): Promise {\n if (!data.orderID) {\n throw new MissingDataError(MissingDataErrorType.MissingOrderId);\n }\n\n const cart = this.paymentIntegrationService.getState().getCartOrThrow();\n const orderDetails = await actions.order.get();\n\n try {\n const billingAddress =\n this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.paypalCommerceIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.paypalCommerceIntegrationService.submitPayment(methodId, data.orderID);\n\n if (onComplete && typeof onComplete === 'function') {\n onComplete();\n }\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingAddressChange(\n data: ShippingAddressChangeCallbackPayload,\n ): Promise {\n const address = this.paypalCommerceIntegrationService.getAddress({\n city: data.shippingAddress.city,\n countryCode: data.shippingAddress.country_code,\n postalCode: data.shippingAddress.postal_code,\n stateOrProvinceCode: data.shippingAddress.state,\n });\n\n try {\n // Info: we use the same address to fill billing and shipping addresses to have valid quota on BE for order updating process\n // on this stage we don't have access to valid customer's address except shipping data\n await this.paymentIntegrationService.updateBillingAddress(address);\n await this.paymentIntegrationService.updateShippingAddress(address);\n\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n ): Promise {\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private handleError(error: Error) {\n if (typeof this.onError === 'function') {\n this.onError(error);\n } else {\n throw error;\n }\n }\n}\n","import {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceCustomerStrategy from './paypal-commerce-customer-strategy';\n\nconst createPayPalCommerceCustomerStrategy: CustomerStrategyFactory<\n PayPalCommerceCustomerStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCustomerStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceCustomerStrategy, [{ id: 'paypalcommerce' }]);\n","import { noop } from 'lodash';\n\nimport {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n StyleButtonColor,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceCreditCustomerInitializeOptions, {\n WithPayPalCommerceCreditCustomerInitializeOptions,\n} from './paypal-commerce-credit-customer-initialize-options';\n\nexport default class PayPalCommerceCreditCustomerStrategy implements CustomerStrategy {\n private onError = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithPayPalCommerceCreditCustomerInitializeOptions,\n ): Promise {\n const { paypalcommercecredit, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!paypalcommercecredit) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"paypalcommercecredit\" argument is not provided.`,\n );\n }\n\n if (!paypalcommercecredit.container) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"paypalcommercecredit.container\" argument is not provided.`,\n );\n }\n\n this.onError = paypalcommercecredit.onError || noop;\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.renderButton(methodId, paypalcommercecredit);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n private renderButton(\n methodId: string,\n paypalCommerceCredit: PayPalCommerceCreditCustomerInitializeOptions,\n ): void {\n const { container, onComplete } = paypalCommerceCredit;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled } = paymentMethod.initializationData || {};\n\n const defaultCallbacks = {\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder('paypalcommercecredit'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const hostedCheckoutCallbacks = {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(data, actions, methodId, onComplete),\n };\n\n const fundingSources = [paypalSdk.FUNDING.PAYLATER, paypalSdk.FUNDING.CREDIT];\n let hasRenderedSmartButton = false;\n\n fundingSources.forEach((fundingSource) => {\n if (!hasRenderedSmartButton) {\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle({\n color: StyleButtonColor.gold,\n }),\n ...defaultCallbacks,\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n };\n\n const paypalButton = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButton.isEligible()) {\n paypalButton.render(`#${container}`);\n hasRenderedSmartButton = true;\n }\n }\n });\n\n if (!hasRenderedSmartButton) {\n this.paypalCommerceIntegrationService.removeElement(container);\n }\n }\n\n private async onHostedCheckoutApprove(\n data: ApproveCallbackPayload,\n actions: ApproveCallbackActions,\n methodId: string,\n onComplete?: () => void,\n ): Promise {\n if (!data.orderID) {\n throw new MissingDataError(MissingDataErrorType.MissingOrderId);\n }\n\n const cart = this.paymentIntegrationService.getState().getCartOrThrow();\n const orderDetails = await actions.order.get();\n\n try {\n const billingAddress =\n this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.paypalCommerceIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.paypalCommerceIntegrationService.submitPayment(methodId, data.orderID);\n\n if (onComplete && typeof onComplete === 'function') {\n onComplete();\n }\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingAddressChange(\n data: ShippingAddressChangeCallbackPayload,\n ): Promise {\n const address = this.paypalCommerceIntegrationService.getAddress({\n city: data.shippingAddress.city,\n countryCode: data.shippingAddress.country_code,\n postalCode: data.shippingAddress.postal_code,\n stateOrProvinceCode: data.shippingAddress.state,\n });\n\n try {\n // Info: we use the same address to fill billing and shipping addresses to have valid quota on BE for order updating process\n // on this stage we don't have access to valid customer's address except shipping data\n await this.paymentIntegrationService.updateBillingAddress(address);\n await this.paymentIntegrationService.updateShippingAddress(address);\n\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n ): Promise {\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private handleError(error: Error) {\n if (typeof this.onError === 'function') {\n this.onError(error);\n } else {\n throw error;\n }\n }\n}\n","import {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceCreditCustomerStrategy from './paypal-commerce-credit-customer-strategy';\n\nconst createPayPalCommerceCreditCustomerStrategy: CustomerStrategyFactory<\n PayPalCommerceCreditCustomerStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditCustomerStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceCreditCustomerStrategy, [\n { id: 'paypalcommercecredit' },\n]);\n","import {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n PaymentIntegrationService,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport { ApproveCallbackPayload, PayPalCommerceButtonsOptions } from '../paypal-commerce-types';\n\nimport { WithPayPalCommerceVenmoCustomerInitializeOptions } from './paypal-commerce-venmo-customer-initialize-options';\n\nexport default class PayPalCommerceVenmoCustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithPayPalCommerceVenmoCustomerInitializeOptions,\n ): Promise {\n const { paypalcommercevenmo, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!paypalcommercevenmo) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"paypalcommercevenmo\" argument is not provided.`,\n );\n }\n\n if (!paypalcommercevenmo.container) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"paypalcommercevenmo.container\" argument is not provided.`,\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.renderButton(methodId, paypalcommercevenmo.container);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n private renderButton(methodId: string, containerId: string): void {\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.VENMO,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(),\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder('paypalcommercevenmo'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const paypalButtonRender = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${containerId}`);\n } else {\n this.paypalCommerceIntegrationService.removeElement(containerId);\n }\n }\n}\n","import {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceVenmoCustomerStrategy from './paypal-commerce-venmo-customer-strategy';\n\nconst createPayPalCommerceVenmoCustomerStrategy: CustomerStrategyFactory<\n PayPalCommerceVenmoCustomerStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceVenmoCustomerStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceVenmoCustomerStrategy, [\n { id: 'paypalcommercevenmo' },\n]);\n","import {\n CustomerStrategy,\n CustomerStrategyFactory,\n CustomerStrategyResolveId,\n isResolvableModule,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ResolveIdRegistry } from '../common/registry';\nimport * as defaultCustomerStrategyFactories from '../generated/customer-strategies';\n\nexport interface CustomerStrategyFactories {\n [key: string]: CustomerStrategyFactory;\n}\n\nexport default function createCustomerStrategyRegistry(\n paymentIntegrationService: PaymentIntegrationService,\n customerStrategyFactories: CustomerStrategyFactories = defaultCustomerStrategyFactories,\n): ResolveIdRegistry {\n const registry = new ResolveIdRegistry();\n\n for (const [, createCustomerStrategy] of Object.entries(customerStrategyFactories)) {\n if (\n !isResolvableModule<\n CustomerStrategyFactory,\n CustomerStrategyResolveId\n >(createCustomerStrategy)\n ) {\n continue;\n }\n\n for (const resolverId of createCustomerStrategy.resolveIds) {\n registry.register(resolverId, () => createCustomerStrategy(paymentIntegrationService));\n }\n }\n\n return registry;\n}\n","import { ExecuteSucceededAction, SpamProtectionAction } from './spam-protection-actions';\n\nexport default function isSpamProtectionExecuteSucceededAction(\n action: SpamProtectionAction,\n): action is ExecuteSucceededAction {\n const succeededAction = action as ExecuteSucceededAction;\n\n return (\n typeof succeededAction === 'object' &&\n typeof succeededAction.payload === 'object' &&\n typeof succeededAction.payload.token === 'string'\n );\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { LoadCheckoutAction } from '../checkout';\nimport { SpamProtectionAction } from '../spam-protection';\n\nimport Customer from './customer';\nimport { InternalCustomerResponseData } from './internal-customer-responses';\n\nexport enum CustomerActionType {\n SignInCustomerRequested = 'SIGN_IN_CUSTOMER_REQUESTED',\n SignInCustomerSucceeded = 'SIGN_IN_CUSTOMER_SUCCEEDED',\n SignInCustomerFailed = 'SIGN_IN_CUSTOMER_FAILED',\n\n SignOutCustomerRequested = 'SIGN_OUT_CUSTOMER_REQUESTED',\n SignOutCustomerSucceeded = 'SIGN_OUT_CUSTOMER_SUCCEEDED',\n SignOutCustomerFailed = 'SIGN_OUT_CUSTOMER_FAILED',\n\n CreateCustomerRequested = 'CREATE_CUSTOMER_REQUESTED',\n CreateCustomerSucceeded = 'CREATE_CUSTOMER_SUCCEEDED',\n CreateCustomerFailed = 'CREATE_CUSTOMER_FAILED',\n\n CreateCustomerAddressRequested = 'CREATE_CUSTOMER_ADDRESS_REQUESTED',\n CreateCustomerAddressSucceeded = 'CREATE_CUSTOMER_ADDRESS_SUCCEEDED',\n CreateCustomerAddressFailed = 'CREATE_CUSTOMER_ADDRESS_FAILED',\n\n StripeLinkAuthenticated = 'STRIPE_LINK_AUTHENTICATED',\n}\n\nexport type CustomerAction =\n | SignInCustomerAction\n | SignOutCustomerAction\n | CreateCustomerAddressAction\n | CreateCustomerAction;\n\nexport type CreateCustomerAction =\n | CreateCustomerRequestedAction\n | CreateCustomerSucceededAction\n | CreateCustomerFailedAction\n | SpamProtectionAction\n | LoadCheckoutAction;\n\nexport type CreateCustomerAddressAction =\n | CreateCustomerAddressRequestedAction\n | CreateCustomerAddressSucceededAction\n | CreateCustomerAddressFailedAction\n | LoadCheckoutAction;\n\nexport type SignInCustomerAction =\n | SignInCustomerRequestedAction\n | SignInCustomerSucceededAction\n | SignInCustomerFailedAction\n | LoadCheckoutAction;\n\nexport type SignOutCustomerAction =\n | SignOutCustomerRequestedAction\n | SignOutCustomerSucceededAction\n | SignOutCustomerFailedAction\n | LoadCheckoutAction;\n\nexport interface SignInCustomerRequestedAction extends Action {\n type: CustomerActionType.SignInCustomerRequested;\n}\n\nexport interface StripeLinkAuthenticatedAction extends Action {\n type: CustomerActionType.StripeLinkAuthenticated;\n}\n\nexport interface SignInCustomerSucceededAction extends Action {\n type: CustomerActionType.SignInCustomerSucceeded;\n}\n\nexport interface SignInCustomerFailedAction extends Action {\n type: CustomerActionType.SignInCustomerFailed;\n}\n\nexport interface SignOutCustomerRequestedAction extends Action {\n type: CustomerActionType.SignOutCustomerRequested;\n}\n\nexport interface SignOutCustomerSucceededAction extends Action {\n type: CustomerActionType.SignOutCustomerSucceeded;\n}\n\nexport interface SignOutCustomerFailedAction extends Action {\n type: CustomerActionType.SignOutCustomerFailed;\n}\n\nexport interface CreateCustomerRequestedAction extends Action {\n type: CustomerActionType.CreateCustomerRequested;\n}\n\nexport interface CreateCustomerSucceededAction extends Action {\n type: CustomerActionType.CreateCustomerSucceeded;\n}\n\nexport interface CreateCustomerFailedAction extends Action {\n type: CustomerActionType.CreateCustomerFailed;\n}\n\nexport interface CreateCustomerAddressRequestedAction extends Action {\n type: CustomerActionType.CreateCustomerAddressRequested;\n}\n\nexport interface CreateCustomerAddressSucceededAction extends Action {\n type: CustomerActionType.CreateCustomerAddressSucceeded;\n}\n\nexport interface CreateCustomerAddressFailedAction extends Action {\n type: CustomerActionType.CreateCustomerAddressFailed;\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, from, Observable, of } from 'rxjs';\nimport { catchError, switchMap } from 'rxjs/operators';\n\nimport { CheckoutActionCreator, InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\nimport {\n isSpamProtectionExecuteSucceededAction,\n SpamProtectionActionCreator,\n} from '../spam-protection';\n\nimport CustomerAccountRequestBody, { CustomerAddressRequestBody } from './customer-account';\nimport {\n CreateCustomerAction,\n CreateCustomerAddressAction,\n CustomerActionType,\n SignInCustomerAction,\n SignOutCustomerAction,\n} from './customer-actions';\nimport CustomerCredentials from './customer-credentials';\nimport CustomerRequestSender from './customer-request-sender';\n\nexport default class CustomerActionCreator {\n constructor(\n private _customerRequestSender: CustomerRequestSender,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _spamProtectionActionCreator: SpamProtectionActionCreator,\n ) {}\n\n createCustomer(\n customerAccount: CustomerAccountRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const state = store.getState();\n const config = state.config.getStoreConfigOrThrow();\n const { isStorefrontSpamProtectionEnabled } = config.checkoutSettings;\n\n const createCustomer = (token?: string) =>\n from(\n this._customerRequestSender.createAccount(\n { ...customerAccount, token },\n options,\n ),\n ).pipe(\n switchMap(() =>\n concat(\n this._checkoutActionCreator.loadCurrentCheckout(options)(store),\n of(createAction(CustomerActionType.CreateCustomerSucceeded)),\n ),\n ),\n );\n\n return concat(\n of(createAction(CustomerActionType.CreateCustomerRequested)),\n isStorefrontSpamProtectionEnabled\n ? from(this._spamProtectionActionCreator.execute()(store)).pipe(\n switchMap((action) =>\n isSpamProtectionExecuteSucceededAction(action)\n ? concat(of(action), createCustomer(action.payload?.token))\n : of(action),\n ),\n )\n : createCustomer(),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CustomerActionType.CreateCustomerFailed, error),\n ),\n );\n };\n }\n\n createAddress(\n customerAddress: CustomerAddressRequestBody,\n options?: RequestOptions,\n ): Observable {\n return concat(\n of(createAction(CustomerActionType.CreateCustomerAddressRequested)),\n defer(async () => {\n const { body } = await this._customerRequestSender.createAddress(\n customerAddress,\n options,\n );\n\n return createAction(CustomerActionType.CreateCustomerAddressSucceeded, body);\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CustomerActionType.CreateCustomerAddressFailed, error),\n ),\n );\n }\n\n signInCustomer(\n credentials: CustomerCredentials,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(CustomerActionType.SignInCustomerRequested)),\n from(this._customerRequestSender.signInCustomer(credentials, options)).pipe(\n switchMap(({ body }) =>\n concat(\n this._checkoutActionCreator.loadCurrentCheckout(options)(store),\n of(createAction(CustomerActionType.SignInCustomerSucceeded, body.data)),\n ),\n ),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CustomerActionType.SignInCustomerFailed, error),\n ),\n );\n }\n\n signOutCustomer(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(CustomerActionType.SignOutCustomerRequested)),\n from(this._customerRequestSender.signOutCustomer(options)).pipe(\n switchMap(({ body }) =>\n concat(\n this._checkoutActionCreator.loadCurrentCheckout(options)(store),\n of(\n createAction(\n CustomerActionType.SignOutCustomerSucceeded,\n body.data,\n ),\n ),\n ),\n ),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CustomerActionType.SignOutCustomerFailed, error),\n ),\n );\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nimport Customer from './customer';\nimport { CustomerAccountInternalRequestBody, CustomerAddressRequestBody } from './customer-account';\nimport CustomerCredentials from './customer-credentials';\nimport { InternalCustomerResponseBody } from './internal-customer-responses';\n\nexport default class CustomerRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n createAccount(\n customerAccount: CustomerAccountInternalRequestBody,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = '/api/storefront/customer';\n\n return this._requestSender.post(url, {\n timeout,\n headers: SDK_VERSION_HEADERS,\n body: customerAccount,\n });\n }\n\n createAddress(\n customerAddress: CustomerAddressRequestBody,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/customer-address`;\n\n return this._requestSender.post(url, {\n timeout,\n headers: SDK_VERSION_HEADERS,\n body: customerAddress,\n });\n }\n\n signInCustomer(\n credentials: CustomerCredentials,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = '/internalapi/v1/checkout/customer';\n\n return this._requestSender.post(url, {\n timeout,\n headers: SDK_VERSION_HEADERS,\n body: credentials,\n });\n }\n\n signOutCustomer({ timeout }: RequestOptions = {}): Promise<\n Response\n > {\n const url = '/internalapi/v1/checkout/customer';\n\n return this._requestSender.delete(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nexport enum CustomerStrategyActionType {\n SignInFailed = 'CUSTOMER_STRATEGY_SIGN_IN_FAILED',\n SignInRequested = 'CUSTOMER_STRATEGY_SIGN_IN_REQUESTED',\n SignInSucceeded = 'CUSTOMER_STRATEGY_SIGN_IN_SUCCEEDED',\n SignOutFailed = 'CUSTOMER_STRATEGY_SIGN_OUT_FAILED',\n SignOutRequested = 'CUSTOMER_STRATEGY_SIGN_OUT_REQUESTED',\n SignOutSucceeded = 'CUSTOMER_STRATEGY_SIGN_OUT_SUCCEEDED',\n ExecutePaymentMethodCheckoutFailed = 'CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_FAILED',\n ExecutePaymentMethodCheckoutRequested = 'CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_REQUESTED',\n ExecutePaymentMethodCheckoutSucceeded = 'CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_SUCCEEDED',\n InitializeFailed = 'CUSTOMER_STRATEGY_INITIALIZE_FAILED',\n InitializeRequested = 'CUSTOMER_STRATEGY_INITIALIZE_REQUESTED',\n InitializeSucceeded = 'CUSTOMER_STRATEGY_INITIALIZE_SUCCEEDED',\n DeinitializeFailed = 'CUSTOMER_STRATEGY_DEINITIALIZE_FAILED',\n DeinitializeRequested = 'CUSTOMER_STRATEGY_DEINITIALIZE_REQUESTED',\n DeinitializeSucceeded = 'CUSTOMER_STRATEGY_DEINITIALIZE_SUCCEEDED',\n WidgetInteractionStarted = 'CUSTOMER_STRATEGY_WIDGET_INTERACTION_STARTED',\n WidgetInteractionFinished = 'CUSTOMER_STRATEGY_WIDGET_INTERACTION_FINISHED',\n WidgetInteractionFailed = 'CUSTOMER_STRATEGY_WIDGET_INTERACTION_FAILED',\n}\n\nexport type CustomerStrategyAction =\n | CustomerStrategySignInAction\n | CustomerStrategySignOutAction\n | CustomerStrategyExecutePaymentMethodCheckoutAction\n | CustomerStrategyInitializeAction\n | CustomerStrategyDeinitializeAction\n | CustomerStrategyWidgetAction;\n\nexport type CustomerStrategySignInAction =\n | SignInRequestedAction\n | SignInSucceededAction\n | SignInFailedAction;\n\nexport type CustomerStrategySignOutAction =\n | SignOutRequestedAction\n | SignOutSucceededAction\n | SignOutFailedAction;\n\nexport type CustomerStrategyExecutePaymentMethodCheckoutAction =\n | ExecutePaymentMethodCheckoutRequestedAction\n | ExecutePaymentMethodCheckoutSucceededAction\n | ExecutePaymentMethodCheckoutFailedAction;\n\nexport type CustomerStrategyInitializeAction =\n | InitializeRequestedAction\n | InitializeSucceededAction\n | InitializeFailedAction;\n\nexport type CustomerStrategyDeinitializeAction =\n | DeinitializeRequestedAction\n | DeinitializeSucceededAction\n | DeinitializeFailedAction;\n\nexport type CustomerStrategyWidgetAction =\n | WidgetInteractionStartedAction\n | WidgetInteractionFinishedAction\n | WidgetInteractionFailedAction;\n\nexport interface SignInRequestedAction extends Action {\n type: CustomerStrategyActionType.SignInRequested;\n}\n\nexport interface SignInSucceededAction extends Action {\n type: CustomerStrategyActionType.SignInSucceeded;\n}\n\nexport interface SignInFailedAction extends Action {\n type: CustomerStrategyActionType.SignInFailed;\n}\n\nexport interface SignOutRequestedAction extends Action {\n type: CustomerStrategyActionType.SignOutRequested;\n}\n\nexport interface SignOutSucceededAction extends Action {\n type: CustomerStrategyActionType.SignOutSucceeded;\n}\n\nexport interface SignOutFailedAction extends Action {\n type: CustomerStrategyActionType.SignOutFailed;\n}\n\nexport interface ExecutePaymentMethodCheckoutRequestedAction extends Action {\n type: CustomerStrategyActionType.ExecutePaymentMethodCheckoutRequested;\n}\n\nexport interface ExecutePaymentMethodCheckoutSucceededAction extends Action {\n type: CustomerStrategyActionType.ExecutePaymentMethodCheckoutSucceeded;\n}\n\nexport interface ExecutePaymentMethodCheckoutFailedAction extends Action {\n type: CustomerStrategyActionType.ExecutePaymentMethodCheckoutFailed;\n}\n\nexport interface InitializeRequestedAction extends Action {\n type: CustomerStrategyActionType.InitializeRequested;\n}\n\nexport interface InitializeSucceededAction extends Action {\n type: CustomerStrategyActionType.InitializeSucceeded;\n}\n\nexport interface InitializeFailedAction extends Action {\n type: CustomerStrategyActionType.InitializeFailed;\n}\n\nexport interface DeinitializeRequestedAction extends Action {\n type: CustomerStrategyActionType.DeinitializeRequested;\n}\n\nexport interface DeinitializeSucceededAction extends Action {\n type: CustomerStrategyActionType.DeinitializeSucceeded;\n}\n\nexport interface DeinitializeFailedAction extends Action {\n type: CustomerStrategyActionType.DeinitializeFailed;\n}\n\nexport interface WidgetInteractionStartedAction extends Action {\n type: CustomerStrategyActionType.WidgetInteractionStarted;\n}\n\nexport interface WidgetInteractionFinishedAction extends Action {\n type: CustomerStrategyActionType.WidgetInteractionFinished;\n}\n\nexport interface WidgetInteractionFailedAction extends Action {\n type: CustomerStrategyActionType.WidgetInteractionFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { CustomerStrategy as CustomerStrategyV2 } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { Registry } from '../common/registry';\n\nimport CustomerCredentials from './customer-credentials';\nimport {\n CustomerInitializeOptions,\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from './customer-request-options';\nimport {\n CustomerStrategyActionType,\n CustomerStrategyDeinitializeAction,\n CustomerStrategyExecutePaymentMethodCheckoutAction,\n CustomerStrategyInitializeAction,\n CustomerStrategySignInAction,\n CustomerStrategySignOutAction,\n CustomerStrategyWidgetAction,\n} from './customer-strategy-actions';\nimport CustomerStrategyRegistryV2 from './customer-strategy-registry-v2';\nimport { CustomerStrategy } from './strategies';\n\nexport default class CustomerStrategyActionCreator {\n constructor(\n private _strategyRegistry: Registry,\n private _strategyRegistryV2: CustomerStrategyRegistryV2,\n ) {}\n\n signIn(\n credentials: CustomerCredentials,\n options?: CustomerRequestOptions,\n ): Observable {\n return Observable.create((observer: Observer) => {\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n observer.next(\n createAction(CustomerStrategyActionType.SignInRequested, undefined, meta),\n );\n\n const promise: Promise = this._getStrategy(\n methodId,\n ).signIn(credentials, options);\n\n promise\n .then(() => {\n observer.next(\n createAction(CustomerStrategyActionType.SignInSucceeded, undefined, meta),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(CustomerStrategyActionType.SignInFailed, error, meta),\n );\n });\n });\n }\n\n signOut(options?: CustomerRequestOptions): Observable {\n return Observable.create((observer: Observer) => {\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n observer.next(\n createAction(CustomerStrategyActionType.SignOutRequested, undefined, meta),\n );\n\n const promise: Promise =\n this._getStrategy(methodId).signOut(options);\n\n promise\n .then(() => {\n observer.next(\n createAction(CustomerStrategyActionType.SignOutSucceeded, undefined, meta),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(CustomerStrategyActionType.SignOutFailed, error, meta),\n );\n });\n });\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Observable {\n return Observable.create(\n (observer: Observer) => {\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n observer.next(\n createAction(\n CustomerStrategyActionType.ExecutePaymentMethodCheckoutRequested,\n undefined,\n meta,\n ),\n );\n\n const promise: Promise =\n this._getStrategy(methodId).executePaymentMethodCheckout(options);\n\n promise\n .then(() => {\n observer.next(\n createAction(\n CustomerStrategyActionType.ExecutePaymentMethodCheckoutSucceeded,\n undefined,\n meta,\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n CustomerStrategyActionType.ExecutePaymentMethodCheckoutFailed,\n error,\n meta,\n ),\n );\n });\n },\n );\n }\n\n initialize(\n options?: CustomerInitializeOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n if (methodId && state.customerStrategies.isInitialized(methodId)) {\n return observer.complete();\n }\n\n observer.next(\n createAction(CustomerStrategyActionType.InitializeRequested, undefined, meta),\n );\n\n const promise: Promise =\n this._getStrategy(methodId).initialize(options);\n\n promise\n .then(() => {\n observer.next(\n createAction(\n CustomerStrategyActionType.InitializeSucceeded,\n undefined,\n meta,\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n CustomerStrategyActionType.InitializeFailed,\n error,\n meta,\n ),\n );\n });\n });\n }\n\n deinitialize(\n options?: CustomerRequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n if (methodId && !state.customerStrategies.isInitialized(methodId)) {\n return observer.complete();\n }\n\n observer.next(\n createAction(CustomerStrategyActionType.DeinitializeRequested, undefined, meta),\n );\n\n const promise: Promise =\n this._getStrategy(methodId).deinitialize(options);\n\n promise\n .then(() => {\n observer.next(\n createAction(\n CustomerStrategyActionType.DeinitializeSucceeded,\n undefined,\n meta,\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n CustomerStrategyActionType.DeinitializeFailed,\n error,\n meta,\n ),\n );\n });\n });\n }\n\n widgetInteraction(\n method: () => Promise,\n options?: CustomerRequestOptions,\n ): Observable {\n return Observable.create((observer: Observer) => {\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n observer.next(\n createAction(CustomerStrategyActionType.WidgetInteractionStarted, undefined, meta),\n );\n\n method()\n .then(() => {\n observer.next(\n createAction(\n CustomerStrategyActionType.WidgetInteractionFinished,\n undefined,\n meta,\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n CustomerStrategyActionType.WidgetInteractionFailed,\n error,\n meta,\n ),\n );\n });\n });\n }\n\n private _getStrategy(methodId?: string): CustomerStrategy | CustomerStrategyV2 {\n let strategy: CustomerStrategy | CustomerStrategyV2;\n\n try {\n strategy = this._strategyRegistryV2.get({ id: methodId || '' });\n } catch {\n strategy = this._strategyRegistry.get(methodId);\n }\n\n return strategy;\n }\n}\n","import joinIncludes from './join-includes';\nimport mergeIncludes from './merge-includes';\n\n/**\n * Joins or merges a base list of includes with a set of additional includes.\n */\nexport default function joinOrMergeIncludes(\n baseIncludes: T[],\n includeDictionaryOrList: { [key in T]?: boolean } | T[] = [],\n): string {\n return Array.isArray(includeDictionaryOrList)\n ? joinIncludes([...baseIncludes, ...includeDictionaryOrList])\n : mergeIncludes(baseIncludes, includeDictionaryOrList);\n}\n","import { difference, filter, keys, pickBy } from 'lodash';\n\nimport joinIncludes from './join-includes';\n\n/**\n * Merges includes given a list of base includes and a dictionary\n * of includes\n */\nexport default function mergeIncludes(\n baseIncludes: T[],\n includesDictionary?: { [key in T]?: boolean },\n): string {\n const deletions = keys(pickBy(includesDictionary, (on) => !on));\n const additions = keys(filter(includesDictionary));\n\n return joinIncludes([...difference(baseIncludes, deletions), ...additions]);\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n joinOrMergeIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport Checkout, { CheckoutRequestBody } from './checkout';\nimport CHECKOUT_DEFAULT_INCLUDES from './checkout-default-includes';\nimport CheckoutParams from './checkout-params';\nimport { CheckoutNotAvailableError } from './errors';\n\nexport default class CheckoutRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n loadCheckout(\n id: string,\n { params: { include } = {}, timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkout/${id}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender\n .get(url, {\n params: {\n include: joinOrMergeIncludes(CHECKOUT_DEFAULT_INCLUDES, include),\n },\n headers,\n timeout,\n })\n .catch((error) => {\n if (error.status >= 400 && error.status < 500) {\n throw new CheckoutNotAvailableError(error);\n }\n\n throw error;\n });\n }\n\n updateCheckout(\n id: string,\n body: CheckoutRequestBody,\n { params: { include } = {}, timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkout/${id}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.put(url, {\n params: {\n include: joinOrMergeIncludes(CHECKOUT_DEFAULT_INCLUDES, include),\n },\n body,\n headers,\n timeout,\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { LoadConfigAction } from '../config';\nimport { LoadFormFieldsAction } from '../form';\n\nimport Checkout from './checkout';\n\nexport enum CheckoutActionType {\n LoadCheckoutRequested = 'LOAD_CHECKOUT_REQUESTED',\n LoadCheckoutSucceeded = 'LOAD_CHECKOUT_SUCCEEDED',\n LoadCheckoutFailed = 'LOAD_CHECKOUT_FAILED',\n\n UpdateCheckoutRequested = 'UPDATE_CHECKOUT_REQUESTED',\n UpdateCheckoutSucceeded = 'UPDATE_CHECKOUT_SUCCEEDED',\n UpdateCheckoutFailed = 'UPDATE_CHECKOUT_FAILED',\n}\n\nexport type CheckoutAction = LoadCheckoutAction | UpdateCheckoutAction;\n\nexport type LoadCheckoutAction =\n | LoadCheckoutRequestedAction\n | LoadCheckoutSucceededAction\n | LoadCheckoutFailedAction\n | LoadFormFieldsAction\n | LoadConfigAction;\n\nexport type UpdateCheckoutAction =\n | UpdateCheckoutRequestedAction\n | UpdateCheckoutSucceededAction\n | UpdateCheckoutFailedAction;\n\nexport interface LoadCheckoutRequestedAction extends Action {\n type: CheckoutActionType.LoadCheckoutRequested;\n}\n\nexport interface LoadCheckoutSucceededAction extends Action {\n type: CheckoutActionType.LoadCheckoutSucceeded;\n}\n\nexport interface LoadCheckoutFailedAction extends Action {\n type: CheckoutActionType.LoadCheckoutFailed;\n}\n\nexport interface UpdateCheckoutRequestedAction extends Action {\n type: CheckoutActionType.UpdateCheckoutRequested;\n}\n\nexport interface UpdateCheckoutSucceededAction extends Action {\n type: CheckoutActionType.UpdateCheckoutSucceeded;\n}\n\nexport interface UpdateCheckoutFailedAction extends Action {\n type: CheckoutActionType.UpdateCheckoutFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, merge, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\nimport { ConfigActionCreator } from '../config';\nimport { FormFieldsActionCreator } from '../form';\n\nimport { CheckoutRequestBody } from './checkout';\nimport { CheckoutActionType, LoadCheckoutAction, UpdateCheckoutAction } from './checkout-actions';\nimport CheckoutRequestSender from './checkout-request-sender';\nimport InternalCheckoutSelectors from './internal-checkout-selectors';\n\nexport default class CheckoutActionCreator {\n constructor(\n private _checkoutRequestSender: CheckoutRequestSender,\n private _configActionCreator: ConfigActionCreator,\n private _formFieldsActionCreator: FormFieldsActionCreator,\n ) {}\n\n loadCheckout(id: string, options?: RequestOptions): Observable {\n return concat(\n of(createAction(CheckoutActionType.LoadCheckoutRequested)),\n merge(\n this._configActionCreator.loadConfig({\n ...options,\n useCache: true,\n params: { ...options?.params, checkoutId: id },\n }),\n this._formFieldsActionCreator.loadFormFields({ ...options, useCache: true }),\n defer(() =>\n this._checkoutRequestSender\n .loadCheckout(id, options)\n .then(({ body }) =>\n createAction(CheckoutActionType.LoadCheckoutSucceeded, body),\n ),\n ),\n ),\n ).pipe(\n catchError((error) => throwErrorAction(CheckoutActionType.LoadCheckoutFailed, error)),\n );\n }\n\n loadDefaultCheckout(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(CheckoutActionType.LoadCheckoutRequested)),\n merge(\n this._configActionCreator.loadConfig(),\n this._formFieldsActionCreator.loadFormFields({ ...options, useCache: true }),\n ),\n defer(async () => {\n const state = store.getState();\n const context = state.config.getContextConfig();\n\n if (!context || !context.checkoutId) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const { body } = await this._checkoutRequestSender.loadCheckout(\n context.checkoutId,\n options,\n );\n\n return createAction(CheckoutActionType.LoadCheckoutSucceeded, body);\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CheckoutActionType.LoadCheckoutFailed, error),\n ),\n );\n }\n\n updateCheckout(\n body: CheckoutRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n new Observable((observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(createAction(CheckoutActionType.UpdateCheckoutRequested));\n\n this._checkoutRequestSender\n .updateCheckout(checkout.id, body, options)\n .then(({ body }) => {\n observer.next(\n createAction(CheckoutActionType.UpdateCheckoutSucceeded, body),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(CheckoutActionType.UpdateCheckoutFailed, response),\n );\n });\n });\n }\n\n loadCurrentCheckout(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n return this.loadCheckout(checkout.id, options);\n };\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { FormFields } from './form-field';\n\nexport enum FormFieldsActionType {\n LoadFormFieldsRequested = 'LOAD_FORM_FIELDS_REQUESTED',\n LoadFormFieldsSucceeded = 'LOAD_FORM_FIELDS_SUCCEEDED',\n LoadFormFieldsFailed = 'LOAD_FORM_FIELDS_FAILED',\n}\n\nexport type LoadFormFieldsAction =\n | LoadFormFieldsRequestedAction\n | LoadFormFieldsSucceededAction\n | LoadFormFieldsFailedAction;\n\nexport interface LoadFormFieldsRequestedAction extends Action {\n type: FormFieldsActionType.LoadFormFieldsRequested;\n}\n\nexport interface LoadFormFieldsSucceededAction extends Action {\n type: FormFieldsActionType.LoadFormFieldsSucceeded;\n}\n\nexport interface LoadFormFieldsFailedAction extends Action {\n type: FormFieldsActionType.LoadFormFieldsFailed;\n}\n","import { createAction } from '@bigcommerce/data-store';\nimport { concat, defer, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { ActionOptions, cachableAction } from '../common/data-store';\nimport { throwErrorAction } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\n\nimport { FormFieldsActionType, LoadFormFieldsAction } from './form-fields-actions';\nimport FormFieldsRequestSender from './form-fields-request-sender';\n\nexport default class FormFieldsActionCreator {\n constructor(private _formFieldsRequestSender: FormFieldsRequestSender) {}\n\n @cachableAction\n loadFormFields(options?: RequestOptions & ActionOptions): Observable {\n return concat(\n of(createAction(FormFieldsActionType.LoadFormFieldsRequested)),\n defer(async () => {\n const { body } = await this._formFieldsRequestSender.loadFields(options);\n\n return createAction(FormFieldsActionType.LoadFormFieldsSucceeded, body);\n }),\n ).pipe(\n catchError((response) =>\n throwErrorAction(FormFieldsActionType.LoadFormFieldsFailed, response),\n ),\n );\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport { FormFields } from './form-field';\n\nexport default class FormFieldsRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n loadFields({ timeout }: RequestOptions = {}): Promise> {\n const url = '/api/storefront/form-fields';\n\n return this._requestSender.get(url, {\n timeout,\n headers: {\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport PaymentMethod from './payment-method';\nimport PaymentMethodMeta from './payment-method-meta';\n\nexport enum PaymentMethodActionType {\n LoadPaymentMethodRequested = 'LOAD_PAYMENT_METHOD_REQUESTED',\n LoadPaymentMethodSucceeded = 'LOAD_PAYMENT_METHOD_SUCCEEDED',\n LoadPaymentMethodFailed = 'LOAD_PAYMENT_METHOD_FAILED',\n\n LoadPaymentMethodsRequested = 'LOAD_PAYMENT_METHODS_REQUESTED',\n LoadPaymentMethodsSucceeded = 'LOAD_PAYMENT_METHODS_SUCCEEDED',\n LoadPaymentMethodsFailed = 'LOAD_PAYMENT_METHODS_FAILED',\n}\n\nexport type PaymentMethodAction = LoadPaymentMethodAction | LoadPaymentMethodsAction;\n\nexport type LoadPaymentMethodAction =\n | LoadPaymentMethodRequestedAction\n | LoadPaymentMethodSucceededAction\n | LoadPaymentMethodFailedAction;\n\nexport type LoadPaymentMethodsAction =\n | LoadPaymentMethodsRequestedAction\n | LoadPaymentMethodsSucceededAction\n | LoadPaymentMethodsFailedAction;\n\nexport interface LoadPaymentMethodRequestedAction extends Action {\n type: PaymentMethodActionType.LoadPaymentMethodRequested;\n}\n\nexport interface LoadPaymentMethodSucceededAction extends Action {\n type: PaymentMethodActionType.LoadPaymentMethodSucceeded;\n}\n\nexport interface LoadPaymentMethodFailedAction extends Action {\n type: PaymentMethodActionType.LoadPaymentMethodFailed;\n}\n\nexport interface LoadPaymentMethodsRequestedAction extends Action {\n type: PaymentMethodActionType.LoadPaymentMethodsRequested;\n}\n\nexport interface LoadPaymentMethodsSucceededAction\n extends Action {\n type: PaymentMethodActionType.LoadPaymentMethodsSucceeded;\n}\n\nexport interface LoadPaymentMethodsFailedAction extends Action {\n type: PaymentMethodActionType.LoadPaymentMethodsFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { filter } from 'lodash';\nimport { Observable, Observer } from 'rxjs';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { ActionOptions, cachableAction } from '../common/data-store';\nimport { RequestOptions } from '../common/http-request';\n\nimport {\n LoadPaymentMethodAction,\n LoadPaymentMethodsAction,\n PaymentMethodActionType,\n} from './payment-method-actions';\nimport PaymentMethodRequestSender from './payment-method-request-sender';\nimport { isApplePayWindow } from './strategies/apple-pay';\n\nimport { PaymentMethod } from '.';\n\nconst APPLEPAYID = 'applepay';\n\nexport default class PaymentMethodActionCreator {\n constructor(private _requestSender: PaymentMethodRequestSender) {}\n\n loadPaymentMethods(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const cart = state.cart.getCartOrThrow();\n\n observer.next(createAction(PaymentMethodActionType.LoadPaymentMethodsRequested));\n\n this._requestSender\n .loadPaymentMethods({\n ...options,\n params: { ...options?.params, cartId: cart.id },\n })\n .then((response) => {\n const meta = {\n deviceSessionId: response.headers['x-device-session-id'],\n sessionHash: response.headers['x-session-hash'],\n };\n const methods = response.body;\n const filteredMethods = Array.isArray(methods)\n ? this._filterApplePay(methods)\n : methods;\n\n observer.next(\n createAction(\n PaymentMethodActionType.LoadPaymentMethodsSucceeded,\n filteredMethods,\n meta,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n PaymentMethodActionType.LoadPaymentMethodsFailed,\n response,\n ),\n );\n });\n });\n }\n\n @cachableAction\n loadPaymentMethod(\n methodId: string,\n options?: RequestOptions & ActionOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const cartId = state.cart.getCart()?.id;\n const params = cartId ? { ...options?.params, cartId } : { ...options?.params };\n\n observer.next(\n createAction(PaymentMethodActionType.LoadPaymentMethodRequested, undefined, {\n methodId,\n }),\n );\n\n this._requestSender\n .loadPaymentMethod(methodId, { ...options, params })\n .then((response) => {\n observer.next(\n createAction(\n PaymentMethodActionType.LoadPaymentMethodSucceeded,\n response.body,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n PaymentMethodActionType.LoadPaymentMethodFailed,\n response,\n { methodId },\n ),\n );\n });\n });\n }\n\n private _filterApplePay(methods: PaymentMethod[]): PaymentMethod[] {\n return filter(methods, (method) => {\n if (method.id === APPLEPAYID && !isApplePayWindow(window)) {\n return false;\n }\n\n return true;\n });\n }\n}\n","export interface ApplePayWindow extends Window {\n ApplePaySession: ApplePaySession;\n}\n\nexport default function isApplePayWindow(window: Window): window is ApplePayWindow {\n return 'ApplePaySession' in window;\n}\n\nexport function assertApplePayWindow(window: Window): asserts window is ApplePayWindow {\n if (!isApplePayWindow(window)) {\n throw new Error('Apple pay is not supported');\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport PaymentMethod from './payment-method';\n\nexport default class PaymentMethodRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n loadPaymentMethods({ timeout, params }: RequestOptions = {}): Promise<\n Response\n > {\n const url = '/api/storefront/payments';\n\n return this._requestSender.get(url, {\n timeout,\n headers: {\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n params,\n });\n }\n\n loadPaymentMethod(\n methodId: string,\n { timeout, params }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/payments/${methodId}`;\n\n return this._requestSender.get(url, {\n timeout,\n headers: {\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n params,\n });\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { BuyNowCartRequestBody, Cart } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ContentType, RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nexport default class CartRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n createBuyNowCart(\n body: BuyNowCartRequestBody,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = '/api/storefront/carts';\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, { body, headers, timeout });\n }\n}\n","import { isEqual } from 'lodash';\n\nimport { PartialDeep } from '../common/types';\n\nimport Cart from './cart';\n\nexport default class CartComparator {\n isEqual(cartA: Cart, cartB: Cart): boolean {\n return isEqual(this._normalize(cartA), this._normalize(cartB));\n }\n\n private _normalize(cart: Cart): PartialDeep {\n return {\n cartAmount: cart.cartAmount,\n currency: cart.currency,\n id: cart.id,\n lineItems: {\n digitalItems: cart.lineItems.digitalItems\n .slice()\n .sort((itemA, itemB) =>\n `${itemA.productId}${itemA.variantId}`.localeCompare(\n `${itemB.productId}${itemB.variantId}`,\n ),\n )\n .map((item) => ({\n extendedSalePrice: item.extendedSalePrice,\n productId: item.productId,\n quantity: item.quantity,\n variantId: item.variantId,\n })),\n giftCertificates: cart.lineItems.giftCertificates\n .slice()\n .sort((itemA, itemB) => `${itemA.id}`.localeCompare(`${itemB.id}`))\n .map((item) => ({\n amount: item.amount,\n recipient: item.recipient,\n })),\n physicalItems: cart.lineItems.physicalItems\n .slice()\n .sort((itemA, itemB) =>\n `${itemA.productId}${itemA.variantId}`.localeCompare(\n `${itemB.productId}${itemB.variantId}`,\n ),\n )\n .map((item) => ({\n extendedSalePrice: item.extendedSalePrice,\n productId: item.productId,\n quantity: item.quantity,\n variantId: item.variantId,\n giftWrapping: item.giftWrapping,\n })),\n },\n };\n }\n}\n","import { ComparableCheckout } from '../../checkout';\nimport { StandardError } from '../../common/error/errors';\n\nexport default class CartChangedError extends StandardError {\n /**\n * @alpha\n * Please note that this option is currently in an early stage of\n * development. Therefore the API is unstable and not ready for public\n * consumption.\n */\n data: { previous: ComparableCheckout; updated: ComparableCheckout };\n\n constructor(previous: ComparableCheckout, updated: ComparableCheckout) {\n super(\n 'An update to your shopping cart has been detected and your available shipping costs have been updated.',\n );\n\n this.name = 'CartChangedError';\n this.type = 'cart_changed';\n this.data = {\n previous,\n updated,\n };\n }\n}\n","import { isEqual, map } from 'lodash';\n\nimport { Cart, CartComparator } from '../cart';\nimport { CartChangedError } from '../cart/errors';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\nimport { Coupon, GiftCertificate } from '../coupon';\n\nimport Checkout from './checkout';\nimport CheckoutRequestSender from './checkout-request-sender';\n\nexport type ComparableCheckout = Pick<\n Checkout,\n 'outstandingBalance' | 'coupons' | 'giftCertificates'\n> & {\n cart: Partial;\n};\n\nexport default class CheckoutValidator {\n constructor(private _checkoutRequestSender: CheckoutRequestSender) {}\n\n validate(checkout?: Checkout, options?: RequestOptions): Promise {\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n return this._checkoutRequestSender.loadCheckout(checkout.id, options).then((response) => {\n const comparator = new CartComparator();\n\n if (\n checkout.outstandingBalance === response.body.outstandingBalance &&\n this._compareCoupons(checkout.coupons, response.body.coupons) &&\n this._compareGiftCertificates(\n checkout.giftCertificates,\n response.body.giftCertificates,\n ) &&\n comparator.isEqual(checkout.cart, response.body.cart)\n ) {\n return;\n }\n\n throw new CartChangedError(\n this._getComparableCheckout(checkout),\n this._getComparableCheckout(response.body),\n );\n });\n }\n\n private _compareCoupons(couponsA: Coupon[], couponsB: Coupon[]): boolean {\n return isEqual(map(couponsA, 'code'), map(couponsB, 'code'));\n }\n\n private _compareGiftCertificates(\n giftCertificatesA: GiftCertificate[],\n giftCertificatesB: GiftCertificate[],\n ): boolean {\n return isEqual(map(giftCertificatesA, 'code'), map(giftCertificatesB, 'code'));\n }\n\n private _getComparableCheckout(checkout: Checkout): ComparableCheckout {\n const { cart, coupons, giftCertificates, outstandingBalance } = checkout;\n\n return {\n cart: {\n cartAmount: cart.cartAmount,\n currency: cart.currency,\n lineItems: cart.lineItems,\n },\n coupons,\n giftCertificates,\n outstandingBalance,\n };\n }\n}\n","export default class CancellablePromise {\n promise: Promise;\n cancel!: (reason?: any) => void;\n\n constructor(promise: Promise) {\n const cancellable = new Promise((_, reject) => {\n this.cancel = reject;\n });\n\n this.promise = Promise.race([promise, cancellable]);\n }\n}\n","import { StandardError } from '../../error/errors';\n\nexport default class UnexpectedDetachmentError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Unable to proceed because the required element is unexpectedly detached from the page.',\n );\n\n this.name = 'UnexpectedDetachmentError';\n this.type = 'unexpected_detachment';\n }\n}\n","import { CancellablePromise } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { UnexpectedDetachmentError } from './errors';\nimport { MutationObserverFactory } from './mutation-observer';\n\nexport default class DetachmentObserver {\n constructor(private _mutationObserver: MutationObserverFactory) {}\n\n async ensurePresence(targets: Node[], promise: Promise): Promise {\n const cancellable = new CancellablePromise(promise);\n\n const observer = this._mutationObserver.create((mutationsList) => {\n mutationsList.forEach((mutation) => {\n const removedTargets = Array.from(mutation.removedNodes).filter((node) =>\n targets.some((target) => node === target || node.contains(target)),\n );\n\n if (removedTargets.length === 0) {\n return;\n }\n\n cancellable.cancel(new UnexpectedDetachmentError());\n });\n });\n\n observer.observe(document.body, { childList: true, subtree: true });\n\n try {\n const output = await cancellable.promise;\n\n observer.disconnect();\n\n return output;\n } catch (error) {\n observer.disconnect();\n\n throw error;\n }\n }\n}\n","export interface MutationObeserverCreator {\n prototype: MutationObserver;\n new (callback: MutationCallback): MutationObserver;\n}\n\nexport interface MutationObserverWindow extends Window {\n MutationObserver: MutationObeserverCreator;\n}\n\nexport class MutationObserverFactory {\n constructor(private _window: MutationObserverWindow = window as MutationObserverWindow) {}\n\n create(callback: MutationCallback): MutationObserver {\n return new this._window.MutationObserver(callback);\n }\n}\n","import { InvalidArgumentError } from '../error/errors';\n\nimport Url from './url';\n\nexport default function parseUrl(url: string): Url {\n if (!/^(https?:)?\\/\\//.test(url)) {\n throw new InvalidArgumentError('The provided URL must be absolute.');\n }\n\n // new URL() is not supported in IE11, use anchor tag instead\n const anchor = document.createElement('a');\n\n anchor.href = url;\n\n // IE11 returns 80 or 443 for the port number depending on the URL scheme,\n // even if the port number is not specified in the URL.\n const port =\n anchor.port && url.indexOf(`${anchor.hostname}:${anchor.port}`) !== -1 ? anchor.port : '';\n\n return {\n hash: anchor.hash,\n hostname: anchor.hostname,\n href: anchor.href,\n origin: `${anchor.protocol}//${anchor.hostname}${port ? `:${port}` : ''}`,\n pathname: anchor.pathname,\n port,\n protocol: anchor.protocol,\n search: anchor.search,\n };\n}\n","import IframeEvent from './iframe-event';\n\nexport default function isIframeEvent, TType extends string>(\n object: any,\n type: TType,\n): object is TEvent {\n return object.type === type;\n}\n","import { fromEvent } from 'rxjs';\nimport { filter, map, take } from 'rxjs/operators';\n\nimport { parseUrl } from '../url';\n\nimport IframeEvent from './iframe-event';\nimport isIframeEvent from './is-iframe-event';\n\nexport interface IframeEventPostOptions<\n TSuccessEvent extends IframeEvent,\n TErrorEvent extends IframeEvent,\n> {\n errorType?: TErrorEvent['type'];\n successType?: TSuccessEvent['type'];\n}\n\nexport default class IframeEventPoster {\n private _targetOrigin: string;\n\n constructor(targetOrigin: string, private _targetWindow?: Window) {\n this._targetOrigin = targetOrigin === '*' ? '*' : parseUrl(targetOrigin).origin;\n }\n\n post(event: TEvent): void;\n post<\n TSuccessEvent extends IframeEvent = IframeEvent,\n TErrorEvent extends IframeEvent = IframeEvent,\n >(\n event: TEvent,\n options: IframeEventPostOptions,\n ): Promise;\n post<\n TSuccessEvent extends IframeEvent = IframeEvent,\n TErrorEvent extends IframeEvent = IframeEvent,\n >(\n event: TEvent,\n options?: IframeEventPostOptions,\n ): Promise | void {\n const targetWindow = this._targetWindow;\n\n if (window === targetWindow) {\n return;\n }\n\n if (!targetWindow) {\n throw new Error('Unable to post message because target window is not set.');\n }\n\n const result =\n options &&\n fromEvent(window, 'message')\n .pipe(\n filter(\n (event) =>\n event.origin === this._targetOrigin &&\n isIframeEvent(event.data, event.data.type) &&\n [options.successType, options.errorType].indexOf(event.data.type) !==\n -1,\n ),\n map((event) => {\n if (options.errorType === event.data.type) {\n throw event.data;\n }\n\n return event.data;\n }),\n take(1),\n )\n .toPromise();\n\n targetWindow.postMessage(event, this._targetOrigin);\n\n return result;\n }\n\n setTarget(window: Window) {\n this._targetWindow = window;\n }\n}\n","/**\n * Decorates a class or a method by binding all its prototype methods or itself\n * to the calling instance respectively.\n */\nfunction bindDecorator(\n target: object,\n key: string,\n descriptor: TypedPropertyDescriptor,\n): TypedPropertyDescriptor;\nfunction bindDecorator>(target: T): T;\n\nfunction bindDecorator(target: any, key?: any, descriptor?: any): any {\n if (!key || !descriptor) {\n return bindClassDecorator(target);\n }\n\n return bindMethodDecorator(target, key, descriptor);\n}\n\nexport default bindDecorator;\n\n/**\n * Decorates a class by binding all its prototype methods to the calling\n * instance.\n */\nexport function bindClassDecorator>(target: T): T {\n const decoratedTarget = class extends target {};\n\n Object.getOwnPropertyNames(target.prototype).forEach((key) => {\n const descriptor = Object.getOwnPropertyDescriptor(target.prototype, key);\n\n if (!descriptor || key === 'constructor') {\n return;\n }\n\n Object.defineProperty(\n decoratedTarget.prototype,\n key,\n bindMethodDecorator(target.prototype, key, descriptor),\n );\n });\n\n return decoratedTarget;\n}\n\n/**\n * Decorates a method by binding it to the calling instance.\n */\nexport function bindMethodDecorator(\n _: object,\n key: string,\n descriptor: TypedPropertyDescriptor,\n): TypedPropertyDescriptor {\n if (typeof descriptor.value !== 'function') {\n return descriptor;\n }\n\n let method: T = descriptor.value;\n\n return {\n get() {\n const boundMethod = method.bind(this) as T;\n\n Object.defineProperty(this, key, {\n ...descriptor,\n value: boundMethod,\n });\n\n return boundMethod;\n },\n set(value) {\n method = value;\n },\n };\n}\n\nexport type Constructor = new (...args: any[]) => T;\nexport type Method = (...args: any[]) => any;\n","import { appendWww, parseUrl } from '../url';\nimport { bindDecorator as bind } from '../utility';\n\nimport { IframeEventMap } from './iframe-event';\nimport isIframeEvent from './is-iframe-event';\n\nexport default class IframeEventListener> {\n private _isListening: boolean;\n private _listeners: EventListeners;\n private _sourceOrigins: string[];\n\n constructor(sourceOrigin: string) {\n this._sourceOrigins = [\n parseUrl(sourceOrigin).origin,\n appendWww(parseUrl(sourceOrigin)).origin,\n ];\n this._isListening = false;\n this._listeners = {};\n }\n\n listen(): void {\n if (this._isListening) {\n return;\n }\n\n this._isListening = true;\n\n window.addEventListener('message', this._handleMessage);\n }\n\n stopListen(): void {\n if (!this._isListening) {\n return;\n }\n\n this._isListening = false;\n\n window.removeEventListener('message', this._handleMessage);\n }\n\n addListener(\n type: TType,\n listener: (event: TEventMap[TType]) => void,\n ): void {\n let listeners = this._listeners[type];\n\n if (!listeners) {\n this._listeners[type] = listeners = [];\n }\n\n if (listeners.indexOf(listener) === -1) {\n listeners.push(listener);\n }\n }\n\n removeListener(\n type: TType,\n listener: (event: TEventMap[TType]) => void,\n ): void {\n const listeners = this._listeners[type];\n\n if (!listeners) {\n return;\n }\n\n const index = listeners.indexOf(listener);\n\n if (index >= 0) {\n listeners.splice(index, 1);\n }\n }\n\n trigger(event: TEventMap[TType]): void {\n const listeners = this._listeners[event.type];\n\n if (!listeners) {\n return;\n }\n\n listeners.forEach((listener) => listener(event));\n }\n\n @bind\n private _handleMessage(event: MessageEvent): void {\n if (\n this._sourceOrigins.indexOf(event.origin) === -1 ||\n !isIframeEvent(event.data as TEventMap[keyof TEventMap], event.data.type)\n ) {\n return;\n }\n\n this.trigger(event.data);\n }\n}\n\ntype EventListeners = {\n [key in keyof TEventMap]?: Array<(event: TEventMap[key]) => void>;\n};\n","import parseUrl from './parse-url';\nimport Url from './url';\n\nexport default function appendWww(url: Url): Url {\n return parseUrl(\n url.hostname.indexOf('www') === 0\n ? url.href\n : url.href.replace(url.hostname, `www.${url.hostname}`),\n );\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if the shopper chooses not to complete the spam protection\n * challenge (i.e.: they close the reCaptcha window).\n */\nexport default class SpamProtectionChallengeNotCompletedError extends StandardError {\n constructor() {\n super(\"You haven't complete our spam protection challenge. Please try again.\");\n\n this.name = 'SpamProtectionChallengeNotCompletedError';\n this.type = 'spam_protection_challenge_not_completed';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if the shopper chooses not to complete the spam protection\n * challenge (i.e.: they close the reCaptcha window).\n */\nexport default class CardingProtectionChallengeNotCompletedError extends StandardError {\n constructor() {\n super('Please complete our human verification challenge and try again.');\n\n this.name = 'CardingProtectionChallengeNotCompletedError';\n this.type = 'carding_protection_challenge_not_completed';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if we fail to complete the required spam protection\n * verification due to an unknown reason.\n */\nexport default class CardingProtectionFailedError extends StandardError {\n constructor() {\n super('We were not able to verify that you are not a robot. Please try again.');\n\n this.name = 'CardingProtectionFailedError';\n this.type = 'carding_protection_failed';\n }\n}\n","import { switchMap, take } from 'rxjs/operators';\n\nimport { RequestError } from '../common/error/errors';\nimport { PaymentAdditionalAction } from '../payment';\n\nimport {\n CardingProtectionChallengeNotCompletedError,\n CardingProtectionFailedError,\n SpamProtectionChallengeNotCompletedError,\n} from './errors';\nimport GoogleRecaptcha from './google-recaptcha';\n\nexport default class PaymentHumanVerificationHandler {\n constructor(private _googleRecaptcha: GoogleRecaptcha) {}\n\n handle(error: Error): Promise;\n handle(id: string, key: string): Promise;\n async handle(errorOrId: Error | string, key?: string): Promise {\n if (typeof errorOrId === 'string') {\n return this.handleWithRecaptchaSitekey(errorOrId, key);\n }\n\n return this.handleWithPaymentHumanVerificationRequestError(errorOrId);\n }\n\n private async handleWithPaymentHumanVerificationRequestError(\n error: Error,\n ): Promise {\n if (!this._isPaymentHumanVerificationRequest(error)) {\n throw error;\n }\n\n await this._initialize(error.body.additional_action_required.data.key);\n\n return this._performRecaptcha();\n }\n\n private async handleWithRecaptchaSitekey(\n id: string,\n key?: string,\n ): Promise {\n if (id !== 'recaptcha_v2') {\n throw Error('Human verification method is not supported.');\n }\n\n if (!key) {\n throw Error('Recaptcha site key is missing.');\n }\n\n await this._initialize(key);\n\n return this._performRecaptcha();\n }\n\n private _performRecaptcha(): Promise {\n return this._googleRecaptcha\n .execute()\n .pipe(take(1))\n .pipe(\n switchMap(async ({ error, token }) => {\n if (error instanceof SpamProtectionChallengeNotCompletedError) {\n throw new CardingProtectionChallengeNotCompletedError();\n }\n\n if (error || !token) {\n throw new CardingProtectionFailedError();\n }\n\n return {\n type: 'recaptcha_v2_verification',\n data: {\n human_verification_token: token,\n },\n };\n }),\n )\n .toPromise();\n }\n\n private _initialize(recaptchaSitekey: string): Promise {\n const cardingProtectionElementId = 'cardingProtectionContainer';\n\n let cardingProtectionElement = document.getElementById(cardingProtectionElementId);\n\n if (cardingProtectionElement && cardingProtectionElement.parentNode) {\n cardingProtectionElement.parentNode.removeChild(cardingProtectionElement);\n }\n\n cardingProtectionElement = document.createElement('div');\n cardingProtectionElement.setAttribute('id', cardingProtectionElementId);\n document.body.appendChild(cardingProtectionElement);\n\n return this._googleRecaptcha.load(cardingProtectionElementId, recaptchaSitekey);\n }\n\n private _isPaymentHumanVerificationRequest(error: Error): error is RequestError {\n const { additional_action_required, status } = (error as RequestError).body || {};\n\n return (\n status === 'additional_action_required' &&\n additional_action_required &&\n additional_action_required.type === 'recaptcha_v2_verification'\n );\n }\n}\n","import StandardError from './standard-error';\n\nexport enum NotInitializedErrorType {\n CheckoutButtonNotInitialized,\n CustomerNotInitialized,\n PaymentNotInitialized,\n ShippingNotInitialized,\n SpamProtectionNotInitialized,\n}\n\n/**\n * Throw this error if a method requires a certain initialization call to be\n * made first. Some objects can be constructed but they cannot be used until a\n * separate initialization call is made.\n */\nexport default class NotInitializedError extends StandardError {\n constructor(public subtype: NotInitializedErrorType) {\n super(getErrorMessage(subtype));\n\n this.name = 'NotInitializedError';\n this.type = 'not_initialized';\n }\n}\n\nfunction getErrorMessage(type: NotInitializedErrorType): string {\n switch (type) {\n case NotInitializedErrorType.CustomerNotInitialized:\n return 'Unable to proceed because the customer step of checkout has not been initialized.';\n\n case NotInitializedErrorType.PaymentNotInitialized:\n return 'Unable to proceed because the payment step of checkout has not been initialized.';\n\n case NotInitializedErrorType.ShippingNotInitialized:\n return 'Unable to proceed because the shipping step of checkout has not been initialized.';\n\n case NotInitializedErrorType.SpamProtectionNotInitialized:\n return 'Unable to proceed because the checkout spam protection has not been initialized.';\n\n default:\n return 'Unable to proceed because the required component has not been initialized.';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if we fail to complete the required spam protection\n * verification due to an unknown reason.\n */\nexport default class SpamProtectionFailedError extends StandardError {\n constructor() {\n super('We were not able to complete your spam protection verification. Please try again.');\n\n this.name = 'SpamProtectionFailedError';\n this.type = 'spam_protection_failed';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if spam protection is not loaded when trying to\n * complete the required spam protection verification.\n */\nexport default class SpamProtectionNotLoadedError extends StandardError {\n constructor() {\n super('Spam protection is not loaded. Please try again.');\n\n this.name = 'SpamProtectionNotLoadedError';\n this.type = 'spam_protection_failed';\n }\n}\n","import { memoize } from '@bigcommerce/memoize';\nimport { defer, Observable, of, Subject, throwError } from 'rxjs';\nimport { catchError, delay, retryWhen, switchMap } from 'rxjs/operators';\n\nimport { MutationObserverFactory } from '../common/dom';\nimport { NotInitializedError, NotInitializedErrorType } from '../common/error/errors';\n\nimport {\n SpamProtectionChallengeNotCompletedError,\n SpamProtectionFailedError,\n SpamProtectionNotLoadedError,\n} from './errors';\nimport GoogleRecaptchaScriptLoader from './google-recaptcha-script-loader';\n\nconst TIMEOUT = 7000;\nconst RETRY_INTERVAL = 250;\nconst MAX_RETRIES = TIMEOUT / RETRY_INTERVAL;\n\nexport interface RecaptchaResult {\n error?: Error;\n token?: string;\n}\n\nexport default class GoogleRecaptcha {\n private _event$?: Subject;\n private _recaptcha?: ReCaptchaV2.ReCaptcha;\n private _memoized: (\n recaptcha: ReCaptchaV2.ReCaptcha,\n sitekey: string,\n container: HTMLElement | null,\n ) => Subject;\n private _widgetId?: number;\n\n constructor(\n private googleRecaptchaScriptLoader: GoogleRecaptchaScriptLoader,\n private mutationObserverFactory: MutationObserverFactory,\n ) {\n this._memoized = memoize(\n (recaptcha: ReCaptchaV2.ReCaptcha, sitekey: string, container: HTMLElement | null) => {\n const event$ = new Subject();\n\n if (!container) {\n throw new Error();\n }\n\n this._widgetId = recaptcha.render(container.id, {\n sitekey,\n size: 'invisible',\n callback: () => {\n event$.next({\n token: recaptcha.getResponse(this._widgetId),\n });\n recaptcha.reset(this._widgetId);\n },\n 'error-callback': () => {\n event$.next({\n error: new SpamProtectionFailedError(),\n });\n },\n });\n\n return event$;\n },\n { isEqual: (a, b) => a === b },\n );\n }\n\n load(containerId: string, sitekey: string): Promise {\n return this.googleRecaptchaScriptLoader.load().then((recaptcha) => {\n if (recaptcha) {\n this._event$ = this._memoized(\n recaptcha,\n sitekey,\n document.getElementById(containerId),\n );\n this._recaptcha = recaptcha;\n }\n });\n }\n\n execute(): Observable {\n return defer(() => {\n const event$ = this._event$;\n const recaptcha = this._recaptcha;\n\n if (!event$ || !recaptcha) {\n throw new NotInitializedError(NotInitializedErrorType.SpamProtectionNotInitialized);\n }\n\n return defer(() => {\n const element = document.querySelector('iframe[src*=\"bframe\"]');\n\n return element ? of(element) : throwError(new SpamProtectionNotLoadedError());\n }).pipe(\n retryWhen((errors) =>\n errors.pipe(\n delay(RETRY_INTERVAL),\n switchMap((error, index) =>\n index < MAX_RETRIES ? of(error) : throwError(error),\n ),\n ),\n ),\n switchMap((element) => {\n this._watchRecaptchaChallengeWindow(event$, element);\n recaptcha.execute(this._widgetId);\n\n return event$;\n }),\n catchError((error) => of({ error })),\n );\n });\n }\n\n private _watchRecaptchaChallengeWindow(event: Subject, element: Element) {\n const iframeContainer = element.parentElement;\n\n if (!iframeContainer) {\n throw new SpamProtectionNotLoadedError();\n }\n\n const container = iframeContainer.parentElement;\n\n if (!container) {\n throw new SpamProtectionNotLoadedError();\n }\n\n this.mutationObserverFactory\n .create(() => {\n // When customer closes the Google ReCaptcha challenge window, throw SpamProtectionNotCompletedError\n if (container.style.visibility === 'hidden') {\n event.next({\n error: new SpamProtectionChallengeNotCompletedError(),\n });\n }\n })\n .observe(container, { attributes: true, attributeFilter: ['style'] });\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nexport default class GoogleRecaptchaScriptLoader {\n private _loadPromise?: Promise;\n\n constructor(\n private _scriptLoader: ScriptLoader,\n private _window: GoogleRecaptchaWindow = window,\n ) {}\n\n load(): Promise {\n if (!this._loadPromise) {\n this._loadPromise = this._loadScript();\n }\n\n return this._loadPromise;\n }\n\n private _loadScript(): Promise {\n const callbackName = 'initRecaptcha';\n const params = [`onload=${callbackName}`, 'render=explicit'].join('&');\n\n return new Promise((resolve, reject) => {\n this._window[callbackName] = () => resolve(this._window.grecaptcha);\n\n this._scriptLoader\n .loadScript(`//www.google.com/recaptcha/api.js?${params}`)\n .catch((error) => {\n this._loadPromise = undefined;\n reject(error);\n });\n });\n }\n}\n\nexport interface GoogleRecaptchaWindow extends Window {\n grecaptcha?: ReCaptchaV2.ReCaptcha;\n initRecaptcha?(): void;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { MutationObserverFactory } from '../common/dom';\n\nimport GoogleRecaptcha from './google-recaptcha';\nimport GoogleRecaptchaScriptLoader from './google-recaptcha-script-loader';\n\nexport default function createSpamProtection(scriptLoader: ScriptLoader): GoogleRecaptcha {\n return new GoogleRecaptcha(\n new GoogleRecaptchaScriptLoader(scriptLoader),\n new MutationObserverFactory(),\n );\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { PaymentErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport RequestError from './request-error';\n\nexport default function mapFromPaymentErrorResponse(\n response: Response,\n message?: string,\n): RequestError {\n const { body } = response;\n const { errors = [] } = body;\n\n return new RequestError(response, {\n message: joinErrors(errors) || message,\n errors,\n });\n}\n\nfunction joinErrors(errors: Array<{ code: string; message?: string }>): string | undefined {\n if (!Array.isArray(errors)) {\n return;\n }\n\n return errors\n .reduce((result: string[], error) => {\n if (error && error.message) {\n return [...result, error.message];\n }\n\n return result;\n }, [])\n .join(' ');\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport default class InvalidHostedFormConfigError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Unable to proceed due to invalid configuration provided for the hosted payment form.',\n );\n\n this.name = 'InvalidHostedFormConfigError';\n this.type = 'invalid_hosted_form_config';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport default class InvalidHostedFormError extends StandardError {\n constructor(message?: string) {\n super(message || 'Unable to proceed due to an unknown error with the hosted payment form.');\n\n this.name = 'InvalidHostedFormError';\n this.type = 'invalid_hosted_form';\n }\n}\n","import { flatMap, map, values } from 'lodash';\n\nimport { StandardError } from '../../common/error/errors';\nimport { HostedInputValidateErrorDataMap } from '../iframe-content';\n\nexport default class InvalidHostedFormValueError extends StandardError {\n constructor(public errors: HostedInputValidateErrorDataMap) {\n super(\n [\n 'Unable to proceed due to invalid user input values',\n ...flatMap(values(errors), (fieldErrors) =>\n map(fieldErrors, ({ message }) => message),\n ),\n ].join('. '),\n );\n\n this.name = 'InvalidHostedFormValueError';\n this.type = 'invalid_hosted_form_value';\n }\n}\n","import { CardInstrument } from '../payment/instrument';\n\nimport HostedFieldType from './hosted-field-type';\nimport { HostedFieldStylesMap } from './hosted-form-options';\nimport HostedFormOrderData from './hosted-form-order-data';\n\nexport enum HostedFieldEventType {\n AttachRequested = 'HOSTED_FIELD:ATTACH_REQUESTED',\n SubmitRequested = 'HOSTED_FIELD:SUBMITTED_REQUESTED',\n ValidateRequested = 'HOSTED_FIELD:VALIDATE_REQUESTED',\n}\n\nexport interface HostedFieldEventMap {\n [HostedFieldEventType.AttachRequested]: HostedFieldAttachEvent;\n [HostedFieldEventType.SubmitRequested]: HostedFieldSubmitRequestEvent;\n [HostedFieldEventType.ValidateRequested]: HostedFieldValidateRequestEvent;\n}\n\nexport type HostedFieldEvent =\n | HostedFieldAttachEvent\n | HostedFieldSubmitRequestEvent\n | HostedFieldValidateRequestEvent;\n\nexport interface HostedFieldAttachEvent {\n type: HostedFieldEventType.AttachRequested;\n payload: {\n accessibilityLabel?: string;\n cardInstrument?: CardInstrument;\n fontUrls?: string[];\n placeholder?: string;\n styles?: HostedFieldStylesMap;\n origin?: string;\n type: HostedFieldType;\n };\n}\n\nexport interface HostedFieldSubmitRequestEvent {\n type: HostedFieldEventType.SubmitRequested;\n payload: {\n data: HostedFormOrderData;\n fields: HostedFieldType[];\n };\n}\n\nexport interface HostedFieldValidateRequestEvent {\n type: HostedFieldEventType.ValidateRequested;\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport {\n PaymentErrorData,\n PaymentErrorResponseBody,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport HostedFieldType from '../hosted-field-type';\nimport { HostedFormErrorsData } from '../hosted-form-options';\n\nimport HostedInputInitializeErrorData from './hosted-input-initialize-error-data';\nimport HostedInputValidateResults from './hosted-input-validate-results';\n\n// Event types\nexport enum HostedInputEventType {\n AttachSucceeded = 'HOSTED_INPUT:ATTACH_SUCCEEDED',\n AttachFailed = 'HOSTED_INPUT:ATTACH_FAILED',\n BinChanged = 'HOSTED_INPUT:BIN_CHANGED',\n Blurred = 'HOSTED_INPUT:BLURRED',\n Changed = 'HOSTED_INPUT:CHANGED',\n CardTypeChanged = 'HOSTED_INPUT:CARD_TYPE_CHANGED',\n Entered = 'HOSTED_INPUT:ENTERED',\n Focused = 'HOSTED_INPUT:FOCUSED',\n SubmitSucceeded = 'HOSTED_INPUT:SUBMIT_SUCCEEDED',\n SubmitFailed = 'HOSTED_INPUT:SUBMIT_FAILED',\n Validated = 'HOSTED_INPUT:VALIDATED',\n}\n\n// Event mapping\nexport interface HostedInputEventMap {\n [HostedInputEventType.AttachSucceeded]: HostedInputAttachSuccessEvent;\n [HostedInputEventType.AttachFailed]: HostedInputAttachErrorEvent;\n [HostedInputEventType.BinChanged]: HostedInputBinChangeEvent;\n [HostedInputEventType.Blurred]: HostedInputBlurEvent;\n [HostedInputEventType.Changed]: HostedInputChangeEvent;\n [HostedInputEventType.CardTypeChanged]: HostedInputCardTypeChangeEvent;\n [HostedInputEventType.Entered]: HostedInputEnterEvent;\n [HostedInputEventType.Focused]: HostedInputFocusEvent;\n [HostedInputEventType.SubmitSucceeded]: HostedInputSubmitSuccessEvent;\n [HostedInputEventType.SubmitFailed]: HostedInputSubmitErrorEvent;\n [HostedInputEventType.Validated]: HostedInputValidateEvent;\n}\n\n// Events\nexport type HostedInputEvent =\n | HostedInputAttachSuccessEvent\n | HostedInputAttachErrorEvent\n | HostedInputBinChangeEvent\n | HostedInputBlurEvent\n | HostedInputChangeEvent\n | HostedInputCardTypeChangeEvent\n | HostedInputEnterEvent\n | HostedInputFocusEvent\n | HostedInputSubmitSuccessEvent\n | HostedInputSubmitErrorEvent\n | HostedInputValidateEvent;\n\nexport interface HostedInputAttachSuccessEvent {\n type: HostedInputEventType.AttachSucceeded;\n}\n\nexport interface HostedInputAttachErrorEvent {\n type: HostedInputEventType.AttachFailed;\n payload: {\n error: HostedInputInitializeErrorData;\n };\n}\n\nexport interface HostedInputBinChangeEvent {\n type: HostedInputEventType.BinChanged;\n payload: {\n bin?: string;\n };\n}\n\nexport interface HostedInputBlurEvent {\n type: HostedInputEventType.Blurred;\n payload: {\n fieldType: HostedFieldType;\n errors?: HostedFormErrorsData;\n };\n}\n\nexport interface HostedInputChangeEvent {\n type: HostedInputEventType.Changed;\n payload: {\n fieldType: HostedFieldType;\n };\n}\n\nexport interface HostedInputCardTypeChangeEvent {\n type: HostedInputEventType.CardTypeChanged;\n payload: {\n cardType?: string;\n };\n}\n\nexport interface HostedInputFocusEvent {\n type: HostedInputEventType.Focused;\n payload: {\n fieldType: HostedFieldType;\n };\n}\n\nexport interface HostedInputEnterEvent {\n type: HostedInputEventType.Entered;\n payload: {\n fieldType: HostedFieldType;\n };\n}\n\nexport interface HostedInputSubmitSuccessEvent {\n type: HostedInputEventType.SubmitSucceeded;\n payload: {\n response: Response;\n };\n}\n\nexport interface HostedInputSubmitErrorEvent {\n type: HostedInputEventType.SubmitFailed;\n payload: {\n error: PaymentErrorData;\n response?: Response;\n };\n}\n\nexport interface HostedInputValidateEvent {\n type: HostedInputEventType.Validated;\n payload: HostedInputValidateResults;\n}\n","import { values } from 'lodash';\nimport { fromEvent } from 'rxjs';\nimport { switchMap, take } from 'rxjs/operators';\n\nimport { DetachmentObserver } from '../common/dom';\nimport { mapFromPaymentErrorResponse } from '../common/error/errors';\nimport { IframeEventListener, IframeEventPoster } from '../common/iframe';\nimport { parseUrl } from '../common/url';\nimport { CardInstrument } from '../payment/instrument';\n\nimport {\n InvalidHostedFormConfigError,\n InvalidHostedFormError,\n InvalidHostedFormValueError,\n} from './errors';\nimport { HostedFieldEvent, HostedFieldEventType } from './hosted-field-events';\nimport HostedFieldType from './hosted-field-type';\nimport { HostedFieldStylesMap } from './hosted-form-options';\nimport HostedFormOrderData from './hosted-form-order-data';\nimport {\n HostedInputEventMap,\n HostedInputEventType,\n HostedInputSubmitErrorEvent,\n HostedInputSubmitSuccessEvent,\n HostedInputValidateEvent,\n} from './iframe-content';\n\nexport const RETRY_INTERVAL = 60 * 1000;\nexport const LAST_RETRY_KEY = 'lastRetry';\n\nexport default class HostedField {\n private _iframe: HTMLIFrameElement;\n\n constructor(\n private _type: HostedFieldType,\n private _containerId: string,\n private _placeholder: string,\n private _accessibilityLabel: string,\n private _styles: HostedFieldStylesMap,\n private _eventPoster: IframeEventPoster,\n private _eventListener: IframeEventListener,\n private _detachmentObserver: DetachmentObserver,\n private _cardInstrument?: CardInstrument,\n ) {\n this._iframe = document.createElement('iframe');\n\n this._iframe.src = `/checkout/payment/hosted-field?version=${LIBRARY_VERSION}`;\n this._iframe.style.border = 'none';\n this._iframe.style.height = '100%';\n this._iframe.style.overflow = 'hidden';\n this._iframe.style.width = '100%';\n }\n\n getType(): HostedFieldType {\n return this._type;\n }\n\n async attach(): Promise {\n const container = document.getElementById(this._containerId);\n\n if (!container) {\n throw new InvalidHostedFormConfigError(\n 'Unable to proceed because the provided container ID is not valid.',\n );\n }\n\n container.appendChild(this._iframe);\n this._eventListener.listen();\n\n const promise = fromEvent(this._iframe, 'load')\n .pipe(\n switchMap(async ({ target }) => {\n const contentWindow = target && (target as HTMLIFrameElement).contentWindow;\n\n if (!contentWindow) {\n throw new Error('The content window of the iframe cannot be accessed.');\n }\n\n this._eventPoster.setTarget(contentWindow);\n\n await this._eventPoster.post(\n {\n type: HostedFieldEventType.AttachRequested,\n payload: {\n accessibilityLabel: this._accessibilityLabel,\n cardInstrument: this._cardInstrument,\n fontUrls: this._getFontUrls(),\n placeholder: this._placeholder,\n styles: this._styles,\n origin: document.location.origin,\n type: this._type,\n },\n },\n {\n successType: HostedInputEventType.AttachSucceeded,\n errorType: HostedInputEventType.AttachFailed,\n },\n );\n }),\n take(1),\n )\n .toPromise();\n\n await this._detachmentObserver.ensurePresence([this._iframe], promise);\n }\n\n detach(): void {\n if (!this._iframe.parentElement) {\n return;\n }\n\n this._iframe.parentElement.removeChild(this._iframe);\n this._eventListener.stopListen();\n }\n\n async submitForm(\n fields: HostedFieldType[],\n data: HostedFormOrderData,\n ): Promise {\n try {\n const promise = this._eventPoster.post(\n {\n type: HostedFieldEventType.SubmitRequested,\n payload: { fields, data },\n },\n {\n successType: HostedInputEventType.SubmitSucceeded,\n errorType: HostedInputEventType.SubmitFailed,\n },\n );\n\n return await this._detachmentObserver.ensurePresence([this._iframe], promise);\n } catch (event) {\n if (this._isSubmitErrorEvent(event)) {\n if (event.payload.error.code === 'hosted_form_error') {\n throw new InvalidHostedFormError(event.payload.error.message);\n }\n\n if (event.payload.response) {\n throw mapFromPaymentErrorResponse(event.payload.response);\n }\n\n throw new Error(event.payload.error.message);\n }\n\n throw event;\n }\n }\n\n async validateForm(): Promise {\n const promise = this._eventPoster.post(\n {\n type: HostedFieldEventType.ValidateRequested,\n },\n {\n successType: HostedInputEventType.Validated,\n },\n );\n\n const { payload } = await this._detachmentObserver.ensurePresence([this._iframe], promise);\n\n if (!payload.isValid) {\n throw new InvalidHostedFormValueError(payload.errors);\n }\n }\n\n private _getFontUrls(): string[] {\n const hostname = 'fonts.googleapis.com';\n const links = document.querySelectorAll(`link[href*='${hostname}'][rel='stylesheet']`);\n\n return Array.prototype.slice\n .call(links)\n .filter((link) => parseUrl(link.href).hostname === hostname)\n .filter((link) =>\n values(this._styles)\n .map((style) => style && style.fontFamily)\n .filter((family): family is string => typeof family === 'string')\n .some((family) =>\n family\n .split(/,\\s/)\n .some((name) => link.href.indexOf(name.replace(' ', '+')) !== -1),\n ),\n )\n .map((link) => link.href);\n }\n\n private _isSubmitErrorEvent(event: any): event is HostedInputSubmitErrorEvent {\n return event.type === HostedInputEventType.SubmitFailed;\n }\n}\n","import { noop, without } from 'lodash';\n\nimport { HostedForm as HostedFormInterface } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { IframeEventListener } from '../common/iframe';\nimport { OrderPaymentRequestBody } from '../order';\nimport { PaymentAdditionalAction } from '../payment';\nimport { PaymentHumanVerificationHandler } from '../spam-protection';\n\nimport { InvalidHostedFormConfigError } from './errors';\nimport HostedField from './hosted-field';\nimport HostedFormOptions from './hosted-form-options';\nimport HostedFormOrderDataTransformer from './hosted-form-order-data-transformer';\nimport {\n HostedInputEnterEvent,\n HostedInputEventMap,\n HostedInputEventType,\n HostedInputSubmitSuccessEvent,\n} from './iframe-content';\n\ntype HostedFormEventCallbacks = Pick<\n HostedFormOptions,\n 'onBlur' | 'onCardTypeChange' | 'onFocus' | 'onEnter' | 'onValidate'\n>;\n\nexport default class HostedForm implements HostedFormInterface {\n private _bin?: string;\n private _cardType?: string;\n\n constructor(\n private _fields: HostedField[],\n private _eventListener: IframeEventListener,\n private _payloadTransformer: HostedFormOrderDataTransformer,\n private _eventCallbacks: HostedFormEventCallbacks,\n private _paymentHumanVerificationHandler: PaymentHumanVerificationHandler,\n ) {\n const {\n onBlur = noop,\n onCardTypeChange = noop,\n onFocus = noop,\n onValidate = noop,\n } = this._eventCallbacks;\n\n this._eventListener.addListener(HostedInputEventType.Blurred, ({ payload }) =>\n onBlur(payload),\n );\n this._eventListener.addListener(HostedInputEventType.CardTypeChanged, ({ payload }) =>\n onCardTypeChange(payload),\n );\n this._eventListener.addListener(HostedInputEventType.Focused, ({ payload }) =>\n onFocus(payload),\n );\n this._eventListener.addListener(HostedInputEventType.Validated, ({ payload }) =>\n onValidate(payload),\n );\n this._eventListener.addListener(HostedInputEventType.Entered, this._handleEnter);\n\n this._eventListener.addListener(\n HostedInputEventType.CardTypeChanged,\n ({ payload }) => (this._cardType = payload.cardType),\n );\n this._eventListener.addListener(\n HostedInputEventType.BinChanged,\n ({ payload }) => (this._bin = payload.bin),\n );\n }\n\n getBin(): string | undefined {\n return this._bin;\n }\n\n getCardType(): string | undefined {\n return this._cardType;\n }\n\n async attach(): Promise {\n this._eventListener.listen();\n\n const field = this._getFirstField();\n const otherFields = without(this._fields, field);\n\n await field.attach();\n await Promise.all(otherFields.map((otherField) => otherField.attach()));\n }\n\n detach(): void {\n this._eventListener.stopListen();\n\n this._fields.forEach((field) => {\n field.detach();\n });\n }\n\n async submit(\n payload: OrderPaymentRequestBody,\n additionalActionData?: PaymentAdditionalAction,\n ): Promise {\n try {\n return await this._getFirstField().submitForm(\n this._fields.map((field) => field.getType()),\n this._payloadTransformer.transform(payload, additionalActionData),\n );\n } catch (error) {\n const additionalAction = await this._paymentHumanVerificationHandler.handle(error);\n\n return await this._getFirstField().submitForm(\n this._fields.map((field) => field.getType()),\n this._payloadTransformer.transform(payload, additionalAction),\n );\n }\n }\n\n async validate(): Promise {\n return this._getFirstField().validateForm();\n }\n\n private _getFirstField(): HostedField {\n const field = this._fields[0];\n\n if (!field) {\n throw new InvalidHostedFormConfigError(\n 'Unable to proceed because the payment form has no field defined.',\n );\n }\n\n return field;\n }\n\n private _handleEnter: (event: HostedInputEnterEvent) => Promise = async ({ payload }) => {\n try {\n await this.validate();\n } catch (error) {\n // Catch form validation error because we want to trigger `onEnter`\n // irrespective of the validation result.\n if (error.name !== 'InvalidHostedFormValueError') {\n throw error;\n }\n }\n\n const { onEnter = noop } = this._eventCallbacks;\n\n onEnter(payload);\n };\n}\n","import {\n FormattedPayload,\n FormattedVaultedInstrument,\n HostedVaultedInstrument,\n PaymentInstrument,\n VaultedInstrument,\n} from './payment';\n\nexport default function isVaultedInstrument(\n instrument: PaymentInstrument,\n): instrument is VaultedInstrument {\n return Boolean((instrument as VaultedInstrument).instrumentId);\n}\n\nexport function isHostedVaultedInstrument(\n instrument: PaymentInstrument,\n): instrument is HostedVaultedInstrument {\n return (\n Boolean((instrument as HostedVaultedInstrument).instrumentId) &&\n !Object.prototype.hasOwnProperty.call(instrument, 'ccNumber') &&\n !Object.prototype.hasOwnProperty.call(instrument, 'ccCvv')\n );\n}\n\nexport function isFormattedVaultedInstrument(\n instrument: PaymentInstrument,\n): instrument is FormattedPayload {\n const formattedInstrument = (instrument as FormattedPayload)\n .formattedPayload;\n\n if (!formattedInstrument) {\n return false;\n }\n\n return (\n typeof formattedInstrument.bigpay_token === 'string' ||\n Boolean(formattedInstrument.bigpay_token && formattedInstrument.bigpay_token.token)\n );\n}\n","import { omit } from 'lodash';\n\nimport { ReadableCheckoutStore } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { OrderPaymentRequestBody } from '../order';\nimport {\n HostedCreditCardInstrument,\n isVaultedInstrument,\n PaymentAdditionalAction,\n} from '../payment';\n\nimport HostedFormOrderData from './hosted-form-order-data';\n\nexport default class HostedFormOrderDataTransformer {\n constructor(private _store: ReadableCheckoutStore) {}\n\n transform(\n payload: OrderPaymentRequestBody,\n additionalAction?: PaymentAdditionalAction,\n ): HostedFormOrderData {\n const state = this._store.getState();\n const checkout = state.checkout.getCheckout();\n const config = state.config.getConfig();\n const instrumentMeta = state.instruments.getInstrumentsMeta();\n const order = state.order.getOrder();\n const orderMeta = state.order.getOrderMeta();\n const payment = omit(\n payload.paymentData,\n 'ccExpiry',\n 'ccName',\n 'ccNumber',\n 'ccCvv',\n ) as HostedCreditCardInstrument;\n const paymentMethod = state.paymentMethods.getPaymentMethod(\n payload.methodId,\n payload.gatewayId,\n );\n const paymentMethodMeta = state.paymentMethods.getPaymentMethodsMeta();\n const authToken =\n instrumentMeta && payment && isVaultedInstrument(payment)\n ? `${state.payment.getPaymentToken()}, ${instrumentMeta.vaultAccessToken}`\n : state.payment.getPaymentToken();\n\n if (!authToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n return {\n additionalAction,\n authToken,\n checkout,\n config,\n order,\n orderMeta,\n payment,\n paymentMethod,\n paymentMethodMeta,\n };\n }\n}\n","import { createScriptLoader } from '@bigcommerce/script-loader';\nimport { pick } from 'lodash';\n\nimport { ReadableCheckoutStore } from '../checkout';\nimport { DetachmentObserver, MutationObserverFactory } from '../common/dom';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { IframeEventListener, IframeEventPoster } from '../common/iframe';\nimport { CardInstrument } from '../payment/instrument';\nimport { createSpamProtection, PaymentHumanVerificationHandler } from '../spam-protection';\n\nimport HostedField from './hosted-field';\nimport HostedFieldType from './hosted-field-type';\nimport HostedForm from './hosted-form';\nimport HostedFormOptions, {\n HostedCardFieldOptionsMap,\n HostedStoredCardFieldOptionsMap,\n} from './hosted-form-options';\nimport HostedFormOrderDataTransformer from './hosted-form-order-data-transformer';\n\nexport default class HostedFormFactory {\n constructor(private _store: ReadableCheckoutStore) {}\n\n create(host: string, options: HostedFormOptions): HostedForm {\n const fieldTypes = Object.keys(options.fields) as HostedFieldType[];\n const fields = fieldTypes.reduce((result, type) => {\n const fields = options.fields as HostedStoredCardFieldOptionsMap &\n HostedCardFieldOptionsMap;\n const fieldOptions = fields[type];\n\n if (!fieldOptions) {\n return result;\n }\n\n return [\n ...result,\n new HostedField(\n type,\n fieldOptions.containerId,\n fieldOptions.placeholder || '',\n fieldOptions.accessibilityLabel || '',\n options.styles || {},\n new IframeEventPoster(host),\n new IframeEventListener(host),\n new DetachmentObserver(new MutationObserverFactory()),\n 'instrumentId' in fieldOptions\n ? this._getCardInstrument(fieldOptions.instrumentId)\n : undefined,\n ),\n ];\n }, []);\n\n return new HostedForm(\n fields,\n new IframeEventListener(host),\n new HostedFormOrderDataTransformer(this._store),\n pick(options, 'onBlur', 'onEnter', 'onFocus', 'onCardTypeChange', 'onValidate'),\n new PaymentHumanVerificationHandler(createSpamProtection(createScriptLoader())),\n );\n }\n\n private _getCardInstrument(instrumentId: string): CardInstrument {\n const {\n instruments: { getCardInstrument },\n } = this._store.getState();\n const instrument = getCardInstrument(instrumentId);\n\n if (!instrument) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentInstrument);\n }\n\n return instrument;\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if the shopper chooses not to complete the spam check.\n */\nexport default class SpamProtectionNotCompletedError extends StandardError {\n constructor() {\n super(\"You haven't complete our spam check. Please try again.\");\n\n this.name = 'SpamProtectionNotCompletedError';\n this.type = 'spam_protection_not_completed';\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { InternalOrderResponseData } from './internal-order-responses';\nimport Order from './order';\n\nexport enum OrderActionType {\n LoadOrderRequested = 'LOAD_ORDER_REQUESTED',\n LoadOrderSucceeded = 'LOAD_ORDER_SUCCEEDED',\n LoadOrderFailed = 'LOAD_ORDER_FAILED',\n\n LoadOrderPaymentsRequested = 'LOAD_ORDER_PAYMENTS_REQUESTED',\n LoadOrderPaymentsSucceeded = 'LOAD_ORDER_PAYMENTS_SUCCEEDED',\n LoadOrderPaymentsFailed = 'LOAD_ORDER_PAYMENTS_FAILED',\n\n SubmitOrderRequested = 'SUBMIT_ORDER_REQUESTED',\n SubmitOrderSucceeded = 'SUBMIT_ORDER_SUCCEEDED',\n SubmitOrderFailed = 'SUBMIT_ORDER_FAILED',\n\n FinalizeOrderRequested = 'FINALIZE_ORDER_REQUESTED',\n FinalizeOrderSucceeded = 'FINALIZE_ORDER_SUCCEEDED',\n FinalizeOrderFailed = 'FINALIZE_ORDER_FAILED',\n}\n\nexport type OrderAction =\n | LoadOrderAction\n | LoadOrderPaymentsAction\n | SubmitOrderAction\n | FinalizeOrderAction;\n\nexport type LoadOrderPaymentsAction =\n | LoadOrderPaymentsRequestedAction\n | LoadOrderPaymentsSucceededAction\n | LoadOrderPaymentsFailedAction;\n\nexport type LoadOrderAction =\n | LoadOrderRequestedAction\n | LoadOrderSucceededAction\n | LoadOrderFailedAction;\n\nexport type SubmitOrderAction =\n | SubmitOrderRequestedAction\n | SubmitOrderSucceededAction\n | SubmitOrderFailedAction\n | LoadOrderAction;\n\nexport type FinalizeOrderAction =\n | FinalizeOrderRequestedAction\n | FinalizeOrderSucceededAction\n | FinalizeOrderFailedAction\n | LoadOrderAction;\n\nexport interface LoadOrderRequestedAction extends Action {\n type: OrderActionType.LoadOrderRequested;\n}\n\nexport interface LoadOrderSucceededAction extends Action {\n type: OrderActionType.LoadOrderSucceeded;\n}\n\nexport interface LoadOrderFailedAction extends Action {\n type: OrderActionType.LoadOrderFailed;\n}\n\nexport interface LoadOrderPaymentsRequestedAction extends Action {\n type: OrderActionType.LoadOrderPaymentsRequested;\n}\n\nexport interface LoadOrderPaymentsSucceededAction extends Action {\n type: OrderActionType.LoadOrderPaymentsSucceeded;\n}\n\nexport interface LoadOrderPaymentsFailedAction extends Action {\n type: OrderActionType.LoadOrderPaymentsFailed;\n}\n\nexport interface SubmitOrderRequestedAction extends Action {\n type: OrderActionType.SubmitOrderRequested;\n}\n\nexport interface SubmitOrderSucceededAction extends Action {\n type: OrderActionType.SubmitOrderSucceeded;\n}\n\nexport interface SubmitOrderFailedAction extends Action {\n type: OrderActionType.SubmitOrderFailed;\n}\n\nexport interface FinalizeOrderRequestedAction extends Action {\n type: OrderActionType.FinalizeOrderRequested;\n}\n\nexport interface FinalizeOrderSucceededAction extends Action {\n type: OrderActionType.FinalizeOrderSucceeded;\n}\n\nexport interface FinalizeOrderFailedAction extends Action {\n type: OrderActionType.FinalizeOrderFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, from, Observable, Observer, of } from 'rxjs';\nimport { catchError, switchMap } from 'rxjs/operators';\n\nimport { CheckoutValidator, InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\nimport { SpamProtectionNotCompletedError } from '../spam-protection/errors';\n\nimport InternalOrderRequestBody from './internal-order-request-body';\nimport {\n FinalizeOrderAction,\n LoadOrderAction,\n LoadOrderPaymentsAction,\n OrderActionType,\n SubmitOrderAction,\n} from './order-actions';\nimport OrderRequestBody from './order-request-body';\nimport OrderRequestSender from './order-request-sender';\n\nexport default class OrderActionCreator {\n constructor(\n private _orderRequestSender: OrderRequestSender,\n private _checkoutValidator: CheckoutValidator,\n ) {}\n\n loadOrder(orderId: number, options?: RequestOptions): Observable {\n return new Observable((observer: Observer) => {\n observer.next(createAction(OrderActionType.LoadOrderRequested));\n\n this._orderRequestSender\n .loadOrder(orderId, options)\n .then((response) => {\n observer.next(createAction(OrderActionType.LoadOrderSucceeded, response.body));\n observer.complete();\n })\n .catch((response) => {\n observer.error(createErrorAction(OrderActionType.LoadOrderFailed, response));\n });\n });\n }\n\n // TODO: Remove when checkout does not contain unrelated order data.\n loadOrderPayments(\n orderId: number,\n options?: RequestOptions,\n ): Observable {\n return new Observable((observer: Observer) => {\n observer.next(createAction(OrderActionType.LoadOrderPaymentsRequested));\n\n this._orderRequestSender\n .loadOrder(orderId, options)\n .then((response) => {\n observer.next(\n createAction(OrderActionType.LoadOrderPaymentsSucceeded, response.body),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(OrderActionType.LoadOrderPaymentsFailed, response),\n );\n });\n });\n }\n\n loadCurrentOrder(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n defer(() => {\n const orderId = this._getCurrentOrderId(store.getState());\n\n if (!orderId) {\n throw new MissingDataError(MissingDataErrorType.MissingOrderId);\n }\n\n return this.loadOrder(orderId, options);\n });\n }\n\n submitOrder(\n payload?: OrderRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(OrderActionType.SubmitOrderRequested)),\n defer(() => {\n const state = store.getState();\n const externalSource = state.config.getExternalSource();\n const variantIdentificationToken = state.config.getVariantIdentificationToken();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (checkout.shouldExecuteSpamCheck) {\n throw new SpamProtectionNotCompletedError();\n }\n\n return from(\n this._checkoutValidator.validate(checkout, options).then(() =>\n this._orderRequestSender.submitOrder(\n this._mapToOrderRequestBody(\n payload ?? {},\n checkout.id,\n checkout.customerMessage,\n externalSource,\n ),\n {\n ...options,\n headers: {\n checkoutVariant: variantIdentificationToken,\n },\n },\n ),\n ),\n ).pipe(\n switchMap((response) =>\n concat(\n // TODO: Remove once we can submit orders using storefront API\n this.loadOrder(response.body.data.order.orderId, options),\n of(\n createAction(\n OrderActionType.SubmitOrderSucceeded,\n response.body.data,\n { ...response.body.meta, token: response.headers.token },\n ),\n ),\n ),\n ),\n );\n }).pipe(\n catchError((error) =>\n throwErrorAction(OrderActionType.SubmitOrderFailed, error),\n ),\n ),\n );\n }\n\n finalizeOrder(\n orderId: number,\n options?: RequestOptions,\n ): Observable {\n return concat(\n of(createAction(OrderActionType.FinalizeOrderRequested)),\n from(this._orderRequestSender.finalizeOrder(orderId, options)).pipe(\n switchMap((response) =>\n concat(\n this.loadOrder(orderId, options),\n of(\n createAction(\n OrderActionType.FinalizeOrderSucceeded,\n response.body.data,\n ),\n ),\n ),\n ),\n ),\n ).pipe(catchError((error) => throwErrorAction(OrderActionType.FinalizeOrderFailed, error)));\n }\n\n private _getCurrentOrderId(state: InternalCheckoutSelectors): number | undefined {\n const order = state.order.getOrder();\n const checkout = state.checkout.getCheckout();\n\n return (order && order.orderId) || (checkout && checkout.orderId);\n }\n\n private _mapToOrderRequestBody(\n payload: OrderRequestBody,\n cartId: string,\n customerMessage: string,\n externalSource?: string,\n ): InternalOrderRequestBody {\n const { payment, ...order } = payload;\n\n if (!payment) {\n return {\n ...order,\n cartId,\n customerMessage,\n externalSource,\n };\n }\n\n return {\n ...order,\n cartId,\n customerMessage,\n externalSource,\n payment: {\n paymentData: payment.paymentData,\n name: payment.methodId,\n gateway: payment.gatewayId,\n },\n };\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error is thrown when the server detects inconsistency in cart data since it is last requested,\n * for example, product prices or eligible discounts have changed.\n */\nexport default class CartConsistencyError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Your checkout could not be processed because some details have changed. Please review your order and try again.',\n );\n\n this.name = 'CartConsistencyError';\n this.type = 'cart_consistency';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Checkout prevents consumers from placing their orders when a merchant wishes\n * to be able to block transactions if the automated tax provider cannot be reached.\n */\nexport default class OrderTaxProviderUnavailableError extends StandardError {\n constructor(message?: string) {\n super(message || 'The tax provider is unavailable.');\n\n this.name = 'OrderTaxProviderUnavailableError';\n this.type = 'tax_provider_unavailable';\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\nimport { isNil, omitBy } from 'lodash';\n\nimport { CartConsistencyError } from '../cart/errors';\nimport {\n ContentType,\n joinIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport { OrderTaxProviderUnavailableError } from './errors';\nimport InternalOrderRequestBody from './internal-order-request-body';\nimport { InternalOrderResponseBody } from './internal-order-responses';\nimport Order from './order';\n\nexport interface SubmitOrderRequestOptions extends RequestOptions {\n headers?: {\n checkoutVariant?: string;\n };\n}\n\nexport default class OrderRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n loadOrder(orderId: number, { timeout }: RequestOptions = {}): Promise> {\n const url = `/api/storefront/orders/${orderId}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n const include = [\n 'payments',\n 'lineItems.physicalItems.socialMedia',\n 'lineItems.physicalItems.options',\n 'lineItems.physicalItems.categories',\n 'lineItems.digitalItems.socialMedia',\n 'lineItems.digitalItems.options',\n 'lineItems.digitalItems.categories',\n ];\n\n return this._requestSender.get(url, {\n params: {\n include: joinIncludes(include),\n },\n headers,\n timeout,\n });\n }\n\n submitOrder(\n body?: InternalOrderRequestBody,\n { headers, timeout }: SubmitOrderRequestOptions = {},\n ): Promise> {\n const url = '/internalapi/v1/checkout/order';\n\n return this._requestSender\n .post(url, {\n body,\n headers: omitBy(\n {\n 'X-Checkout-Variant': headers && headers.checkoutVariant,\n ...SDK_VERSION_HEADERS,\n },\n isNil,\n ),\n timeout,\n })\n .catch((error) => {\n if (error.body.type === 'tax_provider_unavailable') {\n throw new OrderTaxProviderUnavailableError();\n }\n\n if (error.body.type === 'cart_has_changed') {\n throw new CartConsistencyError();\n }\n\n throw error;\n });\n }\n\n finalizeOrder(\n orderId: number,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/internalapi/v1/checkout/order/${orderId}`;\n\n return this._requestSender.post(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { LoadOrderAction } from '../order';\n\nimport PaymentResponseBody from './payment-response-body';\n\nexport enum PaymentActionType {\n SubmitPaymentRequested = 'SUBMIT_PAYMENT_REQUESTED',\n SubmitPaymentSucceeded = 'SUBMIT_PAYMENT_SUCCEEDED',\n SubmitPaymentFailed = 'SUBMIT_PAYMENT_FAILED',\n\n InitializeOffsitePaymentRequested = 'INITIALIZE_OFFSITE_PAYMENT_REQUESTED',\n InitializeOffsitePaymentSucceeded = 'INITIALIZE_OFFSITE_PAYMENT_SUCCEEDED',\n InitializeOffsitePaymentFailed = 'INITIALIZE_OFFSITE_PAYMENT_FAILED',\n}\n\nexport type PaymentAction = SubmitPaymentAction | InitializeOffsitePaymentAction;\n\nexport type SubmitPaymentAction =\n | SubmitPaymentRequestedAction\n | SubmitPaymentSucceededAction\n | SubmitPaymentFailedAction\n | LoadOrderAction;\n\nexport type InitializeOffsitePaymentAction =\n | InitializeOffsitePaymentRequestedAction\n | InitializeOffsitePaymentSucceededAction\n | InitializeOffsitePaymentFailedAction;\n\nexport interface SubmitPaymentRequestedAction extends Action {\n type: PaymentActionType.SubmitPaymentRequested;\n}\n\nexport interface SubmitPaymentSucceededAction extends Action {\n type: PaymentActionType.SubmitPaymentSucceeded;\n}\n\nexport interface SubmitPaymentFailedAction extends Action {\n type: PaymentActionType.SubmitPaymentFailed;\n}\n\nexport interface InitializeOffsitePaymentRequestedAction extends Action {\n type: PaymentActionType.InitializeOffsitePaymentRequested;\n}\n\nexport interface InitializeOffsitePaymentSucceededAction extends Action {\n type: PaymentActionType.InitializeOffsitePaymentSucceeded;\n}\n\nexport interface InitializeOffsitePaymentFailedAction extends Action {\n type: PaymentActionType.InitializeOffsitePaymentFailed;\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, of } from 'rxjs';\nimport { catchError, switchMap } from 'rxjs/operators';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { OrderActionCreator } from '../order';\nimport { PaymentHumanVerificationHandler } from '../spam-protection';\n\nimport Payment, {\n FormattedHostedInstrument,\n FormattedPayload,\n FormattedVaultedInstrument,\n} from './payment';\nimport {\n InitializeOffsitePaymentAction,\n PaymentActionType,\n SubmitPaymentAction,\n} from './payment-actions';\nimport PaymentRequestSender from './payment-request-sender';\nimport PaymentRequestTransformer from './payment-request-transformer';\n\ninterface InitializeOffsitePaymentSettings {\n methodId: string;\n gatewayId?: string;\n instrumentId?: string;\n target?: string;\n promise?: Promise;\n shouldSaveInstrument?: boolean;\n shouldSetAsDefaultInstrument?: boolean;\n}\n\ntype InitializeOffsitePayment = (\n settings: InitializeOffsitePaymentSettings,\n) => ThunkAction;\n\nexport default class PaymentActionCreator {\n constructor(\n private _paymentRequestSender: PaymentRequestSender,\n private _orderActionCreator: OrderActionCreator,\n private _paymentRequestTransformer: PaymentRequestTransformer,\n private _paymentHumanVerificationHandler: PaymentHumanVerificationHandler,\n ) {}\n\n submitPayment(payment: Payment): ThunkAction {\n return (store) =>\n concat(\n of(createAction(PaymentActionType.SubmitPaymentRequested)),\n defer(async () => {\n try {\n return await this._paymentRequestSender.submitPayment(\n this._paymentRequestTransformer.transform(payment, store.getState()),\n );\n } catch (error) {\n const additionalAction = await this._paymentHumanVerificationHandler.handle(\n error,\n );\n\n return await this._paymentRequestSender.submitPayment(\n this._paymentRequestTransformer.transform(\n { ...payment, additionalAction },\n store.getState(),\n ),\n );\n }\n }).pipe(\n switchMap(({ body }) =>\n concat(\n this._orderActionCreator.loadCurrentOrder()(store),\n of(createAction(PaymentActionType.SubmitPaymentSucceeded, body)),\n ),\n ),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(PaymentActionType.SubmitPaymentFailed, error),\n ),\n );\n }\n\n initializeOffsitePayment: InitializeOffsitePayment = ({\n methodId,\n gatewayId,\n instrumentId,\n target,\n promise,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n }) => {\n return (store) => {\n let paymentData:\n | FormattedPayload\n | undefined;\n\n if (instrumentId) {\n paymentData = { formattedPayload: { bigpay_token: instrumentId } };\n } else if (shouldSaveInstrument) {\n paymentData = {\n formattedPayload: {\n vault_payment_instrument: shouldSaveInstrument,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n },\n };\n }\n\n const payload = this._paymentRequestTransformer.transform(\n { gatewayId, methodId, paymentData },\n store.getState(),\n );\n\n return concat(\n of(createAction(PaymentActionType.InitializeOffsitePaymentRequested)),\n Promise.race(\n [\n this._paymentRequestSender.initializeOffsitePayment(payload, target),\n promise,\n ].filter(Boolean),\n ).then(() => createAction(PaymentActionType.InitializeOffsitePaymentSucceeded)),\n ).pipe(\n catchError((error) =>\n throwErrorAction(PaymentActionType.InitializeOffsitePaymentFailed, error),\n ),\n );\n };\n };\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport PaymentRequestBody from './payment-request-body';\n\n/**\n * @todo Convert this file into TypeScript properly\n */\nexport default class PaymentRequestSender {\n /**\n * @class\n * @param {BigpayClient} client\n */\n constructor(private _client: any) {}\n\n submitPayment(payload: PaymentRequestBody): Promise> {\n return new Promise((resolve, reject) => {\n this._client.submitPayment(payload, (error: any, response: any) => {\n if (error) {\n reject(this._transformResponse(error));\n } else {\n resolve(this._transformResponse(response));\n }\n });\n });\n }\n\n initializeOffsitePayment(payload: PaymentRequestBody, target?: string): Promise {\n return new Promise(() => {\n this._client.initializeOffsitePayment(payload, null, target);\n });\n }\n\n private _transformResponse(response: any): Response {\n return {\n headers: response.headers,\n body: response.data,\n status: response.status,\n statusText: response.statusText,\n };\n }\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@bigcommerce/bigpay-client\");","// / \nimport { createClient as createBigpayClient } from '@bigcommerce/bigpay-client';\n\nimport { CheckoutStore } from '../checkout';\n\nexport default function createPaymentClient(store: CheckoutStore) {\n const paymentClient = createBigpayClient();\n\n store.subscribe(\n (state) => {\n const config = state.config.getStoreConfig();\n\n if (config) {\n paymentClient.setHost(config.paymentSettings.bigpayBaseUrl);\n }\n },\n (state) => state.config.getStoreConfig(),\n );\n\n return paymentClient;\n}\n","import { Address } from '../address';\n\nimport BillingAddress from './billing-address';\n\nexport default function isBillingAddressLike(address: Address): address is BillingAddress {\n const billingAddress = address as BillingAddress;\n\n return typeof billingAddress.id !== 'undefined';\n}\n","import { BillingAddress, isBillingAddressLike } from '../billing';\nimport { Consignment } from '../shipping';\n\nimport Address from './address';\nimport InternalAddress from './internal-address';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalAddress(\n address: Address | BillingAddress,\n consignments?: Consignment[],\n): InternalAddress {\n let addressId;\n\n if (isBillingAddressLike(address)) {\n addressId = address.id;\n } else if (consignments && consignments.length) {\n addressId = consignments[0].id;\n }\n\n return {\n id: addressId,\n firstName: address.firstName,\n lastName: address.lastName,\n company: address.company,\n addressLine1: address.address1,\n addressLine2: address.address2,\n city: address.city,\n province: address.stateOrProvince,\n provinceCode: address.stateOrProvinceCode,\n postCode: address.postalCode,\n country: address.country,\n countryCode: address.countryCode,\n phone: address.phone,\n customFields: address.customFields,\n };\n}\n","export default class AmountTransformer {\n constructor(private _decimalPlaces: number) {}\n\n toInteger(amount: number): number {\n return Math.round(amount * Math.pow(10, this._decimalPlaces));\n }\n}\n","import Coupon from './coupon';\nimport InternalCoupon from './internal-coupon';\n\nconst couponTypes = [\n 'per_item_discount',\n 'percentage_discount',\n 'per_total_discount',\n 'shipping_discount',\n 'free_shipping',\n];\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalCoupon(coupon: Coupon): InternalCoupon {\n return {\n code: coupon.code,\n discount: coupon.displayName,\n discountType: couponTypes.indexOf(coupon.couponType),\n };\n}\n","enum CheckoutButtonMethodType {\n APPLEPAY = \"applepay\",\n AMAZON_PAY_V2 = \"amazonpay\",\n BRAINTREE_PAYPAL = \"braintreepaypal\",\n BRAINTREE_VENMO = \"braintreevenmo\",\n BRAINTREE_PAYPAL_CREDIT = \"braintreepaypalcredit\",\n GOOGLEPAY_ADYENV2 = \"googlepayadyenv2\",\n GOOGLEPAY_ADYENV3 = \"googlepayadyenv3\",\n GOOGLEPAY_AUTHORIZENET = \"googlepayauthorizenet\",\n GOOGLEPAY_BNZ = \"googlepaybnz\",\n GOOGLEPAY_BRAINTREE = \"googlepaybraintree\",\n GOOGLEPAY_CHECKOUTCOM = \"googlepaycheckoutcom\",\n GOOGLEPAY_CYBERSOURCEV2 = \"googlepaycybersourcev2\",\n GOOGLEPAY_ORBITAL = \"googlepayorbital\",\n GOOGLEPAY_STRIPE = \"googlepaystripe\",\n GOOGLEPAY_STRIPEUPE = \"googlepaystripeupe\",\n GOOGLEPAY_WORLDPAYACCESS = \"googlepayworldpayaccess\",\n MASTERPASS = \"masterpass\",\n PAYPALEXPRESS = \"paypalexpress\"\n}\nexport default CheckoutButtonMethodType;\n\n","import GiftCertificate from './gift-certificate';\nimport InternalGiftCertificate from './internal-gift-certificate';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalGiftCertificate(\n giftCertificate: GiftCertificate,\n): InternalGiftCertificate {\n return {\n code: giftCertificate.code,\n discountedAmount: giftCertificate.used,\n remainingBalance: giftCertificate.remaining,\n giftCertificate: {\n balance: giftCertificate.balance,\n code: giftCertificate.code,\n purchaseDate: giftCertificate.purchaseDate,\n },\n };\n}\n","import InternalLineItem from './internal-line-item';\nimport { LineItem } from './line-item';\nimport LineItemMap from './line-item-map';\nimport mapGiftCertificateToInternalLineItem from './map-gift-certificate-to-internal-line-item';\nimport mapToInternalLineItem from './map-to-internal-line-item';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalLineItems(\n itemMap: LineItemMap,\n decimalPlaces: number,\n idKey: keyof LineItem = 'id',\n): InternalLineItem[] {\n return (Object.keys(itemMap) as Array).reduce(\n (result, key) => [\n ...result,\n ...(itemMap[key] as LineItem[]).map((item: any) => {\n if (key === 'giftCertificates') {\n return mapGiftCertificateToInternalLineItem(item, decimalPlaces);\n }\n\n return mapToInternalLineItem(\n item,\n mapToInternalLineItemType(key),\n decimalPlaces,\n idKey,\n );\n }),\n ],\n [] as InternalLineItem[],\n );\n}\n\nfunction mapToInternalLineItemType(type: string): string {\n switch (type) {\n case 'physicalItems':\n return 'ItemPhysicalEntity';\n\n case 'digitalItems':\n return 'ItemDigitalEntity';\n\n case 'giftCertificates':\n return 'ItemGiftCertificateEntity';\n\n default:\n return '';\n }\n}\n","import { AmountTransformer } from '../common/utility';\n\nimport InternalLineItem from './internal-line-item';\nimport { GiftCertificateItem } from './line-item';\n\nexport default function mapGiftCertificateToInternalLineItem(\n item: GiftCertificateItem,\n decimalPlaces: number,\n): InternalLineItem {\n const amountTransformer = new AmountTransformer(decimalPlaces);\n\n return {\n id: item.id,\n imageUrl: '',\n name: item.name,\n amount: item.amount,\n amountAfterDiscount: item.amount,\n discount: 0,\n integerAmount: amountTransformer.toInteger(item.amount),\n integerAmountAfterDiscount: amountTransformer.toInteger(item.amount),\n integerUnitPrice: amountTransformer.toInteger(item.amount),\n integerUnitPriceAfterDiscount: amountTransformer.toInteger(item.amount),\n integerDiscount: 0,\n quantity: 1,\n sender: item.sender,\n recipient: item.recipient,\n type: 'ItemGiftCertificateEntity',\n attributes: [],\n variantId: null,\n };\n}\n","import { AmountTransformer } from '../common/utility';\n\nimport InternalLineItem from './internal-line-item';\nimport { DigitalItem, LineItem } from './line-item';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalLineItem(\n item: LineItem,\n type: string,\n decimalPlaces: number,\n idKey: keyof LineItem = 'id',\n): InternalLineItem {\n const amountTransformer = new AmountTransformer(decimalPlaces);\n\n return {\n id: item[idKey] as string | number,\n imageUrl: item.imageUrl,\n amount: item.extendedListPrice,\n amountAfterDiscount: item.extendedSalePrice,\n discount: item.discountAmount,\n integerAmount: amountTransformer.toInteger(item.extendedListPrice),\n integerAmountAfterDiscount: amountTransformer.toInteger(item.extendedSalePrice),\n integerDiscount: amountTransformer.toInteger(item.discountAmount),\n integerUnitPrice: amountTransformer.toInteger(item.listPrice),\n integerUnitPriceAfterDiscount: amountTransformer.toInteger(item.salePrice),\n downloadsPageUrl: (item as DigitalItem).downloadPageUrl,\n name: item.name,\n quantity: item.quantity,\n brand: item.brand,\n sku: item.sku,\n categoryNames: item.categoryNames,\n variantId: item.variantId,\n productId: item.productId,\n attributes: (item.options || []).map((option) => ({\n name: option.name,\n value: option.value,\n })),\n addedByPromotion: item.addedByPromotion,\n type,\n };\n}\n","import { keyBy, reduce, some } from 'lodash';\n\nimport { Checkout } from '../checkout';\nimport { AmountTransformer } from '../common/utility';\nimport { mapToInternalCoupon, mapToInternalGiftCertificate } from '../coupon';\nimport { mapToDiscountNotifications } from '../promotion';\n\nimport InternalCart from './internal-cart';\nimport mapToInternalLineItems from './map-to-internal-line-items';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalCart(checkout: Checkout): InternalCart {\n const decimalPlaces = checkout.cart.currency.decimalPlaces;\n const amountTransformer = new AmountTransformer(decimalPlaces);\n\n return {\n id: checkout.cart.id,\n items: mapToInternalLineItems(checkout.cart.lineItems, decimalPlaces),\n currency: checkout.cart.currency.code,\n coupon: {\n discountedAmount: reduce(\n checkout.cart.coupons,\n (sum, coupon) => {\n return sum + coupon.discountedAmount;\n },\n 0,\n ),\n coupons: checkout.cart.coupons.map(mapToInternalCoupon),\n },\n discount: {\n amount: checkout.cart.discountAmount,\n integerAmount: amountTransformer.toInteger(checkout.cart.discountAmount),\n },\n discountNotifications: mapToDiscountNotifications(checkout.promotions),\n giftCertificate: {\n totalDiscountedAmount: reduce(\n checkout.giftCertificates,\n (sum, certificate) => {\n return sum + certificate.used;\n },\n 0,\n ),\n appliedGiftCertificates: keyBy(\n checkout.giftCertificates.map(mapToInternalGiftCertificate),\n 'code',\n ),\n },\n shipping: {\n amount: checkout.shippingCostTotal,\n integerAmount: amountTransformer.toInteger(checkout.shippingCostTotal),\n amountBeforeDiscount: checkout.shippingCostBeforeDiscount,\n integerAmountBeforeDiscount: amountTransformer.toInteger(\n checkout.shippingCostBeforeDiscount,\n ),\n required: some(\n checkout.cart.lineItems.physicalItems,\n (lineItem) => lineItem.isShippingRequired,\n ),\n },\n subtotal: {\n amount: checkout.subtotal,\n integerAmount: amountTransformer.toInteger(checkout.subtotal),\n },\n storeCredit: {\n amount: checkout.customer ? checkout.customer.storeCredit : 0,\n },\n taxSubtotal: {\n amount: checkout.taxTotal,\n integerAmount: amountTransformer.toInteger(checkout.taxTotal),\n },\n taxes: checkout.taxes,\n taxTotal: {\n amount: checkout.taxTotal,\n integerAmount: amountTransformer.toInteger(checkout.taxTotal),\n },\n handling: {\n amount: checkout.handlingCostTotal,\n integerAmount: amountTransformer.toInteger(checkout.handlingCostTotal),\n },\n grandTotal: {\n amount: checkout.grandTotal,\n integerAmount: amountTransformer.toInteger(checkout.grandTotal),\n },\n };\n}\n","import { DiscountNotification } from '../discount';\n\nimport { Promotion } from '.';\n\nexport default function mapToDiscountNotifications(\n promotions?: Promotion[],\n): DiscountNotification[] {\n const notifications: DiscountNotification[] = [];\n\n (promotions || []).forEach((promotion) => {\n (promotion.banners || []).forEach((banner) => {\n notifications.push({\n placeholders: [],\n discountType: null,\n message: '',\n messageHtml: banner.text,\n });\n });\n });\n\n return notifications;\n}\n","import { mapToInternalAddress } from '../address';\nimport { OrderBillingAddress } from '../order-billing-address/order-billing-address-state';\n\nimport InternalCustomer from './internal-customer';\n\nimport { Customer } from '.';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalCustomer(\n customer: Customer,\n billingAddress: OrderBillingAddress,\n): InternalCustomer {\n const firstName = customer.firstName || billingAddress.firstName || '';\n const lastName = customer.lastName || billingAddress.lastName || '';\n\n return {\n addresses: (customer.addresses || []).map((address) => mapToInternalAddress(address)),\n customerId: customer.id,\n isGuest: customer.isGuest,\n storeCredit: customer.storeCredit,\n email: customer.email || billingAddress.email || '',\n firstName,\n lastName,\n name: customer.fullName || [firstName, lastName].join(' '),\n customerGroupName: customer.customerGroup && customer.customerGroup.name,\n };\n}\n","import CardExpiryDate from './card-expiry-date';\n\nconst NUMBER_SEPARATOR = '/';\n\nexport default class CardExpiryFormatter {\n format(value: string): string {\n const [month = '', year = ''] = value.split(new RegExp(`\\\\s*${NUMBER_SEPARATOR}\\\\s*`));\n const trimmedMonth = month.slice(0, 2);\n const trimmedYear =\n year.length === 4 ? year.slice(-2) : year ? year.slice(0, 2) : month.slice(2);\n\n // i.e.: '1'\n if (value.length < 2) {\n return month;\n }\n\n // ie.: '10 /' (without trailing space)\n if (value.length > 3 && !trimmedYear) {\n return trimmedMonth;\n }\n\n return `${trimmedMonth} ${NUMBER_SEPARATOR} ${trimmedYear}`;\n }\n\n toObject(value: string): CardExpiryDate {\n const [month = '', year = ''] = value.split(new RegExp(`\\\\s*${NUMBER_SEPARATOR}\\\\s*`));\n\n if (!/^\\d+$/.test(month) || !/^\\d+$/.test(year)) {\n return { month: '', year: '' };\n }\n\n return {\n month: month.length === 1 ? `0${month}` : month.slice(0, 2),\n year: year.length === 2 ? `20${year}` : year.slice(0, 4),\n };\n }\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"card-validator\");","import { creditCardType, number } from 'card-validator';\nimport { max } from 'lodash';\n\nconst NUMBER_SEPARATOR = ' ';\n\nexport default class CardNumberFormatter {\n format(value: string): string {\n const { card } = number(value);\n\n if (!card) {\n return value;\n }\n\n const maxLength = max(creditCardType(value).map((info) => max(info.lengths)));\n const unformattedValue = this.unformat(value).slice(0, maxLength);\n\n return card.gaps\n .filter((gapIndex) => unformattedValue.length > gapIndex)\n .reduce(\n (output, gapIndex, index) =>\n [output.slice(0, gapIndex + index), output.slice(gapIndex + index)].join(\n NUMBER_SEPARATOR,\n ),\n unformattedValue,\n );\n }\n\n unformat(value: string): string {\n const { card } = number(value);\n\n if (!card) {\n return value;\n }\n\n return value.replace(new RegExp(NUMBER_SEPARATOR, 'g'), '');\n }\n}\n","import { filter, find, keyBy, reduce } from 'lodash';\n\nimport { LineItem, mapToInternalLineItems } from '../cart';\nimport { Checkout } from '../checkout';\nimport { AmountTransformer } from '../common/utility';\nimport { mapToInternalCoupon } from '../coupon';\nimport { HOSTED } from '../payment';\n\nimport InternalOrder, {\n InternalGiftCertificateList,\n InternalIncompleteOrder,\n InternalOrderPayment,\n InternalSocialDataList,\n} from './internal-order';\nimport Order, {\n GatewayOrderPayment,\n GiftCertificateOrderPayment,\n OrderPayment,\n OrderPayments,\n} from './order';\nimport { OrderMetaState } from './order-state';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalOrder(\n order: Order,\n orderMeta: OrderMetaState = {},\n): InternalOrder {\n const decimalPlaces = order.currency.decimalPlaces;\n const amountTransformer = new AmountTransformer(decimalPlaces);\n\n return {\n id: order.orderId,\n items: mapToInternalLineItems(order.lineItems, order.currency.decimalPlaces, 'productId'),\n orderId: order.orderId,\n currency: order.currency.code,\n customerCanBeCreated: order.customerCanBeCreated,\n payment: mapToInternalOrderPayment(order.payments, orderMeta.payment),\n subtotal: {\n amount: order.baseAmount,\n integerAmount: amountTransformer.toInteger(order.baseAmount),\n },\n coupon: {\n discountedAmount: reduce(\n order.coupons,\n (sum, coupon) => {\n return sum + coupon.discountedAmount;\n },\n 0,\n ),\n coupons: order.coupons.map(mapToInternalCoupon),\n },\n discount: {\n amount: order.discountAmount,\n integerAmount: amountTransformer.toInteger(order.discountAmount),\n },\n token: orderMeta.orderToken,\n callbackUrl: orderMeta.callbackUrl,\n discountNotifications: [],\n giftCertificate: mapToGiftCertificates(order.payments),\n socialData: mapToInternalSocialDataList(order),\n status: order.status,\n hasDigitalItems: order.hasDigitalItems,\n isDownloadable: order.isDownloadable,\n isComplete: order.isComplete,\n shipping: {\n amount: order.shippingCostTotal,\n integerAmount: amountTransformer.toInteger(order.shippingCostTotal),\n amountBeforeDiscount: order.shippingCostBeforeDiscount,\n integerAmountBeforeDiscount: amountTransformer.toInteger(\n order.shippingCostBeforeDiscount,\n ),\n },\n storeCredit: {\n amount: mapToStoreCredit(order.payments),\n },\n taxes: order.taxes,\n taxTotal: {\n amount: order.taxTotal,\n integerAmount: amountTransformer.toInteger(order.taxTotal),\n },\n handling: {\n amount: order.handlingCostTotal,\n integerAmount: amountTransformer.toInteger(order.handlingCostTotal),\n },\n grandTotal: {\n amount: order.orderAmount,\n integerAmount: order.orderAmountAsInteger,\n },\n };\n}\n\nexport function mapToInternalIncompleteOrder(checkout: Checkout): InternalIncompleteOrder {\n const payment = find(checkout.payments, { providerType: HOSTED });\n\n return {\n orderId: null,\n isComplete: false,\n payment: !payment\n ? {}\n : {\n id: payment.providerId,\n gateway: payment.gatewayId,\n status: mapToInternalPaymentStatus(payment.detail.step),\n },\n };\n}\n\nfunction mapToInternalPaymentStatus(status: string): string {\n return `PAYMENT_STATUS_${status}`;\n}\n\nfunction mapToStoreCredit(payments?: OrderPayments): number {\n const item = find(payments, { providerId: 'storecredit' });\n\n return item ? item.amount : 0;\n}\n\nfunction mapToGiftCertificates(payments?: OrderPayments): InternalGiftCertificateList {\n const items = filter(payments, {\n providerId: 'giftcertificate',\n }) as GiftCertificateOrderPayment[];\n\n return {\n totalDiscountedAmount: reduce(items, (sum, item) => item.amount + sum, 0),\n appliedGiftCertificates: keyBy(\n items.map((item) => ({\n code: item.detail.code,\n discountedAmount: item.amount,\n remainingBalance: item.detail.remaining,\n giftCertificate: {\n balance: item.amount + item.detail.remaining,\n code: item.detail.code,\n purchaseDate: '',\n },\n })),\n 'code',\n ),\n };\n}\n\nfunction mapToInternalOrderPayment(\n payments?: OrderPayments,\n payment: InternalOrderPayment = {},\n): InternalOrderPayment {\n const item = find(payments, isDefaultOrderPayment) as GatewayOrderPayment;\n\n if (!item) {\n return {};\n }\n\n return {\n id: item.providerId,\n status: mapToInternalPaymentStatus(item.detail.step),\n helpText: item.detail.instructions,\n returnUrl: payment.returnUrl,\n };\n}\n\nfunction isDefaultOrderPayment(payment: OrderPayment): payment is GatewayOrderPayment {\n return payment.providerId !== 'giftcertificate' && payment.providerId !== 'storecredit';\n}\n\nfunction mapToInternalSocialDataList(\n order: Order,\n): { [itemId: string]: InternalSocialDataList } | undefined {\n const socialDataObject: { [itemId: string]: InternalSocialDataList } = {};\n const items = [...order.lineItems.physicalItems, ...order.lineItems.digitalItems];\n\n items.forEach((item) => {\n socialDataObject[item.id] = mapToInternalSocialData(item);\n });\n\n return socialDataObject;\n}\n\nfunction mapToInternalSocialData(lineItem: LineItem): InternalSocialDataList {\n const codes = ['fb', 'tw', 'gp'];\n\n return codes.reduce((socialData, code) => {\n const item =\n lineItem.socialMedia && find(lineItem.socialMedia, (item) => item.code === code);\n\n if (!item) {\n return socialData;\n }\n\n socialData[code] = {\n name: lineItem.name,\n description: lineItem.name,\n image: lineItem.imageUrl,\n url: item.link,\n shareText: item.text,\n sharingLink: item.link,\n channelName: item.channel,\n channelCode: item.code,\n };\n\n return socialData;\n }, {} as InternalSocialDataList);\n}\n","import InternalShippingOption from './internal-shipping-option';\nimport ShippingOption from './shipping-option';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalShippingOption(\n option: ShippingOption,\n isSelected: boolean,\n): InternalShippingOption {\n return {\n description: option.description,\n module: option.type,\n price: option.cost,\n id: option.id,\n selected: isSelected,\n isRecommended: option.isRecommended,\n imageUrl: option.imageUrl,\n transitTime: option.transitTime,\n };\n}\n","import { pick } from 'lodash';\n\nimport { Address, mapToInternalAddress } from '../address';\nimport { mapToInternalCart } from '../cart';\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { CheckoutButtonMethodType } from '../checkout-buttons/strategies';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { mapToInternalCustomer } from '../customer';\nimport { HostedFormOrderData } from '../hosted-form';\nimport {\n CardExpiryFormatter,\n CardNumberFormatter,\n HostedInputValues,\n} from '../hosted-form/iframe-content';\nimport { mapToInternalOrder } from '../order';\nimport { mapToInternalShippingOption } from '../shipping';\n\nimport isVaultedInstrument, { isFormattedVaultedInstrument } from './is-vaulted-instrument';\nimport Payment, {\n HostedCreditCardInstrument,\n HostedVaultedInstrument,\n PaymentInstrument,\n} from './payment';\nimport PaymentMethod from './payment-method';\nimport PaymentRequestBody from './payment-request-body';\n\nexport default class PaymentRequestTransformer {\n private _cardExpiryFormatter = new CardExpiryFormatter();\n private _cardNumberFormatter = new CardNumberFormatter();\n\n transform(payment: Payment, checkoutState: InternalCheckoutSelectors): PaymentRequestBody {\n const billingAddress = checkoutState.billingAddress.getBillingAddress();\n const checkout = checkoutState.checkout.getCheckout();\n const customer = checkoutState.customer.getCustomer();\n const order = checkoutState.order.getOrder();\n const paymentMethod = checkoutState.paymentMethods.getPaymentMethod(\n payment.methodId,\n payment.gatewayId,\n );\n const shippingAddress = this._mapShippingAddress(checkoutState, paymentMethod);\n const consignments = checkoutState.consignments.getConsignments();\n const shippingOption = checkoutState.consignments.getShippingOption();\n const storeConfig = checkoutState.config.getStoreConfig();\n const contextConfig = checkoutState.config.getContextConfig();\n const instrumentMeta = checkoutState.instruments.getInstrumentsMeta();\n const paymentMeta = checkoutState.paymentMethods.getPaymentMethodsMeta();\n const orderMeta = checkoutState.order.getOrderMeta();\n const internalCustomer =\n customer && billingAddress && mapToInternalCustomer(customer, billingAddress);\n\n const authToken =\n instrumentMeta &&\n payment.paymentData &&\n (isVaultedInstrument(payment.paymentData) ||\n isFormattedVaultedInstrument(payment.paymentData))\n ? `${checkoutState.payment.getPaymentToken()}, ${instrumentMeta.vaultAccessToken}`\n : checkoutState.payment.getPaymentToken();\n\n if (!authToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n return {\n additionalAction: payment.additionalAction,\n authToken,\n customer: internalCustomer,\n billingAddress: billingAddress && mapToInternalAddress(billingAddress),\n shippingAddress: shippingAddress && mapToInternalAddress(shippingAddress, consignments),\n shippingOption: shippingOption && mapToInternalShippingOption(shippingOption, true),\n cart: checkout && mapToInternalCart(checkout),\n order: order && mapToInternalOrder(order, orderMeta),\n orderMeta,\n payment: payment.paymentData,\n paymentMethod: paymentMethod && this._transformPaymentMethod(paymentMethod),\n quoteMeta: {\n request: {\n ...paymentMeta,\n geoCountryCode: contextConfig && contextConfig.geoCountryCode,\n },\n },\n source: 'bigcommerce-checkout-js-sdk',\n store: pick(storeConfig && storeConfig.storeProfile, [\n 'storeHash',\n 'storeId',\n 'storeLanguage',\n 'storeName',\n ]),\n };\n }\n\n transformWithHostedFormData(\n values: HostedInputValues,\n data: HostedFormOrderData,\n nonce: string,\n ): PaymentRequestBody {\n const {\n additionalAction,\n authToken,\n checkout,\n config,\n order,\n orderMeta,\n payment = {},\n paymentMethod,\n paymentMethodMeta,\n } = data;\n const consignment = checkout && checkout.consignments[0];\n const shippingAddress = consignment && consignment.shippingAddress;\n const shippingOption = consignment && consignment.selectedShippingOption;\n\n return {\n additionalAction,\n authToken,\n paymentMethod: paymentMethod && this._transformPaymentMethod(paymentMethod),\n customer:\n order &&\n order.billingAddress &&\n checkout &&\n mapToInternalCustomer(checkout.customer, order.billingAddress),\n billingAddress:\n order && order.billingAddress && mapToInternalAddress(order.billingAddress),\n shippingAddress:\n shippingAddress &&\n checkout &&\n mapToInternalAddress(shippingAddress, checkout.consignments),\n shippingOption: shippingOption && mapToInternalShippingOption(shippingOption, true),\n cart: checkout && mapToInternalCart(checkout),\n order: order && mapToInternalOrder(order, orderMeta),\n orderMeta,\n payment: this._transformHostedInputValues(values, payment, nonce),\n quoteMeta: {\n request: {\n ...paymentMethodMeta,\n geoCountryCode: config && config.context.geoCountryCode,\n },\n },\n source: 'bigcommerce-checkout-js-sdk',\n store:\n config &&\n pick(config.storeConfig.storeProfile, [\n 'storeHash',\n 'storeId',\n 'storeLanguage',\n 'storeName',\n ]),\n };\n }\n\n private _transformPaymentMethod(paymentMethod: PaymentMethod): PaymentMethod {\n if (paymentMethod.method === 'multi-option' && !paymentMethod.gateway) {\n return { ...paymentMethod, gateway: paymentMethod.id };\n }\n\n if (paymentMethod.initializationData && paymentMethod.initializationData.gateway) {\n return { ...paymentMethod, id: paymentMethod.initializationData.gateway };\n }\n\n if (paymentMethod.id === CheckoutButtonMethodType.BRAINTREE_VENMO) {\n return { ...paymentMethod, id: CheckoutButtonMethodType.BRAINTREE_PAYPAL };\n }\n\n return paymentMethod;\n }\n\n private _transformHostedInputValues(\n values: HostedInputValues,\n payment: HostedCreditCardInstrument | HostedVaultedInstrument,\n nonce: string,\n ): PaymentInstrument {\n return 'instrumentId' in payment\n ? {\n ...payment,\n ccCvv: values.cardCodeVerification,\n ccNumber:\n values.cardNumberVerification &&\n this._cardNumberFormatter.unformat(values.cardNumberVerification),\n hostedFormNonce: nonce,\n }\n : {\n ...payment,\n ccCvv: values.cardCode,\n ccExpiry: this._cardExpiryFormatter.toObject(values.cardExpiry || ''),\n ccName: values.cardName || '',\n ccNumber: this._cardNumberFormatter.unformat(values.cardNumber || ''),\n hostedFormNonce: nonce,\n };\n }\n\n private _mapShippingAddress(\n checkoutState: InternalCheckoutSelectors,\n paymentMethod?: PaymentMethod,\n ): Address | undefined {\n if (paymentMethod) {\n const isBopisEnabled = paymentMethod.initializationData?.bopis?.enabled;\n const requiredAddress = paymentMethod.initializationData?.bopis?.requiredAddress;\n const consignments = checkoutState.consignments.getConsignments();\n const isPickup = consignments?.every((consignment) => consignment.selectedPickupOption);\n\n if (isBopisEnabled && isPickup && requiredAddress === 'none') {\n return undefined;\n }\n }\n\n return checkoutState.shippingAddress.getShippingAddress();\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Checkout } from '../checkout';\n\nimport { ConsignmentMeta } from './consignment';\n\nexport enum ConsignmentActionType {\n CreateConsignmentsRequested = 'CREATE_CONSIGNMENTS_REQUESTED',\n CreateConsignmentsSucceeded = 'CREATE_CONSIGNMENTS_SUCCEEDED',\n CreateConsignmentsFailed = 'CREATE_CONSIGNMENTS_FAILED',\n\n UpdateConsignmentRequested = 'UPDATE_CONSIGNMENT_REQUESTED',\n UpdateConsignmentSucceeded = 'UPDATE_CONSIGNMENT_SUCCEEDED',\n UpdateConsignmentFailed = 'UPDATE_CONSIGNMENT_FAILED',\n\n DeleteConsignmentRequested = 'DELETE_CONSIGNMENT_REQUESTED',\n DeleteConsignmentSucceeded = 'DELETE_CONSIGNMENT_SUCCEEDED',\n DeleteConsignmentFailed = 'DELETE_CONSIGNMENT_FAILED',\n\n UpdateShippingOptionRequested = 'UPDATE_SHIPPING_OPTION_REQUESTED',\n UpdateShippingOptionSucceeded = 'UPDATE_SHIPPING_OPTION_SUCCEEDED',\n UpdateShippingOptionFailed = 'UPDATE_SHIPPING_OPTION_FAILED',\n\n LoadShippingOptionsRequested = 'LOAD_SHIPPING_OPTIONS_REQUESTED',\n LoadShippingOptionsSucceeded = 'LOAD_SHIPPING_OPTIONS_SUCCEEDED',\n LoadShippingOptionsFailed = 'LOAD_SHIPPING_OPTIONS_FAILED',\n}\n\nexport type ConsignmentAction =\n | CreateConsignmentsAction\n | UpdateConsignmentAction\n | DeleteConsignmentAction\n | UpdateShippingOptionAction\n | LoadShippingOptionsAction;\n\nexport type CreateConsignmentsAction =\n | CreateConsignmentsRequestedAction\n | CreateConsignmentsSucceededAction\n | CreateConsignmentsFailedAction;\n\nexport type UpdateConsignmentAction =\n | UpdateConsignmentRequestedAction\n | UpdateConsignmentSucceededAction\n | UpdateConsignmentFailedAction;\n\nexport type DeleteConsignmentAction =\n | DeleteConsignmentRequestedAction\n | DeleteConsignmentSucceededAction\n | DeleteConsignmentFailedAction;\n\nexport type UpdateShippingOptionAction =\n | UpdateShippingOptionRequestedAction\n | UpdateShippingOptionSucceededAction\n | UpdateShippingOptionFailedAction;\n\nexport type LoadShippingOptionsAction =\n | LoadShippingOptionsRequestedAction\n | LoadShippingOptionsSucceededAction\n | LoadShippingOptionsFailedAction;\n\nexport interface CreateConsignmentsRequestedAction extends Action {\n type: ConsignmentActionType.CreateConsignmentsRequested;\n}\n\nexport interface CreateConsignmentsSucceededAction extends Action {\n type: ConsignmentActionType.CreateConsignmentsSucceeded;\n}\n\nexport interface CreateConsignmentsFailedAction extends Action {\n type: ConsignmentActionType.CreateConsignmentsFailed;\n}\n\nexport interface UpdateConsignmentRequestedAction extends Action {\n type: ConsignmentActionType.UpdateConsignmentRequested;\n}\n\nexport interface UpdateConsignmentSucceededAction extends Action {\n type: ConsignmentActionType.UpdateConsignmentSucceeded;\n}\n\nexport interface UpdateConsignmentFailedAction extends Action {\n type: ConsignmentActionType.UpdateConsignmentFailed;\n}\n\nexport interface DeleteConsignmentRequestedAction extends Action {\n type: ConsignmentActionType.DeleteConsignmentRequested;\n}\n\nexport interface DeleteConsignmentSucceededAction extends Action {\n type: ConsignmentActionType.DeleteConsignmentSucceeded;\n}\n\nexport interface DeleteConsignmentFailedAction extends Action {\n type: ConsignmentActionType.DeleteConsignmentFailed;\n}\n\nexport interface UpdateShippingOptionRequestedAction extends Action {\n type: ConsignmentActionType.UpdateShippingOptionRequested;\n}\n\nexport interface UpdateShippingOptionSucceededAction extends Action {\n type: ConsignmentActionType.UpdateShippingOptionSucceeded;\n}\n\nexport interface UpdateShippingOptionFailedAction extends Action {\n type: ConsignmentActionType.UpdateShippingOptionFailed;\n}\n\nexport interface LoadShippingOptionsRequestedAction extends Action {\n type: ConsignmentActionType.LoadShippingOptionsRequested;\n}\n\nexport interface LoadShippingOptionsSucceededAction extends Action {\n type: ConsignmentActionType.LoadShippingOptionsSucceeded;\n}\n\nexport interface LoadShippingOptionsFailedAction extends Action {\n type: ConsignmentActionType.LoadShippingOptionsFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { find } from 'lodash';\nimport { Observable, Observer } from 'rxjs';\n\nimport { AddressRequestBody } from '../address';\nimport { Cart } from '../cart';\nimport {\n CheckoutIncludes,\n CheckoutParams,\n CheckoutRequestSender,\n InternalCheckoutSelectors,\n ReadableCheckoutStore,\n} from '../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\n\nimport Consignment, {\n ConsignmentAssignmentBaseRequestBodyWithAddress,\n ConsignmentAssignmentBaseRequestBodyWithShippingAddress,\n ConsignmentAssignmentRequestBody,\n ConsignmentCreateRequestBody,\n ConsignmentLineItem,\n ConsignmentRequestBody,\n ConsignmentShippingOptionRequestBody,\n ConsignmentsRequestBody,\n ConsignmentUpdateRequestBody,\n} from './consignment';\nimport {\n ConsignmentActionType,\n CreateConsignmentsAction,\n DeleteConsignmentAction,\n LoadShippingOptionsAction,\n UpdateConsignmentAction,\n UpdateShippingOptionAction,\n} from './consignment-actions';\nimport ConsignmentRequestSender from './consignment-request-sender';\n\nexport default class ConsignmentActionCreator {\n constructor(\n private _consignmentRequestSender: ConsignmentRequestSender,\n private _checkoutRequestSender: CheckoutRequestSender,\n ) {}\n\n unassignItemsByAddress(\n consignment: ConsignmentAssignmentRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const address = this._consignmentHasAddress(consignment)\n ? consignment.address\n : consignment.shippingAddress;\n\n const existingConsignment = state.consignments.getConsignmentByAddress(address);\n\n if (!existingConsignment) {\n throw new InvalidArgumentError('No consignment found for the specified address');\n }\n\n const lineItems = this._removeLineItems(\n consignment.lineItems,\n existingConsignment,\n state.cart.getCart(),\n );\n\n if (!lineItems.length) {\n return this.deleteConsignment(existingConsignment.id, options)(store);\n }\n\n return this.updateConsignment(\n {\n id: existingConsignment.id,\n address,\n lineItems,\n },\n options,\n )(store);\n };\n }\n\n assignItemsByAddress(\n consignment: ConsignmentAssignmentRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const state = store.getState();\n const address = this._consignmentHasAddress(consignment)\n ? consignment.address\n : consignment.shippingAddress;\n const existingConsignment = state.consignments.getConsignmentByAddress(address);\n\n return this._createOrUpdateConsignment(\n {\n id: existingConsignment && existingConsignment.id,\n address,\n lineItems: this._addLineItems(\n consignment.lineItems,\n existingConsignment,\n state.cart.getCart(),\n ),\n },\n options,\n )(store);\n };\n }\n\n selectShippingOption(\n id: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n const consignments = state.consignments.getConsignments();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!consignments || !consignments.length) {\n throw new MissingDataError(MissingDataErrorType.MissingConsignments);\n }\n\n const consignmentUpdateBody = {\n id: consignments[0].id,\n shippingOptionId: id,\n };\n\n const consignmentMeta = {\n id: consignments[0].id,\n };\n\n observer.next(\n createAction(\n ConsignmentActionType.UpdateShippingOptionRequested,\n undefined,\n consignmentMeta,\n ),\n );\n\n this._consignmentRequestSender\n .updateConsignment(checkout.id, consignmentUpdateBody, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n ConsignmentActionType.UpdateShippingOptionSucceeded,\n body,\n consignmentMeta,\n ),\n );\n\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ConsignmentActionType.UpdateShippingOptionFailed,\n response,\n consignmentMeta,\n ),\n );\n });\n });\n }\n\n loadShippingOptions(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const checkout = store.getState().checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(createAction(ConsignmentActionType.LoadShippingOptionsRequested));\n\n this._checkoutRequestSender\n .loadCheckout(checkout.id, {\n ...options,\n params: {\n include: [CheckoutIncludes.AvailableShippingOptions],\n },\n })\n .then(({ body }) => {\n observer.next(\n createAction(ConsignmentActionType.LoadShippingOptionsSucceeded, body),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ConsignmentActionType.LoadShippingOptionsFailed,\n response,\n ),\n );\n });\n });\n }\n\n updateAddress(\n address: AddressRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const consignment = this._getUpdateAddressRequestBody(address, store);\n const consignments = store.getState().consignments.getConsignments();\n\n if (consignments && consignments.length) {\n (consignment as ConsignmentUpdateRequestBody).id = consignments[0].id;\n }\n\n return this._createOrUpdateConsignment(consignment, options)(store);\n };\n }\n\n createConsignments(\n consignments: ConsignmentsRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const checkout = store.getState().checkout.getCheckout();\n\n if (!checkout || !checkout.id) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(createAction(ConsignmentActionType.CreateConsignmentsRequested));\n\n this._consignmentRequestSender\n .createConsignments(checkout.id, consignments, options)\n .then(({ body }) => {\n observer.next(\n createAction(ConsignmentActionType.CreateConsignmentsSucceeded, body),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ConsignmentActionType.CreateConsignmentsFailed,\n response,\n ),\n );\n });\n });\n }\n\n updateConsignment(\n consignment: ConsignmentUpdateRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const checkout = store.getState().checkout.getCheckout();\n\n if (!checkout || !checkout.id) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const consignmentMeta = { id: consignment.id };\n\n observer.next(\n createAction(\n ConsignmentActionType.UpdateConsignmentRequested,\n undefined,\n consignmentMeta,\n ),\n );\n\n this._consignmentRequestSender\n .updateConsignment(checkout.id, consignment, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n ConsignmentActionType.UpdateConsignmentSucceeded,\n body,\n consignmentMeta,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ConsignmentActionType.UpdateConsignmentFailed,\n response,\n consignmentMeta,\n ),\n );\n });\n });\n }\n\n deleteConsignment(\n consignmentId: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const checkout = store.getState().checkout.getCheckout();\n const consignmentMeta = { id: consignmentId };\n\n if (!checkout || !checkout.id) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(\n createAction(\n ConsignmentActionType.DeleteConsignmentRequested,\n undefined,\n consignmentMeta,\n ),\n );\n\n this._consignmentRequestSender\n .deleteConsignment(checkout.id, consignmentId, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n ConsignmentActionType.DeleteConsignmentSucceeded,\n body,\n consignmentMeta,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ConsignmentActionType.DeleteConsignmentFailed,\n response,\n consignmentMeta,\n ),\n );\n });\n });\n }\n\n updateShippingOption(\n consignment: ConsignmentShippingOptionRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const checkout = store.getState().checkout.getCheckout();\n\n if (!checkout || !checkout.id) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const consignmentMeta = { id: consignment.id };\n\n observer.next(\n createAction(\n ConsignmentActionType.UpdateShippingOptionRequested,\n undefined,\n consignmentMeta,\n ),\n );\n\n this._consignmentRequestSender\n .updateConsignment(checkout.id, consignment, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n ConsignmentActionType.UpdateShippingOptionSucceeded,\n body,\n consignmentMeta,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ConsignmentActionType.UpdateShippingOptionFailed,\n response,\n consignmentMeta,\n ),\n );\n });\n });\n }\n\n private _createOrUpdateConsignment(\n consignment: ConsignmentCreateRequestBody | ConsignmentUpdateRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const checkout = store.getState().checkout.getCheckout();\n\n if (!checkout || !checkout.id) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (this._isUpdateConsignmentRequest(consignment)) {\n return this.updateConsignment(consignment, options)(store);\n }\n\n return this.createConsignments([consignment], options)(store);\n };\n }\n\n private _getUpdateAddressRequestBody(\n address: AddressRequestBody,\n store: ReadableCheckoutStore,\n ): ConsignmentRequestBody {\n const state = store.getState();\n const cart = state.cart.getCart();\n\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n const { physicalItems, customItems = [] } = cart.lineItems;\n\n return {\n address,\n lineItems: [...physicalItems, ...customItems].map((item) => ({\n itemId: item.id,\n quantity: item.quantity,\n })),\n };\n }\n\n private _removeLineItems(\n lineItems: ConsignmentLineItem[],\n consignment: Consignment,\n cart?: Cart,\n ): ConsignmentLineItem[] {\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n return this._hydrateLineItems(consignment.lineItemIds, cart)\n .map((existingItem) => {\n const sharedItem = find(\n lineItems,\n (lineItem) => lineItem.itemId === existingItem.itemId,\n );\n\n return {\n ...existingItem,\n quantity: sharedItem\n ? existingItem.quantity - sharedItem.quantity\n : existingItem.quantity,\n };\n })\n .filter((lineItem) => lineItem.quantity > 0);\n }\n\n private _addLineItems(\n lineItems: ConsignmentLineItem[],\n consignment?: Consignment,\n cart?: Cart,\n ): ConsignmentLineItem[] {\n if (!consignment) {\n return lineItems;\n }\n\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n return lineItems\n .concat(this._hydrateLineItems(consignment.lineItemIds, cart))\n .filter((lineItem) => lineItem.quantity > 0);\n }\n\n private _hydrateLineItems(lineItemIds: string[], cart: Cart): ConsignmentLineItem[] {\n return lineItemIds.map((itemId) => {\n const item = find(cart.lineItems.physicalItems, (lineItem) => lineItem.id === itemId);\n\n return {\n itemId,\n quantity: item ? item.quantity : 0,\n };\n });\n }\n\n private _isUpdateConsignmentRequest(\n request: ConsignmentRequestBody,\n ): request is ConsignmentUpdateRequestBody {\n const updateRequest = request as ConsignmentUpdateRequestBody;\n\n return !!updateRequest.id;\n }\n\n private _consignmentHasAddress(\n consignment:\n | ConsignmentAssignmentBaseRequestBodyWithAddress\n | ConsignmentAssignmentBaseRequestBodyWithShippingAddress,\n ): consignment is ConsignmentAssignmentBaseRequestBodyWithAddress {\n return typeof consignment === 'object' && 'address' in consignment;\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Checkout, CheckoutParams } from '../checkout';\nimport {\n ContentType,\n joinIncludes,\n joinOrMergeIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport { ConsignmentsRequestBody, ConsignmentUpdateRequestBody } from './consignment';\n\nconst DEFAULT_INCLUDES = [\n 'consignments.availableShippingOptions',\n 'cart.lineItems.physicalItems.options',\n 'cart.lineItems.digitalItems.options',\n 'customer',\n 'promotions.banners',\n];\n\nexport default class ConsignmentRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n createConsignments(\n checkoutId: string,\n consignments: ConsignmentsRequestBody,\n { timeout, params: { include } = {} }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/consignments`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, {\n body: consignments,\n params: {\n include: joinOrMergeIncludes(DEFAULT_INCLUDES, include),\n },\n headers,\n timeout,\n });\n }\n\n updateConsignment(\n checkoutId: string,\n consignment: ConsignmentUpdateRequestBody,\n { timeout, params: { include } = {} }: RequestOptions = {},\n ): Promise> {\n const { id, ...body } = consignment;\n const url = `/api/storefront/checkouts/${checkoutId}/consignments/${id}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.put(url, {\n body,\n params: {\n include: joinOrMergeIncludes(DEFAULT_INCLUDES, include),\n },\n headers,\n timeout,\n });\n }\n\n deleteConsignment(\n checkoutId: string,\n consignmentId: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/consignments/${consignmentId}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n const include = joinIncludes(DEFAULT_INCLUDES);\n\n return this._requestSender.delete(url, { params: { include }, headers, timeout });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Checkout } from '../checkout';\n\nexport enum SpamProtectionActionType {\n InitializeFailed = 'SPAM_PROTECTION_INITIALIZE_FAILED',\n InitializeSucceeded = 'SPAM_PROTECTION_INITIALIZE_SUCCEEDED',\n InitializeRequested = 'SPAM_PROTECTION_INITIALIZE_REQUESTED',\n VerifyCheckoutRequested = 'SPAM_PROTECTION_CHECKOUT_VERIFY_REQUESTED',\n VerifyCheckoutSucceeded = 'SPAM_PROTECTION_CHECKOUT_VERIFY_SUCCEEDED',\n VerifyCheckoutFailed = 'SPAM_PROTECTION_CHECKOUT_VERIFY_FAILED',\n ExecuteRequested = 'SPAM_PROTECTION_EXECUTE_REQUESTED',\n ExecuteSucceeded = 'SPAM_PROTECTION_EXECUTE_SUCCEEDED',\n ExecuteFailed = 'SPAM_PROTECTION_EXECUTE_FAILED',\n}\n\nexport type SpamProtectionAction =\n | InitializeRequestedAction\n | InitializeSucceededAction\n | InitializeFailedAction\n | ExecuteRequestedAction\n | ExecuteSucceededAction\n | ExecuteFailedAction\n | CheckoutVerifyRequestedAction\n | CheckoutVerifyFailedAction\n | CheckoutVerifySucceededAction;\n\nexport interface InitializeRequestedAction extends Action {\n type: SpamProtectionActionType.InitializeRequested;\n}\n\nexport interface InitializeSucceededAction extends Action {\n type: SpamProtectionActionType.InitializeSucceeded;\n}\n\nexport interface InitializeFailedAction extends Action {\n type: SpamProtectionActionType.InitializeFailed;\n}\n\nexport interface ExecuteRequestedAction extends Action {\n type: SpamProtectionActionType.ExecuteRequested;\n}\n\nexport interface ExecuteSucceededAction extends Action<{ token: string }> {\n type: SpamProtectionActionType.ExecuteSucceeded;\n}\n\nexport interface ExecuteFailedAction extends Action {\n type: SpamProtectionActionType.ExecuteFailed;\n}\n\nexport interface CheckoutVerifyRequestedAction extends Action {\n type: SpamProtectionActionType.VerifyCheckoutRequested;\n}\n\nexport interface CheckoutVerifyFailedAction extends Action {\n type: SpamProtectionActionType.VerifyCheckoutFailed;\n}\n\nexport interface CheckoutVerifySucceededAction extends Action {\n type: SpamProtectionActionType.VerifyCheckoutSucceeded;\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, from, of } from 'rxjs';\nimport { catchError, switchMap, take } from 'rxjs/operators';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\n\nimport { SpamProtectionChallengeNotCompletedError, SpamProtectionFailedError } from './errors';\nimport GoogleRecaptcha from './google-recaptcha';\nimport isSpamProtectionExecuteSucceededAction from './is-spam-protection-succeeded-action';\nimport { SpamProtectionAction, SpamProtectionActionType } from './spam-protection-actions';\nimport { SpamProtectionOptions } from './spam-protection-options';\nimport SpamProtectionRequestSender from './spam-protection-request-sender';\n\nexport default class SpamProtectionActionCreator {\n constructor(\n private _googleRecaptcha: GoogleRecaptcha,\n private _requestSender: SpamProtectionRequestSender,\n ) {}\n\n initialize(\n options?: SpamProtectionOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(SpamProtectionActionType.InitializeRequested, undefined)),\n defer(async () => {\n const spamProtectionElementId = options\n ? options.containerId\n : 'spamProtectionContainer';\n\n if (!options && !document.getElementById(spamProtectionElementId)) {\n const spamProtectionElement = document.createElement('div');\n\n spamProtectionElement.setAttribute('id', spamProtectionElementId);\n document.body.appendChild(spamProtectionElement);\n }\n\n const state = store.getState();\n const storeConfig = state.config.getStoreConfigOrThrow();\n const recaptchaSitekey = storeConfig.checkoutSettings.googleRecaptchaSitekey;\n\n await this._googleRecaptcha.load(spamProtectionElementId, recaptchaSitekey);\n\n return createAction(SpamProtectionActionType.InitializeSucceeded);\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(SpamProtectionActionType.InitializeFailed, error),\n ),\n );\n }\n\n verifyCheckoutSpamProtection(): ThunkAction {\n return (store) =>\n defer(() => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n return concat(\n of(createAction(SpamProtectionActionType.VerifyCheckoutRequested)),\n from(this.execute()(store)).pipe(\n switchMap((action) => {\n if (\n !isSpamProtectionExecuteSucceededAction(action) ||\n !action.payload\n ) {\n return of(action);\n }\n\n return from(\n this._requestSender.validate(checkout.id, action.payload.token),\n ).pipe(\n switchMap(({ body }) =>\n concat(\n of(action),\n of(\n createAction(\n SpamProtectionActionType.VerifyCheckoutSucceeded,\n body,\n ),\n ),\n ),\n ),\n );\n }),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(SpamProtectionActionType.VerifyCheckoutFailed, error),\n ),\n );\n });\n }\n\n execute(): ThunkAction {\n return (store) =>\n concat(\n of(createAction(SpamProtectionActionType.ExecuteRequested)),\n this.initialize()(store),\n this._googleRecaptcha\n .execute()\n .pipe(take(1))\n .pipe(\n switchMap(async ({ error, token }) => {\n if (error instanceof SpamProtectionChallengeNotCompletedError) {\n throw error;\n }\n\n if (error || !token) {\n throw new SpamProtectionFailedError();\n }\n\n return createAction(SpamProtectionActionType.ExecuteSucceeded, {\n token,\n });\n }),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(SpamProtectionActionType.ExecuteFailed, error),\n ),\n );\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Checkout } from '../checkout';\nimport { ContentType, RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nexport default class SpamProtectionRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n validate(\n checkoutId: string,\n token: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/spam-protection`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, { body: { token }, headers, timeout });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Checkout } from '../checkout';\nimport { RequestError } from '../common/error/errors';\n\nexport enum StoreCreditActionType {\n ApplyStoreCreditRequested = 'APPLY_STORE_CREDIT_REQUESTED',\n ApplyStoreCreditSucceeded = 'APPLY_STORE_CREDIT_SUCCEEDED',\n ApplyStoreCreditFailed = 'APPLY_STORE_CREDIT_FAILED',\n}\n\nexport type StoreCreditAction = ApplyStoreCreditAction;\n\nexport type ApplyStoreCreditAction =\n | ApplyStoreCreditRequestedAction\n | ApplyStoreCreditSucceededAction\n | ApplyStoreCreditFailedAction;\n\nexport interface ApplyStoreCreditRequestedAction extends Action {\n type: StoreCreditActionType.ApplyStoreCreditRequested;\n}\n\nexport interface ApplyStoreCreditSucceededAction extends Action {\n type: StoreCreditActionType.ApplyStoreCreditSucceeded;\n}\n\nexport interface ApplyStoreCreditFailedAction\n extends Action> {\n type: StoreCreditActionType.ApplyStoreCreditFailed;\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\n\nimport { StoreCreditAction, StoreCreditActionType } from './store-credit-actions';\nimport StoreCreditRequestSender from './store-credit-request-sender';\n\nexport default class StoreCreditActionCreator {\n constructor(private _storeCreditRequestSender: StoreCreditRequestSender) {}\n\n applyStoreCredit(\n useStoreCredit: boolean,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(StoreCreditActionType.ApplyStoreCreditRequested)),\n defer(async () => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const { body } = await (useStoreCredit\n ? this._storeCreditRequestSender.applyStoreCredit(checkout.id, options)\n : this._storeCreditRequestSender.removeStoreCredit(checkout.id, options));\n\n return createAction(StoreCreditActionType.ApplyStoreCreditSucceeded, body);\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(StoreCreditActionType.ApplyStoreCreditFailed, error),\n ),\n );\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Checkout, CHECKOUT_DEFAULT_INCLUDES } from '../checkout';\nimport {\n ContentType,\n joinIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nexport default class StoreCreditRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n applyStoreCredit(\n checkoutId: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/store-credit`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n },\n });\n }\n\n removeStoreCredit(\n checkoutId: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/store-credit`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.delete(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n },\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Subscriptions } from './subscriptions';\n\nexport enum SubscriptionsActionType {\n UpdateSubscriptionsRequested = 'UPDATE_SUBSCRIPTIONS_REQUESTED',\n UpdateSubscriptionsSucceeded = 'UPDATE_SUBSCRIPTIONS_SUCCEEDED',\n UpdateSubscriptionsFailed = 'UPDATE_SUBSCRIPTIONS_FAILED',\n}\nexport type UpdateSubscriptionsAction =\n | UpdateSubscriptionsRequestedAction\n | UpdateSubscriptionsSucceededAction\n | UpdateSubscriptionsFailedAction;\n\nexport interface UpdateSubscriptionsRequestedAction extends Action {\n type: SubscriptionsActionType.UpdateSubscriptionsRequested;\n}\n\nexport interface UpdateSubscriptionsSucceededAction extends Action {\n type: SubscriptionsActionType.UpdateSubscriptionsSucceeded;\n}\n\nexport interface UpdateSubscriptionsFailedAction extends Action {\n type: SubscriptionsActionType.UpdateSubscriptionsFailed;\n}\n","import { RequestError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when the subscriptions fails to be updated\n */\nexport default class UpdateSubscriptionsError extends RequestError {\n constructor(response?: Response) {\n super(response);\n\n this.name = 'UpdateSubscriptionsError';\n this.type = 'update_subscriptions';\n }\n}\n","import { createAction } from '@bigcommerce/data-store';\nimport { concat, defer, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { throwErrorAction } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\nimport {\n Subscriptions,\n SubscriptionsActionType,\n SubscriptionsRequestSender,\n UpdateSubscriptionsAction,\n} from '../subscription';\n\nimport { UpdateSubscriptionsError } from './errors';\n\nexport default class SubscriptionsActionCreator {\n constructor(private _subscriptionsRequestSender: SubscriptionsRequestSender) {}\n\n updateSubscriptions(\n subscriptions: Subscriptions,\n options?: RequestOptions,\n ): Observable {\n return concat(\n of(createAction(SubscriptionsActionType.UpdateSubscriptionsRequested)),\n defer(async () => {\n const { body } = await this._subscriptionsRequestSender.updateSubscriptions(\n subscriptions,\n options,\n );\n\n return createAction(SubscriptionsActionType.UpdateSubscriptionsSucceeded, body);\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(\n SubscriptionsActionType.UpdateSubscriptionsFailed,\n new UpdateSubscriptionsError(error),\n ),\n ),\n );\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { ContentType, RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nimport { Subscriptions } from './subscriptions';\n\nexport default class SubscriptionsRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n updateSubscriptions(\n subscriptions: Subscriptions,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = '/api/storefront/subscriptions';\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, { body: subscriptions, headers, timeout });\n }\n}\n","import { isPlainObject as lodashIsPlainObject } from 'lodash';\n\n// We need this wrapper because Lodash's version doesn't act as a type guard\nexport default function isPlainObject(value: any): value is object {\n return lodashIsPlainObject(value);\n}\n","import { memoize } from 'lodash';\n\nimport isPlainObject from './is-plain-object';\n\nconst cloneDeep = memoize((input: T): T => {\n if (Array.isArray(input)) {\n // Fixed in later versions of typescript https://github.com/microsoft/TypeScript/issues/36390\n return (input as any[]).map((value: T[keyof T]) => cloneDeepSafe(value)) as any;\n }\n\n if (isPlainObject(input)) {\n return (Object.keys(input) as Array).reduce(\n (result, key) => ({\n ...result,\n [key]: cloneDeepSafe(input[key]),\n }),\n {},\n ) as T;\n }\n\n return input;\n});\n\n// Use WeakMap as the MapCache, this allows for better garbage collection\n// There's a deprecated `clear` method in the lodash implementation\n// of MapCache, hence the `any`\ncloneDeep.cache = new WeakMap() as any;\n\n/**\n * This is a wrapper function for `cloneDeep`. We need it because `cloneDeep` is\n * a memoized function using an instance of `WeakMap` as its cache. Without this\n * wrapper, the memoized function will throw an error if it is called with a\n * non-object argument.\n */\nconst cloneDeepSafe = (input: T): T => {\n return typeof input === 'object' && input !== null ? cloneDeep(input) : input;\n};\n\n/**\n * Clone the return value of a function. If the result is the same as previous\n * calls, return the previous clone instead of cloning it again.\n */\nexport default function cloneResult(fn: T): T {\n return ((...args: any[]) => cloneDeepSafe(fn(...args))) as T;\n}\n\nexport type Func = (...args: any[]) => any;\n","import { PaymentIntegrationSelectors } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { cloneResult as clone } from '../common/utility';\n\nexport default function createPaymentIntegrationSelectors({\n billingAddress: { getBillingAddress, getBillingAddressOrThrow },\n cart: { getCart, getCartOrThrow },\n checkout: { getCheckout, getCheckoutOrThrow },\n config: { getHost, getLocale, getStoreConfig, getStoreConfigOrThrow },\n consignments: { getConsignments, getConsignmentsOrThrow },\n customer: { getCustomer, getCustomerOrThrow },\n instruments: { getCardInstrument, getCardInstrumentOrThrow },\n order: { getOrder, getOrderOrThrow },\n payment: {\n getPaymentToken,\n getPaymentTokenOrThrow,\n getPaymentId,\n getPaymentIdOrThrow,\n getPaymentStatus,\n getPaymentStatusOrThrow,\n getPaymentRedirectUrl,\n getPaymentRedirectUrlOrThrow,\n isPaymentDataRequired,\n },\n paymentMethods: { getPaymentMethod, getPaymentMethodOrThrow },\n paymentStrategies: { isInitialized: isPaymentMethodInitialized },\n shippingAddress: {\n getShippingAddress,\n getShippingAddressOrThrow,\n getShippingAddresses,\n getShippingAddressesOrThrow,\n },\n}: InternalCheckoutSelectors): PaymentIntegrationSelectors {\n return {\n getHost: clone(getHost),\n getLocale: clone(getLocale),\n getBillingAddress: clone(getBillingAddress),\n getBillingAddressOrThrow: clone(getBillingAddressOrThrow),\n getCart: clone(getCart),\n getCartOrThrow: clone(getCartOrThrow),\n getCheckout: clone(getCheckout),\n getCheckoutOrThrow: clone(getCheckoutOrThrow),\n getStoreConfig: clone(getStoreConfig),\n getStoreConfigOrThrow: clone(getStoreConfigOrThrow),\n getConsignments: clone(getConsignments),\n getConsignmentsOrThrow: clone(getConsignmentsOrThrow),\n getCustomer: clone(getCustomer),\n getCustomerOrThrow: clone(getCustomerOrThrow),\n getCardInstrument: clone(getCardInstrument),\n getCardInstrumentOrThrow: clone(getCardInstrumentOrThrow),\n getOrder: clone(getOrder),\n getOrderOrThrow: clone(getOrderOrThrow),\n getPaymentToken,\n getPaymentTokenOrThrow,\n getPaymentId,\n getPaymentIdOrThrow,\n getPaymentStatus,\n getPaymentStatusOrThrow,\n getPaymentRedirectUrl,\n getPaymentRedirectUrlOrThrow,\n getPaymentMethod: clone(getPaymentMethod),\n getPaymentMethodOrThrow: clone(getPaymentMethodOrThrow),\n getShippingAddress: clone(getShippingAddress),\n getShippingAddressOrThrow: clone(getShippingAddressOrThrow),\n getShippingAddresses: clone(getShippingAddresses),\n getShippingAddressesOrThrow: clone(getShippingAddressesOrThrow),\n isPaymentDataRequired,\n isPaymentMethodInitialized,\n };\n}\n","import {\n BillingAddressRequestBody,\n BuyNowCartRequestBody,\n Cart,\n HostedForm,\n HostedFormOptions,\n InitializeOffsitePaymentConfig,\n OrderRequestBody,\n Payment,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n RequestOptions,\n ShippingAddressRequestBody,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BillingAddressActionCreator } from '../billing';\nimport { CartRequestSender } from '../cart';\nimport { CheckoutActionCreator, CheckoutStore } from '../checkout';\nimport { DataStoreProjection } from '../common/data-store';\nimport { CustomerActionCreator, CustomerCredentials } from '../customer';\nimport { HostedFormFactory } from '../hosted-form';\nimport { OrderActionCreator } from '../order';\nimport PaymentActionCreator from '../payment/payment-action-creator';\nimport PaymentMethodActionCreator from '../payment/payment-method-action-creator';\nimport { ConsignmentActionCreator } from '../shipping';\nimport { SpamProtectionActionCreator } from '../spam-protection';\nimport { StoreCreditActionCreator } from '../store-credit';\n\nimport PaymentIntegrationStoreProjectionFactory from './payment-integration-store-projection-factory';\n\nexport default class DefaultPaymentIntegrationService implements PaymentIntegrationService {\n private _storeProjection: DataStoreProjection;\n\n constructor(\n private _store: CheckoutStore,\n private _storeProjectionFactory: PaymentIntegrationStoreProjectionFactory,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _hostedFormFactory: HostedFormFactory,\n private _orderActionCreator: OrderActionCreator,\n private _billingAddressActionCreator: BillingAddressActionCreator,\n private _consignmentActionCreator: ConsignmentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _customerActionCreator: CustomerActionCreator,\n private _cartRequestSender: CartRequestSender,\n private _storeCreditActionCreator: StoreCreditActionCreator,\n private _spamProtectionActionCreator: SpamProtectionActionCreator,\n ) {\n this._storeProjection = this._storeProjectionFactory.create(this._store);\n }\n\n createHostedForm(host: string, options: HostedFormOptions): HostedForm {\n return this._hostedFormFactory.create(host, options);\n }\n\n subscribe(\n subscriber: (state: PaymentIntegrationSelectors) => void,\n ...filters: Array<(state: PaymentIntegrationSelectors) => unknown>\n ): () => void {\n return this._storeProjection.subscribe(subscriber, ...filters);\n }\n\n getState(): PaymentIntegrationSelectors {\n return this._storeProjection.getState();\n }\n\n async initializeOffsitePayment(\n initializeOffsitePaymentConfig: InitializeOffsitePaymentConfig,\n ): Promise {\n await this._store.dispatch(\n this._paymentActionCreator.initializeOffsitePayment(initializeOffsitePaymentConfig),\n );\n\n return this._storeProjection.getState();\n }\n\n async loadCheckout(id?: string): Promise {\n if (id) {\n await this._store.dispatch(this._checkoutActionCreator.loadCheckout(id));\n } else {\n await this._store.dispatch(this._checkoutActionCreator.loadCurrentCheckout());\n }\n\n return this._storeProjection.getState();\n }\n\n async loadDefaultCheckout(): Promise {\n await this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout());\n\n return this._storeProjection.getState();\n }\n\n async loadPaymentMethod(\n methodId: string,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async submitOrder(\n payload?: OrderRequestBody,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(this._orderActionCreator.submitOrder(payload, options));\n\n return this._storeProjection.getState();\n }\n\n async submitPayment(payment: Payment): Promise {\n await this._store.dispatch(this._paymentActionCreator.submitPayment(payment));\n\n return this._storeProjection.getState();\n }\n\n async finalizeOrder(options?: RequestOptions): Promise {\n const {\n order: { getOrderOrThrow },\n } = this._store.getState();\n\n await this._store.dispatch(\n this._orderActionCreator.finalizeOrder(getOrderOrThrow().orderId, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async updateBillingAddress(\n payload: BillingAddressRequestBody,\n ): Promise {\n await this._store.dispatch(this._billingAddressActionCreator.updateAddress(payload));\n\n return this._storeProjection.getState();\n }\n\n async updateShippingAddress(\n payload: ShippingAddressRequestBody,\n ): Promise {\n await this._store.dispatch(this._consignmentActionCreator.updateAddress(payload));\n\n return this._storeProjection.getState();\n }\n\n async selectShippingOption(\n id: string,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(\n this._consignmentActionCreator.selectShippingOption(id, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async signInCustomer(\n credentials: CustomerCredentials,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(\n this._customerActionCreator.signInCustomer(credentials, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async signOutCustomer(options?: RequestOptions): Promise {\n await this._store.dispatch(this._customerActionCreator.signOutCustomer(options));\n\n return this._storeProjection.getState();\n }\n\n async createBuyNowCart(\n buyNowCartRequestBody: BuyNowCartRequestBody,\n options?: RequestOptions,\n ): Promise {\n const { body: buyNowCart } = await this._cartRequestSender.createBuyNowCart(\n buyNowCartRequestBody,\n options,\n );\n\n return buyNowCart;\n }\n\n async applyStoreCredit(\n useStoreCredit: boolean,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(\n this._storeCreditActionCreator.applyStoreCredit(useStoreCredit, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async verifyCheckoutSpamProtection(): Promise {\n const { checkout } = this._store.getState();\n const { shouldExecuteSpamCheck } = checkout.getCheckoutOrThrow();\n\n if (shouldExecuteSpamCheck) {\n await this._store.dispatch(\n this._spamProtectionActionCreator.verifyCheckoutSpamProtection(),\n );\n }\n\n return this._storeProjection.getState();\n }\n}\n","import { Action, createAction, createDataStore, ReadableDataStore } from '@bigcommerce/data-store';\n\nenum ProjectionActionType {\n Synchronize = 'SYNCHRONIZE',\n}\n\ninterface SynchronizeAction extends Action {\n type: ProjectionActionType.Synchronize;\n payload: TState;\n}\n\nexport interface DataStoreProjection\n extends ReadableDataStore {\n notifyState(): void;\n}\n\nexport default function createDataStoreProjection(\n store: ReadableDataStore,\n stateTransformer: (state: TState) => TTransformedState,\n): DataStoreProjection {\n const projection = createDataStore<\n TState | undefined,\n SynchronizeAction,\n TTransformedState\n >(\n (state, action) =>\n action.type === ProjectionActionType.Synchronize ? action.payload : state,\n store.getState(),\n { stateTransformer },\n );\n\n store.subscribe(\n (state) => {\n projection.dispatch(\n createAction(ProjectionActionType.Synchronize, state) as SynchronizeAction,\n );\n },\n { initial: false },\n );\n\n return projection;\n}\n","import { PaymentIntegrationSelectors } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { InternalCheckoutSelectors, ReadableCheckoutStore } from '../checkout';\nimport { createDataStoreProjection, DataStoreProjection } from '../common/data-store';\n\nexport default class PaymentIntegrationStoreProjectionFactory {\n constructor(\n private _transformSelectors: (\n selectors: InternalCheckoutSelectors,\n ) => PaymentIntegrationSelectors,\n ) {}\n\n create(store: ReadableCheckoutStore): DataStoreProjection {\n return createDataStoreProjection(store, this._transformSelectors);\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { createScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BillingAddressActionCreator, BillingAddressRequestSender } from '../billing';\nimport { CartRequestSender } from '../cart';\nimport {\n CheckoutActionCreator,\n CheckoutRequestSender,\n CheckoutStore,\n CheckoutValidator,\n} from '../checkout';\nimport { ConfigActionCreator, ConfigRequestSender } from '../config';\nimport { CustomerActionCreator, CustomerRequestSender } from '../customer';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport { HostedFormFactory } from '../hosted-form';\nimport { OrderActionCreator, OrderRequestSender } from '../order';\nimport {\n createPaymentClient,\n PaymentActionCreator,\n PaymentMethodActionCreator,\n PaymentMethodRequestSender,\n PaymentRequestSender,\n PaymentRequestTransformer,\n} from '../payment';\nimport { ConsignmentActionCreator, ConsignmentRequestSender } from '../shipping';\nimport {\n createSpamProtection,\n PaymentHumanVerificationHandler,\n SpamProtectionActionCreator,\n SpamProtectionRequestSender,\n} from '../spam-protection';\nimport { StoreCreditActionCreator, StoreCreditRequestSender } from '../store-credit';\nimport { SubscriptionsActionCreator, SubscriptionsRequestSender } from '../subscription';\n\nimport createPaymentIntegrationSelectors from './create-payment-integration-selectors';\nimport DefaultPaymentIntegrationService from './default-payment-integration-service';\nimport PaymentIntegrationStoreProjectionFactory from './payment-integration-store-projection-factory';\n\nexport default function createPaymentIntegrationService(\n store: CheckoutStore,\n): PaymentIntegrationService {\n const {\n config: { getHost },\n } = store.getState();\n\n const requestSender = createRequestSender({ host: getHost() });\n\n const storeProjectionFactory = new PaymentIntegrationStoreProjectionFactory(\n createPaymentIntegrationSelectors,\n );\n\n const checkoutActionCreator = new CheckoutActionCreator(\n new CheckoutRequestSender(requestSender),\n new ConfigActionCreator(new ConfigRequestSender(requestSender)),\n new FormFieldsActionCreator(new FormFieldsRequestSender(requestSender)),\n );\n\n const hostedFormFactory = new HostedFormFactory(store);\n\n const orderActionCreator = new OrderActionCreator(\n new OrderRequestSender(requestSender),\n new CheckoutValidator(new CheckoutRequestSender(requestSender)),\n );\n\n const billingAddressActionCreator = new BillingAddressActionCreator(\n new BillingAddressRequestSender(requestSender),\n new SubscriptionsActionCreator(new SubscriptionsRequestSender(requestSender)),\n );\n\n const consignmentActionCreator = new ConsignmentActionCreator(\n new ConsignmentRequestSender(requestSender),\n new CheckoutRequestSender(requestSender),\n );\n\n const paymentMethodActionCreator = new PaymentMethodActionCreator(\n new PaymentMethodRequestSender(requestSender),\n );\n\n const paymentActionCreator = new PaymentActionCreator(\n new PaymentRequestSender(createPaymentClient(store)),\n orderActionCreator,\n new PaymentRequestTransformer(),\n new PaymentHumanVerificationHandler(createSpamProtection(createScriptLoader())),\n );\n\n const customerActionCreator = new CustomerActionCreator(\n new CustomerRequestSender(requestSender),\n checkoutActionCreator,\n new SpamProtectionActionCreator(\n createSpamProtection(createScriptLoader()),\n new SpamProtectionRequestSender(requestSender),\n ),\n );\n\n const storeCreditActionCreator = new StoreCreditActionCreator(\n new StoreCreditRequestSender(requestSender),\n );\n\n const spamProtection = createSpamProtection(createScriptLoader());\n const spamProtectionRequestSender = new SpamProtectionRequestSender(requestSender);\n const spamProtectionActionCreator = new SpamProtectionActionCreator(\n spamProtection,\n spamProtectionRequestSender,\n );\n\n const cartRequestSender = new CartRequestSender(requestSender);\n\n return new DefaultPaymentIntegrationService(\n store,\n storeProjectionFactory,\n checkoutActionCreator,\n hostedFormFactory,\n orderActionCreator,\n billingAddressActionCreator,\n consignmentActionCreator,\n paymentMethodActionCreator,\n paymentActionCreator,\n customerActionCreator,\n cartRequestSender,\n storeCreditActionCreator,\n spamProtectionActionCreator,\n );\n}\n","import { Cart } from '../cart';\n\nimport getLineItemsCount from './getLineItemsCount';\n\nexport default function getShippableItemsCount(cart: Cart): number {\n return getLineItemsCount(cart.lineItems.physicalItems.filter((item) => !item.addedByPromotion));\n}\n","import { reduce } from 'lodash';\n\nimport { LineItem } from '../cart';\n\nexport default function getLineItemsCount(lineItems: LineItem[]): number {\n return reduce(lineItems, (total, item) => total + item.quantity, 0);\n}\n","export default function guard(value: T, errorFactory?: () => Error): NonNullable {\n if (value === undefined || value === null) {\n throw errorFactory ? errorFactory() : new Error('An unexpected error has occurred.');\n }\n\n return value as NonNullable;\n}\n","import { InternalCheckoutSelectors } from '../../../../../core/src/checkout';\n\nexport type EnvironmentType = 'PRODUCTION' | 'TEST';\n\nexport interface AmazonPayV2Options {\n environment: EnvironmentType;\n}\n\nexport interface AmazonPayV2SDK {\n Pay: AmazonPayV2Client;\n}\n\nexport interface RequestConfig {\n createCheckoutSessionConfig: AmazonPayV2CheckoutSessionConfig;\n estimatedOrderAmount?: AmazonPayV2Price;\n productType?: AmazonPayV2PayOptions;\n}\n\nexport interface AmazonPayV2Button {\n /**\n * Allows you to define custom actions.\n */\n onClick: (callback: () => void) => void;\n\n /**\n * Initiates the Amazon Pay checkout.\n */\n initCheckout(requestConfig: RequestConfig): void;\n}\n\nexport type AmazonPayV2ButtonParameters = AmazonPayV2ButtonParams | AmazonPayV2NewButtonParams;\n\nexport interface AmazonPayV2Client {\n /**\n * Render the Amazon Pay button to a HTML container element.\n *\n * @param containerId - HTML element id.\n * @param params - Button rendering params.\n */\n renderButton(containerId: string, params: AmazonPayV2ButtonParameters): AmazonPayV2Button;\n\n /**\n * Bind click events to HTML elements, so that when the element is clicked, the buyer can select a different shipping address or payment method.\n *\n * @param buttonId - HTML element id.\n * @param options - Element binding options.\n */\n bindChangeAction(buttonId: string, options: AmazonPayV2ChangeActionOptions): void;\n\n /**\n * Allow buyers to sign out from their Amazon account.\n */\n signout(): void;\n}\n\nexport interface AmazonPayV2HostWindow extends Window {\n amazon?: AmazonPayV2SDK;\n}\n\nexport interface AmazonPayV2ButtonConfig {\n /**\n * Amazon Pay merchant account identifier.\n */\n merchantId: string;\n\n /**\n * Placement of the Amazon Pay button on your website.\n */\n placement: AmazonPayV2Placement;\n\n /**\n * Ledger currency provided during registration for the given merchant identifier.\n */\n ledgerCurrency: AmazonPayV2LedgerCurrency;\n\n /**\n * Product type selected for checkout. Default is 'PayAndShip'.\n */\n productType?: AmazonPayV2PayOptions;\n\n /**\n * Color of the Amazon Pay button.\n */\n buttonColor?: AmazonPayV2ButtonColor;\n\n /**\n * Language used to render the button and text on Amazon Pay hosted pages.\n */\n checkoutLanguage?: AmazonPayV2CheckoutLanguage;\n\n /**\n * Sets button to Sandbox environment. You do not have to set this parameter\n * if your `publicKeyId` has an environment prefix. Default is false.\n */\n sandbox?: boolean;\n\n /**\n * Sets Amazon Pay button design.\n */\n design?: AmazonPayV2ButtonDesign;\n}\n\nexport interface AmazonPayV2ButtonParams extends AmazonPayV2ButtonConfig {\n /**\n * Configuration for calling the endpoint to Create Checkout Session.\n */\n createCheckoutSession: AmazonPayV2CheckoutSession;\n}\n\nexport interface AmazonPayV2NewButtonParams extends AmazonPayV2ButtonConfig {\n /**\n * Credential provided by Amazon Pay. You must also set the `sandbox`\n * parameter if your `publicKeyId` does not have an environment prefix.\n */\n publicKeyId?: string;\n\n /**\n * It does not have to match the final order amount if the buyer updates\n * their order after starting checkout. Amazon Pay will use this value to\n * assess transaction risk and prevent buyers from selecting payment methods\n * that can't be used to process the order.\n */\n estimatedOrderAmount?: AmazonPayV2Price;\n\n /**\n * Create Checkout Session configuration.\n */\n createCheckoutSessionConfig?: AmazonPayV2CheckoutSessionConfig;\n}\n\nexport interface AmazonPayV2CheckoutSession {\n /**\n * Endpoint URL to Create Checkout Session.\n */\n url: string;\n\n /**\n * HTTP request method. Default is 'POST'.\n */\n method?: 'GET' | 'POST';\n\n /**\n * Checkout Session ID parameter in the response. Default is 'checkoutSessionId'.\n */\n extractAmazonCheckoutSessionId?: string;\n}\n\nexport interface AmazonPayV2CheckoutSessionConfig {\n /**\n * A payload that Amazon Pay will use to create a Checkout Session object.\n */\n payloadJSON: string;\n\n /**\n * Payload's signature.\n */\n signature: string;\n\n /**\n * Credential provided by Amazon Pay. You do not have to set this parameter\n * if your `publicKeyId` has an environment prefix.\n */\n publicKeyId?: string;\n}\n\nexport interface AmazonPayV2Price {\n /**\n * Transaction amount.\n */\n amount: string;\n\n /**\n * Transaction currency code in ISO 4217 format. Example: USD.\n */\n currencyCode: string;\n}\n\nexport type AmazonPayV2ChangeActionType = 'changeAddress' | 'changePayment';\n\nexport interface AmazonPayV2ChangeActionOptions {\n /**\n * Amazon Pay Checkout Session identifier.\n */\n amazonCheckoutSessionId: string;\n\n /**\n * Update requested by the buyer.\n */\n changeAction: AmazonPayV2ChangeActionType;\n}\n\nexport enum AmazonPayV2Regions {\n de = 'eu',\n jp = 'fe',\n uk = 'eu',\n us = 'na',\n}\n\nexport enum AmazonPayV2CheckoutLanguage {\n en_US = 'en_US',\n en_GB = 'en_GB',\n de_DE = 'de_DE',\n fr_FR = 'fr_FR',\n it_IT = 'it_IT',\n es_ES = 'es_ES',\n ja_JP = 'ja_JP',\n}\n\nexport enum AmazonPayV2Placement {\n /** Initial or main page. */\n Home = 'Home',\n\n /** Product details page. */\n Product = 'Product',\n\n /** Cart review page before buyer starts checkout. */\n Cart = 'Cart',\n\n /** Any page after buyer starts checkout. */\n Checkout = 'Checkout',\n\n /** Any page that doesn't fit the previous descriptions. */\n Other = 'Other',\n}\n\nexport enum AmazonPayV2LedgerCurrency {\n USD = 'USD',\n EUR = 'EUR',\n GBP = 'GBP',\n JPY = 'JPY',\n}\n\nexport enum AmazonPayV2PayOptions {\n /** Select this product type if you need the buyer's shipping details. */\n PayAndShip = 'PayAndShip',\n\n /** Select this product type if you do not need the buyer's shipping details. */\n PayOnly = 'PayOnly',\n}\n\nexport enum AmazonPayV2ButtonColor {\n Gold = 'Gold',\n LightGray = 'LightGray',\n DarkGray = 'DarkGray',\n}\n\nexport enum AmazonPayV2ButtonDesign {\n C0001 = 'C0001',\n}\n\nexport interface AmazonPayV2ButtonRenderingOptions {\n checkoutState: InternalCheckoutSelectors;\n containerId: string;\n decoupleCheckoutInitiation?: boolean;\n methodId: string;\n buttonColor?: AmazonPayV2ButtonColor;\n options?: AmazonPayV2ButtonParameters;\n placement: AmazonPayV2Placement;\n}\n","import { PaymentMethod } from '../..';\nimport { InternalCheckoutSelectors } from '../../../../../core/src/checkout';\nimport { getShippableItemsCount } from '../../../../../core/src/shipping';\nimport { guard } from '../../../../src/common/utility';\nimport { StoreProfile } from '../../../../src/config';\nimport { CheckoutSettings } from '../../../../src/config/config';\nimport BuyNowCartRequestBody from '../../../cart/buy-now-cart-request-body';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\n\nimport {\n AmazonPayV2Button,\n AmazonPayV2ButtonColor,\n AmazonPayV2ButtonConfig,\n AmazonPayV2ButtonDesign,\n AmazonPayV2ButtonParameters,\n AmazonPayV2ButtonRenderingOptions,\n AmazonPayV2ChangeActionType,\n AmazonPayV2CheckoutSessionConfig,\n AmazonPayV2NewButtonParams,\n AmazonPayV2PayOptions,\n AmazonPayV2Placement,\n AmazonPayV2Price,\n AmazonPayV2SDK,\n RequestConfig,\n} from './amazon-pay-v2';\nimport AmazonPayV2ScriptLoader from './amazon-pay-v2-script-loader';\n\nexport default class AmazonPayV2PaymentProcessor {\n private _amazonPayV2SDK?: AmazonPayV2SDK;\n private _buttonParentContainer?: HTMLDivElement;\n private _amazonPayV2Button?: AmazonPayV2Button;\n private _buyNowCartRequestBody?: BuyNowCartRequestBody;\n\n constructor(private _amazonPayV2ScriptLoader: AmazonPayV2ScriptLoader) {}\n\n async initialize(paymentMethod: PaymentMethod): Promise {\n this._amazonPayV2SDK = await this._amazonPayV2ScriptLoader.load(paymentMethod);\n this._buttonParentContainer =\n this._buttonParentContainer || this._createAmazonPayButtonParentContainer();\n }\n\n deinitialize(): Promise {\n this._amazonPayV2Button = undefined;\n this._buttonParentContainer?.remove();\n this._buttonParentContainer = undefined;\n this._amazonPayV2SDK = undefined;\n\n return Promise.resolve();\n }\n\n bindButton(\n buttonId: string,\n sessionId: string,\n changeAction: AmazonPayV2ChangeActionType,\n ): void {\n this._getAmazonPayV2SDK().Pay.bindChangeAction(`#${buttonId}`, {\n amazonCheckoutSessionId: sessionId,\n changeAction,\n });\n }\n\n createButton(containerId: string, options: AmazonPayV2ButtonParameters): void {\n this._amazonPayV2Button = this._getAmazonPayV2SDK().Pay.renderButton(\n `#${containerId}`,\n options,\n );\n }\n\n prepareCheckout(createCheckoutSessionConfig: Required) {\n const requestConfig = this._prepareRequestConfig(createCheckoutSessionConfig);\n\n this._getAmazonPayV2Button().onClick(() => {\n this._getAmazonPayV2Button().initCheckout(requestConfig);\n });\n }\n\n prepareCheckoutWithCreationRequestConfig(\n createCheckoutConfig: () => Promise<{\n createCheckoutSessionConfig: Required;\n estimatedOrderAmount: AmazonPayV2Price;\n productType: AmazonPayV2PayOptions;\n }>,\n ) {\n this._getAmazonPayV2Button().onClick(async () => {\n const config = await createCheckoutConfig();\n const requestConfig = this._prepareRequestConfig(\n config.createCheckoutSessionConfig,\n config.estimatedOrderAmount,\n config.productType,\n );\n\n this._getAmazonPayV2Button().initCheckout(requestConfig);\n });\n }\n\n async signout(): Promise {\n if (this._amazonPayV2SDK) {\n this._amazonPayV2SDK.Pay.signout();\n }\n\n return Promise.resolve();\n }\n\n renderAmazonPayButton({\n buttonColor,\n checkoutState,\n containerId,\n decoupleCheckoutInitiation = false,\n methodId,\n options,\n placement,\n }: AmazonPayV2ButtonRenderingOptions): HTMLDivElement {\n const container = document.querySelector(`#${containerId}`);\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to render the Amazon Pay button to an invalid HTML container element.',\n );\n }\n\n const { id: parentContainerId } = container.appendChild(this._getButtonParentContainer());\n\n if (options) {\n options.design = AmazonPayV2ButtonDesign.C0001;\n }\n\n const amazonPayV2ButtonOptions =\n options ??\n this._getAmazonPayV2ButtonOptions(\n checkoutState,\n methodId,\n placement,\n decoupleCheckoutInitiation,\n buttonColor,\n );\n\n this.createButton(parentContainerId, amazonPayV2ButtonOptions);\n\n return this._getButtonParentContainer();\n }\n\n setCartRequestBody(buyNowCartRequestBody: BuyNowCartRequestBody) {\n this._buyNowCartRequestBody = buyNowCartRequestBody;\n }\n\n /**\n * @internal\n */\n isPh4Enabled(\n features: CheckoutSettings['features'],\n storeCountryCode: StoreProfile['storeCountryCode'],\n ): boolean {\n const isPh4Enabled = !!features['PROJECT-3483.amazon_pay_ph4'];\n const isPh4UsOnly = !!features['INT-6885.amazon_pay_ph4_us_only'];\n\n if (isPh4Enabled && isPh4UsOnly) {\n return storeCountryCode === 'US';\n }\n\n return isPh4Enabled;\n }\n\n private _prepareRequestConfig(\n createCheckoutSessionConfig: Required,\n estimatedOrderAmount?: AmazonPayV2Price,\n productType?: AmazonPayV2PayOptions,\n ): RequestConfig {\n const { publicKeyId, ...signedPayload } = createCheckoutSessionConfig;\n\n return {\n createCheckoutSessionConfig: this._isEnvironmentSpecific(publicKeyId)\n ? signedPayload\n : createCheckoutSessionConfig,\n ...(estimatedOrderAmount && { estimatedOrderAmount }),\n ...(productType && { productType }),\n };\n }\n\n private _createAmazonPayButtonParentContainer(): HTMLDivElement {\n const uid = Math.random().toString(16).substr(-4);\n const parentContainer = document.createElement('div');\n\n parentContainer.id = `amazonpay_button_parent_container_${uid}`;\n\n return parentContainer;\n }\n\n private _getAmazonPayV2ButtonOptions(\n {\n cart: { getCart },\n checkout: { getCheckout },\n config: { getStoreConfigOrThrow },\n paymentMethods: { getPaymentMethodOrThrow },\n }: InternalCheckoutSelectors,\n methodId: string,\n placement: AmazonPayV2Placement,\n decoupleCheckoutInitiation = false,\n buttonColor = AmazonPayV2ButtonColor.Gold,\n ): AmazonPayV2ButtonParameters {\n const {\n config: { merchantId, testMode },\n initializationData: {\n checkoutLanguage,\n checkoutSessionMethod,\n createCheckoutSessionConfig,\n extractAmazonCheckoutSessionId,\n ledgerCurrency,\n publicKeyId,\n },\n } = getPaymentMethodOrThrow(methodId);\n\n if (!merchantId || !ledgerCurrency) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const buttonBaseConfig: AmazonPayV2ButtonConfig = {\n merchantId,\n ledgerCurrency,\n checkoutLanguage,\n placement,\n buttonColor,\n design: AmazonPayV2ButtonDesign.C0001,\n };\n\n if (this._buyNowCartRequestBody) {\n return {\n ...buttonBaseConfig,\n sandbox: !!testMode,\n };\n }\n\n const cart = getCart();\n\n buttonBaseConfig.productType =\n cart && getShippableItemsCount(cart) === 0\n ? AmazonPayV2PayOptions.PayOnly\n : AmazonPayV2PayOptions.PayAndShip;\n\n const {\n checkoutSettings: { features },\n storeProfile: { shopPath, storeCountryCode },\n } = getStoreConfigOrThrow();\n\n if (this.isPh4Enabled(features, storeCountryCode)) {\n const amount = getCheckout()?.outstandingBalance.toString();\n const currencyCode = cart?.currency.code;\n const buttonOptions: AmazonPayV2NewButtonParams = { ...buttonBaseConfig };\n let tmpConfig: AmazonPayV2CheckoutSessionConfig;\n\n if (this._isEnvironmentSpecific(publicKeyId)) {\n buttonOptions.publicKeyId = publicKeyId;\n tmpConfig = createCheckoutSessionConfig;\n } else {\n buttonOptions.sandbox = !!testMode;\n tmpConfig = { ...createCheckoutSessionConfig, publicKeyId };\n }\n\n if (!decoupleCheckoutInitiation) {\n buttonOptions.createCheckoutSessionConfig = tmpConfig;\n }\n\n if (amount && currencyCode) {\n buttonOptions.estimatedOrderAmount = { amount, currencyCode };\n }\n\n return buttonOptions;\n }\n\n const createCheckoutSession = {\n method: checkoutSessionMethod,\n url: features['INT-5826.amazon_relative_url']\n ? `/remote-checkout/${methodId}/payment-session`\n : `${shopPath}/remote-checkout/${methodId}/payment-session`,\n extractAmazonCheckoutSessionId,\n };\n\n return {\n ...buttonBaseConfig,\n createCheckoutSession,\n sandbox: !!testMode,\n };\n }\n\n private _isEnvironmentSpecific(publicKeyId: string): boolean {\n return /^(SANDBOX|LIVE)/.test(publicKeyId);\n }\n\n private _getAmazonPayV2SDK(): AmazonPayV2SDK {\n return this._getOrThrow(this._amazonPayV2SDK);\n }\n\n private _getButtonParentContainer(): HTMLDivElement {\n return this._getOrThrow(this._buttonParentContainer);\n }\n\n private _getAmazonPayV2Button(): AmazonPayV2Button {\n return this._getOrThrow(this._amazonPayV2Button);\n }\n\n private _getOrThrow(value?: T): T {\n return guard(\n value,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when the client library of a payment method fails\n * to load, or for some reason, it is inaccessible.\n */\nexport default class PaymentMethodClientUnavailableError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Unable to proceed because the client library of a payment method is not loaded or ready to be used.',\n );\n\n this.name = 'PaymentMethodClientUnavailableError';\n this.type = 'payment_method_client_unavailable';\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\nimport PaymentMethod from '../../payment-method';\n\nimport { AmazonPayV2HostWindow, AmazonPayV2Regions, AmazonPayV2SDK } from './amazon-pay-v2';\n\nexport default class AmazonPayV2ScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _window: AmazonPayV2HostWindow = window,\n ) {}\n\n async load(method: PaymentMethod): Promise {\n const { initializationData: { region = 'us' } = {} } = method;\n\n const amazonPayV2Region = (AmazonPayV2Regions as any)[region];\n\n await this._scriptLoader.loadScript(\n `https://static-${amazonPayV2Region}.payments-amazon.com/checkout.js`,\n );\n\n if (!this._window.amazon) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.amazon;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport AmazonPayV2PaymentProcessor from './amazon-pay-v2-payment-processor';\nimport AmazonPayV2ScriptLoader from './amazon-pay-v2-script-loader';\n\nexport default function createAmazonPayV2PaymentProcessor(): AmazonPayV2PaymentProcessor {\n return new AmazonPayV2PaymentProcessor(new AmazonPayV2ScriptLoader(getScriptLoader()));\n}\n","import StandardError from './standard-error';\n\n/**\n * Throw this error if the shopper is using a browser version that is not\n * supported by us or any third party provider we use.\n */\nexport default class UnsupportedBrowserError extends StandardError {\n constructor(message?: string) {\n super(message || 'Unsupported browser error');\n\n this.name = 'UnsupportedBrowserError';\n this.type = 'unsupported_browser';\n }\n}\n","import { Omit } from '../../../common/types';\nimport {\n GooglePayBraintreeDataRequest,\n GooglePayBraintreePaymentDataRequestV1,\n GooglePayCreator,\n GooglePaymentData,\n TokenizePayload,\n} from '../googlepay';\nimport { PaypalAuthorizeData, PaypalButtonOptions, PaypalButtonRender, PaypalSDK } from '../paypal';\n\nimport {\n VisaCheckoutInitOptions,\n VisaCheckoutPaymentSuccessPayload,\n VisaCheckoutTokenizedPayload,\n} from './visacheckout';\n\n/**\n *\n * Constants\n *\n */\nexport const PAYPAL_COMPONENTS = ['buttons', 'messages'];\n\n/**\n *\n * Common\n *\n */\nexport interface BraintreeModuleCreator<\n TInstance,\n TOptions = BraintreeModuleCreatorConfig,\n TError = BraintreeError,\n> {\n create(\n config: TOptions,\n callback?: (error: TError, instance: TInstance) => void,\n ): Promise;\n}\n\nexport interface BraintreeModuleCreatorConfig {\n client?: BraintreeClient;\n authorization?: string;\n}\n\nexport interface BraintreeModule {\n teardown(): Promise;\n}\n\nexport interface BraintreeSDK {\n client?: BraintreeClientCreator;\n dataCollector?: BraintreeDataCollectorCreator;\n googlePayment?: GooglePayCreator;\n hostedFields?: BraintreeHostedFieldsCreator;\n paypal?: BraintreePaypalCreator;\n paypalCheckout?: BraintreePaypalCheckoutCreator;\n threeDSecure?: BraintreeThreeDSecureCreator;\n venmo?: BraintreeVenmoCheckoutCreator;\n visaCheckout?: BraintreeVisaCheckoutCreator;\n}\n\nexport interface BraintreePaypalRequest {\n amount: string | number;\n billingAgreementDescription?: string;\n currency?: string;\n displayName?: string;\n enableShippingAddress: true;\n flow: 'checkout' | 'vault';\n intent?: 'authorize' | 'order' | 'sale';\n landingPageType?: 'login' | 'billing';\n locale?: string;\n offerCredit?: boolean;\n shippingAddressEditable?: boolean;\n shippingAddressOverride?: BraintreeShippingAddressOverride;\n useraction?: 'commit';\n}\n\nexport interface BraintreeShippingAddressOverride {\n line1: string;\n line2?: string;\n city: string;\n state: string;\n postalCode: string;\n countryCode: string;\n phone?: string;\n recipientName?: string;\n}\n\nexport interface BraintreeTokenizePayload {\n nonce: string;\n type: 'PaypalAccount' | 'VenmoAccount';\n details: BraintreeDetails;\n creditFinancingOffered?: {\n totalCost: {\n value: string;\n currency: string;\n };\n term: number;\n monthlyPayment: {\n value: string;\n currency: string;\n };\n totalInsterest: {\n value: string;\n currency: string;\n };\n payerAcceptance: boolean;\n cartAmountImmutable: boolean;\n };\n}\n\nexport interface BraintreeDetails {\n username?: string;\n email?: string;\n payerId?: string;\n firstName?: string;\n lastName?: string;\n countryCode?: string;\n phone?: string;\n shippingAddress?: BraintreeShippingAddress;\n billingAddress?: BraintreeAddress;\n}\n\nexport interface BraintreeAddress {\n line1: string;\n line2: string;\n city: string;\n state: string;\n postalCode: string;\n countryCode: string;\n}\n\nexport interface BraintreeShippingAddress extends BraintreeAddress {\n recipientName: string;\n}\n\nexport interface BraintreeVerifyPayload {\n nonce: string;\n details: {\n cardType: string;\n lastFour: string;\n lastTwo: string;\n };\n description: string;\n liabilityShiftPossible: boolean;\n liabilityShifted: boolean;\n}\n\nexport interface BraintreeError extends Error {\n type: 'CUSTOMER' | 'MERCHANT' | 'NETWORK' | 'INTERNAL' | 'UNKNOWN';\n code: string;\n details?: unknown;\n}\n\n/**\n *\n * Braintree Client\n *\n */\nexport type BraintreeClientCreator = BraintreeModuleCreator;\n\nexport interface BraintreeClient {\n request(payload: BraintreeRequestData): Promise;\n getVersion(): string | void;\n}\n\nexport interface BraintreeRequestData {\n data: {\n creditCard: {\n billingAddress?: {\n countryCodeAlpha2: string;\n locality: string;\n countryName: string;\n postalCode: string;\n streetAddress: string;\n };\n cardholderName: string;\n cvv?: string;\n expirationDate: string;\n number: string;\n options: {\n validate: boolean;\n };\n };\n };\n endpoint: string;\n method: string;\n}\n\nexport interface BraintreeTokenizeResponse {\n creditCards: Array<{ nonce: string }>;\n}\n\n/**\n *\n * Braintree Data Collector\n *\n */\nexport type BraintreeDataCollectorCreator = BraintreeModuleCreator<\n BraintreeDataCollector,\n BraintreeDataCollectorCreatorConfig\n>;\n\nexport interface BraintreeDataCollectorCreatorConfig extends BraintreeModuleCreatorConfig {\n kount?: boolean;\n paypal?: boolean;\n}\n\nexport interface BraintreeDataCollector extends BraintreeModule {\n deviceData?: string;\n}\n\n/**\n *\n * Braintree Google Pay\n *\n */\nexport interface BraintreeGooglePayThreeDSecure {\n verifyCard(options: BraintreeGooglePayThreeDSecureOptions): Promise;\n}\n\nexport interface BraintreeGooglePayThreeDSecureOptions {\n nonce: string;\n amount: number;\n showLoader?: boolean;\n onLookupComplete(data: BraintreeThreeDSecureVerificationData, next: () => void): void;\n}\n\nexport interface GooglePayBraintreeSDK extends BraintreeModule {\n createPaymentDataRequest(\n request?: GooglePayBraintreeDataRequest,\n ): GooglePayBraintreePaymentDataRequestV1;\n parseResponse(paymentData: GooglePaymentData): Promise;\n}\n\n/**\n *\n * Braintree Hosted Fields\n *\n */\nexport type BraintreeHostedFieldsCreator = BraintreeModuleCreator<\n BraintreeHostedFields,\n BraintreeHostedFieldsCreatorConfig\n>;\n\nexport interface BraintreeHostedFields {\n teardown(): Promise;\n tokenize(\n options?: BraintreeHostedFieldsTokenizeOptions,\n ): Promise;\n on(eventName: string, callback: (event: BraintreeHostedFieldsState) => void): void;\n}\n\nexport interface BraintreeHostedFieldsCreatorConfig extends BraintreeModuleCreatorConfig {\n fields: {\n number?: BraintreeHostedFieldOption;\n expirationDate?: BraintreeHostedFieldOption;\n expirationMonth?: BraintreeHostedFieldOption;\n expirationYear?: BraintreeHostedFieldOption;\n cvv?: BraintreeHostedFieldOption;\n postalCode?: BraintreeHostedFieldOption;\n };\n styles?: {\n input?: { [key: string]: string };\n '.invalid'?: { [key: string]: string };\n '.valid'?: { [key: string]: string };\n ':focus'?: { [key: string]: string };\n };\n}\n\nexport interface BraintreeHostedFieldOption {\n container: string | HTMLElement;\n placeholder?: string;\n type?: string;\n formatInput?: boolean;\n maskInput?: boolean | { character?: string; showLastFour?: string };\n select?: boolean | { options?: string[] };\n maxCardLength?: number;\n maxlength?: number;\n minlength?: number;\n prefill?: string;\n rejectUnsupportedCards?: boolean;\n supportedCardBrands?: { [key: string]: boolean };\n internalLabel?: string;\n}\n\nexport interface BraintreeHostedFieldsState {\n cards: BraintreeHostedFieldsCard[];\n emittedBy: string;\n fields: {\n number?: BraintreeHostedFieldsFieldData;\n expirationDate?: BraintreeHostedFieldsFieldData;\n expirationMonth?: BraintreeHostedFieldsFieldData;\n expirationYear?: BraintreeHostedFieldsFieldData;\n cvv?: BraintreeHostedFieldsFieldData;\n postalCode?: BraintreeHostedFieldsFieldData;\n };\n}\n\nexport interface BraintreeHostedFieldsCard {\n type: string;\n niceType: string;\n code: { name: string; size: number };\n}\n\nexport interface BraintreeFormFieldState {\n isFocused: boolean;\n isEmpty: boolean;\n isPotentiallyValid: boolean;\n isValid: boolean;\n}\n\nexport interface BraintreeHostedFieldsFieldData extends BraintreeFormFieldState {\n container: HTMLElement;\n}\n\nexport type BraintreeFormErrorData = Omit;\n\nexport type BraintreeFormErrorDataKeys =\n | 'number'\n | 'expirationDate'\n | 'expirationMonth'\n | 'expirationYear'\n | 'cvv'\n | 'postalCode';\n\nexport type BraintreeFormErrorsData = Partial<\n Record\n>;\n\nexport interface BraintreeHostedFieldsTokenizeOptions {\n vault?: boolean;\n fieldsToTokenize?: string[];\n cardholderName?: string;\n billingAddress?: BraintreeBillingAddressRequestData;\n}\n\nexport interface BraintreeHostedFieldsTokenizePayload {\n nonce: string;\n details: {\n bin: string;\n cardType: string;\n expirationMonth: string;\n expirationYear: string;\n lastFour: string;\n lastTwo: string;\n };\n description: string;\n type: string;\n binData: {\n commercial: string;\n countryOfIssuance: string;\n debit: string;\n durbinRegulated: string;\n healthcare: string;\n issuingBank: string;\n payroll: string;\n prepaid: string;\n productId: string;\n };\n}\n\nexport interface BraintreeBillingAddressRequestData {\n postalCode?: string;\n firstName?: string;\n lastName?: string;\n company?: string;\n streetAddress?: string;\n extendedAddress?: string;\n locality?: string;\n region?: string;\n countryCodeNumeric?: string;\n countryCodeAlpha2?: string;\n countryCodeAlpha3?: string;\n countryName?: string;\n}\n\nexport interface BraintreeHostedFormError extends BraintreeError {\n details?: {\n invalidFieldKeys?: string[];\n };\n}\n\n/**\n *\n * Braintree 3D Secure\n *\n */\nexport type BraintreeThreeDSecureCreator = BraintreeModuleCreator<\n BraintreeThreeDSecure,\n BraintreeThreeDSecureCreatorConfig\n>;\n\nexport interface BraintreeThreeDSecure extends BraintreeModule {\n verifyCard(options: BraintreeThreeDSecureOptions): Promise;\n cancelVerifyCard(): Promise;\n}\n\nexport interface BraintreeThreeDSecureCreatorConfig extends BraintreeModuleCreatorConfig {\n version?: number;\n}\n\nexport interface BraintreeThreeDSecureOptions {\n nonce: string;\n amount: number;\n challengeRequested: boolean;\n showLoader?: boolean;\n addFrame(error: Error | undefined, iframe: HTMLIFrameElement): void;\n removeFrame(): void;\n onLookupComplete(data: BraintreeThreeDSecureVerificationData, next: () => void): void;\n}\n\ninterface BraintreeThreeDSecureVerificationData {\n lookup: {\n threeDSecureVersion: string;\n };\n paymentMethod: BraintreeVerifyPayload;\n requiresUserAuthentication: boolean;\n threeDSecureInfo: {\n liabilityShiftPossible: boolean;\n liabilityShifted: boolean;\n };\n}\n\n/**\n *\n * Braintree PayPal\n *\n */\nexport type BraintreePaypalCreator = BraintreeModuleCreator;\n\nexport interface BraintreePaypal {\n closeWindow(): void;\n focusWindow(): void;\n tokenize(options: BraintreePaypalRequest): Promise;\n Buttons?(options: PaypalButtonOptions): PaypalButtonRender;\n}\n\n/**\n *\n * Braintree PayPal Checkout\n *\n */\nexport type BraintreePaypalCheckoutCreator = BraintreeModuleCreator;\n\nexport interface BraintreePaypalCheckout {\n loadPayPalSDK(\n config: BraintreePaypalSdkCreatorConfig,\n callback: (instance: BraintreePaypalCheckout) => void,\n ): void;\n createPayment(options: BraintreePaypalRequest): Promise;\n teardown(): Promise;\n tokenizePayment(options: PaypalAuthorizeData): Promise;\n}\n\nexport interface BraintreePaypalSdkCreatorConfig {\n components?: string;\n currency?: string;\n intent?: string;\n isCreditEnabled?: boolean;\n}\n\n/**\n *\n * Braintree Venmo\n *\n */\nexport type BraintreeVenmoCheckoutCreator = BraintreeModuleCreator<\n BraintreeVenmoCheckout,\n BraintreeVenmoCreatorConfig\n>;\n\nexport interface BraintreeVenmoCheckout extends BraintreeModule {\n tokenize(callback: (error: BraintreeError, payload: BraintreeTokenizePayload) => void): void;\n isBrowserSupported(): boolean;\n}\n\nexport interface BraintreeVenmoCreatorConfig extends BraintreeModuleCreatorConfig {\n allowDesktop: boolean;\n paymentMethodUsage: string;\n}\n\n/**\n *\n * Braintree Visa Checkout\n *\n */\nexport type BraintreeVisaCheckoutCreator = BraintreeModuleCreator;\n\nexport interface BraintreeVisaCheckout extends BraintreeModule {\n tokenize(payment: VisaCheckoutPaymentSuccessPayload): Promise;\n createInitOptions(options: Partial): VisaCheckoutInitOptions;\n}\n\n/**\n *\n * Other\n *\n */\nexport interface BraintreeHostWindow extends Window {\n braintree?: BraintreeSDK;\n paypal?: PaypalSDK;\n}\n","import {\n NotInitializedError,\n NotInitializedErrorType,\n UnsupportedBrowserError,\n} from '../../../common/error/errors';\nimport { PaypalHostWindow } from '../paypal';\n\nimport {\n BraintreeClient,\n BraintreeDataCollector,\n BraintreeError,\n BraintreeHostedFields,\n BraintreeHostedFieldsCreatorConfig,\n BraintreeModule,\n BraintreePaypal,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeThreeDSecure,\n BraintreeVenmoCheckout,\n BraintreeVisaCheckout,\n GooglePayBraintreeSDK,\n PAYPAL_COMPONENTS,\n} from './braintree';\nimport BraintreeScriptLoader from './braintree-script-loader';\n\nexport default class BraintreeSDKCreator {\n private _client?: Promise;\n private _3ds?: Promise;\n private _paypal?: Promise;\n private _paypalCheckout?: Promise;\n private _clientToken?: string;\n private _visaCheckout?: Promise;\n private _venmoCheckout?: Promise;\n private _dataCollectors: {\n default?: Promise;\n paypal?: Promise;\n } = {};\n private _googlePay?: Promise;\n private _window: PaypalHostWindow;\n\n constructor(private _braintreeScriptLoader: BraintreeScriptLoader) {\n this._window = window;\n }\n\n initialize(clientToken: string) {\n this._clientToken = clientToken;\n }\n\n getClient(): Promise {\n if (!this._clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!this._client) {\n this._client = this._braintreeScriptLoader\n .loadClient()\n .then((client) => client.create({ authorization: this._clientToken }));\n }\n\n return this._client;\n }\n\n getPaypal(): Promise {\n if (!this._paypal) {\n this._paypal = Promise.all([\n this.getClient(),\n this._braintreeScriptLoader.loadPaypal(),\n ]).then(([client, paypal]) => paypal.create({ client }));\n }\n\n return this._paypal;\n }\n\n async getPaypalCheckout(\n config: Partial,\n onSuccess: (instance: BraintreePaypalCheckout) => void,\n onError: (error: BraintreeError) => void,\n ): Promise {\n const client = await this.getClient();\n const paypalCheckout = await this._braintreeScriptLoader.loadPaypalCheckout();\n\n const paypalCheckoutConfig = { client };\n const paypalCheckoutCallback = (\n error: BraintreeError,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n if (error) {\n return onError(error);\n }\n\n const paypalSdkLoadCallback = () => onSuccess(braintreePaypalCheckout);\n const paypalSdkLoadConfig = {\n currency: config.currency,\n ...(config.isCreditEnabled && { 'enable-funding': 'paylater' }),\n components: PAYPAL_COMPONENTS.toString(),\n intent: config.intent,\n };\n\n if (!this._window.paypal) {\n braintreePaypalCheckout.loadPayPalSDK(paypalSdkLoadConfig, paypalSdkLoadCallback);\n } else {\n onSuccess(braintreePaypalCheckout);\n }\n };\n\n this._paypalCheckout = paypalCheckout.create(paypalCheckoutConfig, paypalCheckoutCallback);\n\n return this._paypalCheckout;\n }\n\n async getVenmoCheckout(\n onSuccess: (braintreeVenmoCheckout: BraintreeVenmoCheckout) => void,\n onError: (error: BraintreeError | UnsupportedBrowserError) => void,\n ): Promise {\n if (!this._venmoCheckout) {\n const client = await this.getClient();\n\n const venmoCheckout = await this._braintreeScriptLoader.loadVenmoCheckout();\n\n const venmoCheckoutConfig = {\n client,\n allowDesktop: true,\n paymentMethodUsage: 'multi_use',\n };\n\n const venmoCheckoutCallback = (\n error: BraintreeError,\n braintreeVenmoCheckout: BraintreeVenmoCheckout,\n ): void => {\n if (error) {\n return onError(error);\n }\n\n if (!braintreeVenmoCheckout.isBrowserSupported()) {\n return onError(new UnsupportedBrowserError());\n }\n\n onSuccess(braintreeVenmoCheckout);\n };\n\n this._venmoCheckout = venmoCheckout.create(venmoCheckoutConfig, venmoCheckoutCallback);\n }\n\n return this._venmoCheckout;\n }\n\n get3DS(): Promise {\n if (!this._3ds) {\n this._3ds = Promise.all([this.getClient(), this._braintreeScriptLoader.load3DS()]).then(\n ([client, threeDSecure]) => threeDSecure.create({ client, version: 2 }),\n );\n }\n\n return this._3ds;\n }\n\n getDataCollector(options?: { paypal: boolean }): Promise {\n const cacheKey = options && options.paypal ? 'paypal' : 'default';\n let cached = this._dataCollectors[cacheKey];\n\n if (!cached) {\n cached = Promise.all([\n this.getClient(),\n this._braintreeScriptLoader.loadDataCollector(),\n ])\n .then(([client, dataCollector]) =>\n dataCollector.create({ client, kount: true, ...options }),\n )\n .catch((error) => {\n if (error && error.code === 'DATA_COLLECTOR_KOUNT_NOT_ENABLED') {\n return { deviceData: undefined, teardown: () => Promise.resolve() };\n }\n\n throw error;\n });\n\n this._dataCollectors[cacheKey] = cached;\n }\n\n return cached;\n }\n\n getVisaCheckout(): Promise {\n if (!this._visaCheckout) {\n this._visaCheckout = Promise.all([\n this.getClient(),\n this._braintreeScriptLoader.loadVisaCheckout(),\n ]).then(([client, visaCheckout]) => visaCheckout.create({ client }));\n }\n\n return this._visaCheckout;\n }\n\n getGooglePaymentComponent(): Promise {\n if (!this._googlePay) {\n this._googlePay = Promise.all([\n this.getClient(),\n this._braintreeScriptLoader.loadGooglePayment(),\n ]).then(([client, googlePay]) => googlePay.create({ client }));\n }\n\n return this._googlePay;\n }\n\n async createHostedFields(\n options: Pick,\n ): Promise {\n const [client, hostedFields] = await Promise.all([\n this.getClient(),\n this._braintreeScriptLoader.loadHostedFields(),\n ]);\n\n return hostedFields.create({ ...options, client });\n }\n\n teardown(): Promise {\n return Promise.all([\n this._teardown(this._3ds),\n this._teardown(this._dataCollectors.default),\n this._teardown(this._dataCollectors.paypal),\n this._teardown(this._googlePay),\n this._teardown(this._paypalCheckout),\n this._teardown(this._venmoCheckout),\n this._teardown(this._visaCheckout),\n ]).then(() => {\n this._3ds = undefined;\n this._dataCollectors = {};\n this._googlePay = undefined;\n this._paypalCheckout = undefined;\n this._venmoCheckout = undefined;\n this._visaCheckout = undefined;\n });\n }\n\n private _teardown(module?: Promise) {\n return module\n ? module\n .then((mod) => mod.teardown())\n .catch((error) => {\n if (error.code !== 'METHOD_CALLED_AFTER_TEARDOWN') {\n throw error;\n }\n })\n : Promise.resolve();\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\nimport { GooglePayCreator } from '../googlepay';\n\nimport {\n BraintreeClientCreator,\n BraintreeDataCollectorCreator,\n BraintreeHostedFieldsCreator,\n BraintreeHostWindow,\n BraintreePaypalCheckoutCreator,\n BraintreePaypalCreator,\n BraintreeThreeDSecureCreator,\n BraintreeVenmoCheckoutCreator,\n BraintreeVisaCheckoutCreator,\n} from './braintree';\n\nconst version = '3.81.0';\n\nexport default class BraintreeScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _window: BraintreeHostWindow = window,\n ) {}\n\n loadClient(): Promise {\n return this._scriptLoader\n .loadScript(`//js.braintreegateway.com/web/${version}/js/client.min.js`)\n .then(() => {\n if (!this._window.braintree || !this._window.braintree.client) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.braintree.client;\n });\n }\n\n load3DS(): Promise {\n return this._scriptLoader\n .loadScript(`//js.braintreegateway.com/web/${version}/js/three-d-secure.min.js`)\n .then(() => {\n if (!this._window.braintree || !this._window.braintree.threeDSecure) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.braintree.threeDSecure;\n });\n }\n\n loadDataCollector(): Promise {\n return this._scriptLoader\n .loadScript(`//js.braintreegateway.com/web/${version}/js/data-collector.min.js`)\n .then(() => {\n if (!this._window.braintree || !this._window.braintree.dataCollector) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.braintree.dataCollector;\n });\n }\n\n loadPaypal(): Promise {\n return this._scriptLoader\n .loadScript(`//js.braintreegateway.com/web/${version}/js/paypal.min.js`)\n .then(() => {\n if (!this._window.braintree || !this._window.braintree.paypal) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.braintree.paypal;\n });\n }\n\n loadPaypalCheckout(): Promise {\n return this._scriptLoader\n .loadScript(`//js.braintreegateway.com/web/${version}/js/paypal-checkout.min.js`)\n .then(() => {\n if (!this._window.braintree || !this._window.braintree.paypalCheckout) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.braintree.paypalCheckout;\n });\n }\n\n loadVisaCheckout(): Promise {\n return this._scriptLoader\n .loadScript(`//js.braintreegateway.com/web/${version}/js/visa-checkout.min.js`)\n .then(() => {\n if (!this._window.braintree || !this._window.braintree.visaCheckout) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.braintree.visaCheckout;\n });\n }\n\n loadVenmoCheckout(): Promise {\n return this._scriptLoader\n .loadScript(`//js.braintreegateway.com/web/${version}/js/venmo.min.js`)\n .then(() => {\n if (!this._window.braintree?.venmo) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.braintree.venmo;\n });\n }\n\n loadGooglePayment(): Promise {\n return this._scriptLoader\n .loadScript(`//js.braintreegateway.com/web/${version}/js/google-payment.min.js`)\n .then(() => {\n if (!this._window.braintree || !this._window.braintree.googlePayment) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.braintree.googlePayment;\n });\n }\n\n async loadHostedFields(): Promise {\n await this._scriptLoader.loadScript(\n `//js.braintreegateway.com/web/${version}/js/hosted-fields.min.js`,\n );\n\n if (!this._window.braintree || !this._window.braintree.hostedFields) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.braintree.hostedFields;\n }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { Address, LegacyAddress } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { SDK_VERSION_HEADERS } from '../../../common/http-request';\n\nimport { BraintreeDataCollector } from './braintree';\nimport BraintreeSDKCreator from './braintree-sdk-creator';\nimport {\n VisaCheckoutAddress,\n VisaCheckoutInitOptions,\n VisaCheckoutPaymentSuccessPayload,\n VisaCheckoutTokenizedPayload,\n} from './visacheckout';\n\nexport default class BraintreeVisaCheckoutPaymentProcessor {\n constructor(\n private _braintreeSDKCreator: BraintreeSDKCreator,\n private _requestSender: RequestSender,\n ) {}\n\n initialize(\n clientToken: string,\n options: VisaCheckoutInitializeOptions,\n ): Promise {\n this._braintreeSDKCreator.initialize(clientToken);\n\n return this._braintreeSDKCreator.getVisaCheckout().then((visaCheckout) =>\n visaCheckout.createInitOptions({\n settings: {\n locale: options.locale,\n shipping: {\n collectShipping: options.collectShipping,\n },\n },\n paymentRequest: {\n currencyCode: options.currencyCode,\n subtotal: String(options.subtotal),\n },\n }),\n );\n }\n\n deinitialize(): Promise {\n return this._braintreeSDKCreator.teardown();\n }\n\n handleSuccess(\n payment: VisaCheckoutPaymentSuccessPayload,\n shipping?: Address,\n billing?: Address,\n ): Promise {\n return this._braintreeSDKCreator.getVisaCheckout().then((braintreeVisaCheckout) =>\n Promise.all([\n braintreeVisaCheckout.tokenize(payment),\n this._braintreeSDKCreator.getDataCollector(),\n ]).then(([tokenizedPayload, dataCollector]) => {\n const {\n shippingAddress = this._toVisaCheckoutAddress(shipping),\n billingAddress = this._toVisaCheckoutAddress(billing),\n } = tokenizedPayload;\n\n return this._postForm(\n {\n ...tokenizedPayload,\n shippingAddress,\n billingAddress,\n },\n dataCollector,\n );\n }),\n );\n }\n\n private _postForm(\n paymentData: VisaCheckoutTokenizedPayload,\n dataCollector: BraintreeDataCollector,\n ) {\n const { userData, billingAddress, shippingAddress, details: cardInformation } = paymentData;\n const { userEmail } = userData;\n const { deviceData } = dataCollector;\n\n return this._requestSender.post('/checkout.php', {\n headers: {\n Accept: 'text/html',\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...SDK_VERSION_HEADERS,\n },\n body: {\n payment_type: paymentData.type,\n nonce: paymentData.nonce,\n provider: 'braintreevisacheckout',\n action: 'set_external_checkout',\n device_data: deviceData,\n card_information: this._getCardInformation(cardInformation),\n billing_address: this._getAddress(userEmail, billingAddress),\n shipping_address: this._getAddress(userEmail, shippingAddress),\n },\n });\n }\n\n private _toVisaCheckoutAddress(address?: Address): VisaCheckoutAddress {\n if (!address) {\n return {};\n }\n\n return {\n firstName: address.firstName,\n lastName: address.lastName,\n phoneNumber: address.phone,\n streetAddress: address.address1,\n extendedAddress: address.address2,\n locality: address.city,\n region: address.stateOrProvinceCode,\n countryCode: address.countryCode,\n postalCode: address.postalCode,\n };\n }\n\n private _getAddress(email: string, address: VisaCheckoutAddress = {}): Partial {\n return {\n email,\n first_name: address.firstName,\n last_name: address.lastName,\n phone_number: address.phoneNumber,\n address_line_1: address.streetAddress,\n address_line_2: address.extendedAddress,\n city: address.locality,\n state: address.region,\n country_code: address.countryCode,\n postal_code: address.postalCode,\n };\n }\n\n private _getCardInformation(cardInformation: { cardType: string; lastTwo: string }) {\n return {\n type: cardInformation.cardType,\n number: cardInformation.lastTwo,\n };\n }\n}\n\nexport interface VisaCheckoutInitializeOptions {\n locale?: string;\n collectShipping?: boolean;\n subtotal?: number;\n currencyCode?: string;\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\nimport { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport BraintreeScriptLoader from './braintree-script-loader';\nimport BraintreeSDKCreator from './braintree-sdk-creator';\nimport BraintreeVisaCheckoutPaymentProcessor from './braintree-visacheckout-payment-processor';\n\nexport default function createBraintreeVisaCheckoutPaymentProcessor(\n scriptLoader: ScriptLoader,\n requestSender: RequestSender,\n) {\n const braintreeScriptLoader = new BraintreeScriptLoader(scriptLoader);\n const braintreeSDKCreator = new BraintreeSDKCreator(braintreeScriptLoader);\n\n return new BraintreeVisaCheckoutPaymentProcessor(braintreeSDKCreator, requestSender);\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { VisaCheckoutHostWindow, VisaCheckoutSDK } from './visacheckout';\n\nexport default class VisaCheckoutScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _window: VisaCheckoutHostWindow = window,\n ) {}\n\n load(testMode?: boolean): Promise {\n return this._scriptLoader\n .loadScript(\n `//${\n testMode ? 'sandbox-' : ''\n }assets.secure.checkout.visa.com/checkout-widget/resources/js/integration/v1/sdk.js`,\n )\n .then(() => {\n if (!this._window.V) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.V;\n });\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { ChasePayHostWindow, JPMC } from './chasepay';\n\nexport default class ChasePayScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, public _window: ChasePayHostWindow = window) {}\n\n load(testMode?: boolean): Promise {\n return this._scriptLoader\n .loadScript(\n `//pwc${\n testMode ? 'psb' : ''\n }.chase.com/pwc/checkout/js/v20170521/list.action?type=raw&applId=PWC&channelId=CWC&version=1`,\n )\n .then(() => {\n if (!this._window.JPMC) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.JPMC;\n });\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if we are unable to synchronize the checkout details of a\n * shopper with a hosted / remote checkout provider (i.e.: Amazon).\n */\nexport default class RemoteCheckoutSynchronizationError extends StandardError {\n constructor(public error?: Error) {\n super(\n 'Unable to synchronize your checkout details with a third party provider. Please try again later.',\n );\n\n this.name = 'RemoteCheckoutSynchronizationError';\n this.type = 'remote_checkout_synchronization';\n }\n}\n","import { PaymentInitializeOptions } from '../..';\nimport { Checkout, InternalCheckoutSelectors } from '../../../checkout';\nimport PaymentMethod from '../../payment-method';\nimport {\n BraintreeModuleCreator,\n BraintreeVerifyPayload,\n GooglePayBraintreeSDK,\n} from '../braintree';\n\nexport enum CallbackTriggerType {\n INITIALIZE = 'INITIALIZE',\n SHIPPING_OPTION = 'SHIPPING_OPTION',\n SHIPPING_ADDRESS = 'SHIPPING_ADDRESS',\n OFFER = 'OFFER',\n}\n\nexport enum TotalPriceStatusType {\n ESTIMATED = 'ESTIMATED',\n FINAL = 'FINAL',\n NOT_CURRENTLY_KNOWN = 'NOT_CURRENTLY_KNOWN',\n}\n\nexport enum CallbackIntentsType {\n OFFER = 'OFFER',\n PAYMENT_AUTHORIZATION = 'PAYMENT_AUTHORIZATION',\n SHIPPING_ADDRESS = 'SHIPPING_ADDRESS',\n SHIPPING_OPTION = 'SHIPPING_OPTION',\n}\n\nexport type EnvironmentType = 'PRODUCTION' | 'TEST';\nexport type TokenizeType = 'AndroidPayCard' | 'CreditCard' | 'CARD';\n\nexport interface GooglePayInitializer {\n initialize(\n checkout: Checkout | void,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n publishableKey?: string,\n ): Promise;\n teardown(): Promise;\n parseResponse(paymentData: GooglePaymentData): Promise;\n}\n\nexport interface GooglePayProviderProcessor {\n initialize(options: PaymentInitializeOptions): Promise;\n processAdditionalAction(error: unknown): Promise;\n}\n\nexport type GooglePayCreator = BraintreeModuleCreator;\n\nexport interface GooglePayPaymentOptions {\n environment: EnvironmentType;\n paymentDataCallbacks?: {\n onPaymentDataChanged(\n intermediatePaymentData: IntermediatePaymentData,\n ): Promise;\n };\n}\n\nexport type GooglePayVerifyPayload = BraintreeVerifyPayload | undefined;\n\nexport interface GooglePayIsReadyToPayResponse {\n result: boolean;\n paymentMethodPresend?: boolean;\n}\n\nexport interface GooglePaySDK {\n payments: {\n api: {\n PaymentsClient: new (options: GooglePayPaymentOptions) => GooglePayClient;\n };\n };\n}\n\nexport interface GooglePayClient {\n isReadyToPay(options: object): Promise;\n loadPaymentData(paymentDataRequest: GooglePayPaymentDataRequestV2): Promise;\n createButton(options: { [key: string]: string | object }): HTMLElement;\n}\n\nexport interface GooglePayHostWindow extends Window {\n google?: GooglePaySDK;\n}\n\nexport interface TokenizePayload {\n nonce: string;\n tokenFormat?: string;\n details: {\n cardType: string;\n lastFour: string;\n lastTwo?: string;\n };\n description?: string;\n type: TokenizeType;\n binData?: {\n commercial: string;\n countryOfIssuance: string;\n debit: string;\n durbinRegulated: string;\n healthcare: string;\n issuingBank: string;\n payroll: string;\n prepaid: string;\n productId: string;\n };\n}\n\nexport interface GooglePaymentData {\n apiVersion: number;\n apiVersionMinor: number;\n paymentMethodData: {\n description: string;\n info: {\n cardDetails: string;\n cardNetwork: string;\n billingAddress: GooglePayAddress;\n };\n tokenizationData: {\n token: string;\n type: string;\n };\n type: TokenizeType;\n };\n shippingAddress: GooglePayAddress;\n email: string;\n}\n\nexport interface GooglePayAddress {\n address1: string;\n address2: string;\n address3: string;\n administrativeArea: string;\n companyName: string;\n countryCode: string;\n locality: string;\n name: string;\n postalCode: string;\n sortingCode: string;\n phoneNumber: string;\n}\n\nexport interface GooglePaymentsError {\n statusCode: string;\n statusMessage?: string;\n}\n\nexport interface PaymentMethodData {\n methodId: string;\n paymentData: {\n method: string;\n nonce: string;\n cardInformation: {\n type: string;\n number: string;\n };\n };\n}\n\nexport enum ButtonType {\n Long = 'long',\n Short = 'short',\n}\nexport enum ButtonColor {\n Default = 'default',\n Black = 'black',\n White = 'white',\n}\n\nexport interface TokenizationSpecification {\n type: string;\n parameters: {\n gateway: string;\n gatewayMerchantId?: string;\n 'braintree:apiVersion'?: string;\n 'braintree:clientKey'?: string;\n 'braintree:merchantId'?: string;\n 'braintree:sdkVersion'?: string;\n 'braintree:authorizationFingerprint'?: string;\n 'stripe:version'?: string;\n 'stripe:publishableKey'?: string;\n };\n}\n\nexport enum BillingAddressFormat {\n /*\n * Name, country code, and postal code (default).\n */\n Min = 'MIN',\n /*\n * Name, street address, locality, region, country code, and postal code.\n */\n Full = 'FULL',\n}\n\nexport interface GooglePayPaymentDataRequestV2 {\n apiVersion: number;\n apiVersionMinor: number;\n merchantInfo: {\n authJwt?: string;\n merchantId?: string;\n merchantName?: string;\n };\n allowedPaymentMethods: [\n {\n type: string;\n parameters: {\n allowedAuthMethods: string[];\n allowedCardNetworks: string[];\n allowPrepaidCards?: boolean;\n billingAddressRequired?: boolean;\n billingAddressParameters?: {\n format?: BillingAddressFormat;\n phoneNumberRequired?: boolean;\n };\n };\n tokenizationSpecification?: TokenizationSpecification;\n },\n ];\n transactionInfo: {\n currencyCode: string;\n countryCode?: string;\n totalPriceStatus?: TotalPriceStatusType;\n totalPrice?: string;\n checkoutOption?: string;\n };\n callbackIntents?: CallbackIntentsType[];\n emailRequired?: boolean;\n shippingAddressRequired?: boolean;\n shippingAddressParameters?: {\n allowedCountryCodes?: string[];\n phoneNumberRequired?: boolean;\n };\n}\n\nexport interface UpdatePaymentDataRequestPayload {\n apiVersion?: number;\n apiVersionMinor?: number;\n merchantInfo?: {\n authJwt?: string;\n merchantId?: string;\n merchantName?: string;\n };\n allowedPaymentMethods?: [\n {\n type: string;\n parameters: {\n allowedAuthMethods: string[];\n allowedCardNetworks: string[];\n allowPrepaidCards?: boolean;\n billingAddressRequired?: boolean;\n billingAddressParameters?: {\n format?: BillingAddressFormat;\n phoneNumberRequired?: boolean;\n };\n };\n tokenizationSpecification?: TokenizationSpecification;\n },\n ];\n transactionInfo?: {\n currencyCode: string;\n countryCode?: string;\n totalPriceStatus?: TotalPriceStatusType;\n totalPrice?: string;\n checkoutOption?: string;\n };\n callbackIntents?: CallbackIntentsType[];\n emailRequired?: boolean;\n shippingAddressRequired?: boolean;\n shippingAddressParameters?: {\n allowedCountryCodes?: string[];\n phoneNumberRequired?: boolean;\n };\n}\n\nexport interface NewTransactionInfo {\n newTransactionInfo: {\n currencyCode: string;\n totalPrice: string;\n totalPriceStatus: TotalPriceStatusType;\n };\n}\n\nexport interface IntermediatePaymentData {\n callbackTrigger: CallbackTriggerType;\n}\n\nexport type GooglePayTransactionInfo = Pick;\n","export function getFirstAndLastName(fullName: string): [string, string] {\n const nameParts = fullName.split(' ');\n\n if (nameParts.length === 1) {\n return [fullName, ''];\n }\n\n const firstName = nameParts.slice(0, -1).join(' ');\n const lastName = nameParts[nameParts.length - 1];\n\n return [firstName, lastName];\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { PaymentMethodInvalidError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { AddressRequestBody } from '../../../address';\nimport { BillingAddressActionCreator, BillingAddressUpdateRequestBody } from '../../../billing';\nimport { Checkout, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { SDK_VERSION_HEADERS } from '../../../common/http-request';\nimport { RemoteCheckoutSynchronizationError } from '../../../remote-checkout/errors';\nimport { ConsignmentActionCreator } from '../../../shipping';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\n\nimport {\n ButtonColor,\n ButtonType,\n EnvironmentType,\n GooglePayAddress,\n GooglePayClient,\n GooglePayInitializer,\n GooglePaymentData,\n GooglePayPaymentDataRequestV2,\n GooglePayPaymentOptions,\n GooglePaySDK,\n TokenizePayload,\n UpdatePaymentDataRequestPayload,\n} from './googlepay';\nimport { getFirstAndLastName } from './googlepay-get-first-and-last-name';\nimport GooglePayScriptLoader from './googlepay-script-loader';\n\nexport default class GooglePayPaymentProcessor {\n private _googlePayClient?: GooglePayClient;\n private _methodId?: string;\n private _paymentDataRequest?: GooglePayPaymentDataRequestV2;\n private _isBuyNowFlow = false;\n\n constructor(\n private _store: CheckoutStore,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _googlePayScriptLoader: GooglePayScriptLoader,\n private _googlePayInitializer: GooglePayInitializer,\n private _billingAddressActionCreator: BillingAddressActionCreator,\n private _consignmentActionCreator: ConsignmentActionCreator,\n private _requestSender: RequestSender,\n ) {}\n\n initialize(methodId: string, googlePayClientOptions?: GooglePayPaymentOptions): Promise {\n this._methodId = methodId;\n\n return this._configureWallet(googlePayClientOptions);\n }\n\n deinitialize(): Promise {\n return this._googlePayInitializer.teardown();\n }\n\n createButton(\n onClick: (event: Event) => Promise,\n buttonType: ButtonType = ButtonType.Short,\n buttonColor: ButtonColor = ButtonColor.Default,\n ): HTMLElement {\n if (!this._googlePayClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._googlePayClient.createButton({\n buttonColor,\n buttonType,\n onClick,\n });\n }\n\n updatePaymentDataRequest(paymentDataRequest: UpdatePaymentDataRequestPayload) {\n const existingPaymentDataRequest = this._getPaymentDataRequest();\n\n this._paymentDataRequest = {\n ...existingPaymentDataRequest,\n ...paymentDataRequest,\n merchantInfo: {\n ...(existingPaymentDataRequest.merchantInfo ?? {}),\n ...(paymentDataRequest.merchantInfo ?? {}),\n },\n transactionInfo: {\n ...(existingPaymentDataRequest.transactionInfo ?? {}),\n ...(paymentDataRequest.transactionInfo ?? {}),\n },\n shippingAddressParameters: {\n ...(existingPaymentDataRequest.shippingAddressParameters ?? {}),\n ...(paymentDataRequest.shippingAddressParameters ?? {}),\n },\n };\n }\n\n displayWallet(): Promise {\n if (!this._googlePayClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._googlePayClient.loadPaymentData(this._getPaymentDataRequest());\n }\n\n handleSuccess(paymentData: GooglePaymentData): Promise {\n return this._googlePayInitializer\n .parseResponse(paymentData)\n .then((tokenizePayload) => this._postForm(tokenizePayload))\n .then(() => this._updateBillingAddress(paymentData));\n }\n\n updateShippingAddress(shippingAddress: GooglePayAddress): Promise {\n return this._store.dispatch(\n this._consignmentActionCreator.updateAddress(\n this._mapGooglePayAddressToShippingAddress(shippingAddress),\n ),\n );\n }\n\n updateBuyNowFlowFlag(isBuyNowFlow: boolean): void {\n this._isBuyNowFlow = isBuyNowFlow;\n }\n\n private _configureWallet(\n googlePayClientOptions?: Partial,\n ): Promise {\n const features = this._store.getState().config.getStoreConfig()?.checkoutSettings.features;\n const options =\n features && features['INT-5826.google_hostname_alias']\n ? { params: { origin: window.location.hostname } }\n : undefined;\n const methodId = this._getMethodId();\n\n return this._store\n .dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId, options))\n .then((state) => {\n const checkout = this._getCheckout(state);\n const paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n const hasShippingAddress = !!state.shippingAddress.getShippingAddress();\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { testMode } = paymentMethod.config;\n\n return Promise.all([\n this._googlePayScriptLoader.load(),\n this._googlePayInitializer.initialize(\n checkout,\n paymentMethod,\n hasShippingAddress,\n ),\n ]).then(([googlePay, paymentDataRequest]) => {\n this._googlePayClient = this._getGooglePayClient(\n googlePay,\n testMode,\n googlePayClientOptions,\n );\n this._paymentDataRequest = paymentDataRequest;\n\n return this._googlePayClient\n .isReadyToPay({\n allowedPaymentMethods: [\n {\n type: paymentDataRequest.allowedPaymentMethods[0].type,\n parameters: {\n allowedAuthMethods:\n paymentDataRequest.allowedPaymentMethods[0].parameters\n .allowedAuthMethods,\n allowedCardNetworks:\n paymentDataRequest.allowedPaymentMethods[0].parameters\n .allowedCardNetworks,\n },\n },\n ],\n apiVersion: paymentDataRequest.apiVersion,\n apiVersionMinor: paymentDataRequest.apiVersionMinor,\n })\n .then((response) => {\n if (response.result) {\n return;\n }\n\n throw new PaymentMethodInvalidError();\n });\n });\n });\n }\n\n private _getCardInformation(cardInformation: { cardType: string; lastFour: string }) {\n return {\n type: cardInformation.cardType,\n number: cardInformation.lastFour,\n };\n }\n\n private _getCheckout(state: InternalCheckoutSelectors): Checkout | void {\n if (this._isBuyNowFlow) {\n return;\n }\n\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n return checkout;\n }\n\n private _getPaymentDataRequest(): GooglePayPaymentDataRequestV2 {\n if (!this._paymentDataRequest) {\n throw new RemoteCheckoutSynchronizationError();\n }\n\n return this._paymentDataRequest;\n }\n\n private _getGooglePayClient(\n google: GooglePaySDK,\n testMode?: boolean,\n googlePayClientOptions?: Partial,\n ): GooglePayClient {\n if (testMode === undefined) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const environment: EnvironmentType = testMode ? 'TEST' : 'PRODUCTION';\n\n return new google.payments.api.PaymentsClient({\n environment,\n ...(googlePayClientOptions ?? {}),\n });\n }\n\n private _getMethodId(): string {\n if (!this._methodId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._methodId;\n }\n\n private _mapGooglePayAddressToBillingAddress(\n paymentData: GooglePaymentData,\n id: string,\n customerEmail?: string,\n ): BillingAddressUpdateRequestBody {\n const fullName = paymentData.paymentMethodData.info.billingAddress.name;\n const [firstName, lastName] = getFirstAndLastName(fullName);\n const address1 = paymentData.paymentMethodData.info.billingAddress.address1;\n const city = paymentData.paymentMethodData.info.billingAddress.locality;\n const postalCode = paymentData.paymentMethodData.info.billingAddress.postalCode;\n const countryCode = paymentData.paymentMethodData.info.billingAddress.countryCode;\n\n if (!firstName || !address1 || !city || !postalCode || !countryCode) {\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n\n return {\n id,\n firstName,\n lastName,\n company: paymentData.paymentMethodData.info.billingAddress.companyName,\n address1,\n address2:\n paymentData.paymentMethodData.info.billingAddress.address2 +\n paymentData.paymentMethodData.info.billingAddress.address3,\n city,\n stateOrProvince: paymentData.paymentMethodData.info.billingAddress.administrativeArea,\n stateOrProvinceCode:\n paymentData.paymentMethodData.info.billingAddress.administrativeArea,\n postalCode,\n countryCode,\n phone: paymentData.paymentMethodData.info.billingAddress.phoneNumber,\n customFields: [],\n email: customerEmail || paymentData.email,\n };\n }\n\n private _mapGooglePayAddressToShippingAddress(address: GooglePayAddress): AddressRequestBody {\n const [firstName, lastName] = getFirstAndLastName(address.name);\n\n return {\n firstName,\n lastName,\n company: address.companyName,\n address1: address.address1,\n address2: address.address2 + address.address3,\n city: address.locality,\n stateOrProvince: address.administrativeArea,\n stateOrProvinceCode: address.administrativeArea,\n postalCode: address.postalCode,\n countryCode: address.countryCode,\n phone: address.phoneNumber,\n customFields: [],\n };\n }\n\n private _postForm(postPaymentData: TokenizePayload): Promise> {\n const cardInformation = postPaymentData.details;\n const buyNowCartId = this._isBuyNowFlow\n ? this._store.getState().cart.getCartOrThrow().id\n : undefined;\n\n return this._requestSender.post('/checkout.php', {\n headers: {\n Accept: 'text/html',\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...SDK_VERSION_HEADERS,\n },\n body: {\n payment_type: postPaymentData.type,\n nonce: postPaymentData.nonce,\n tokenFormat: postPaymentData.tokenFormat,\n provider: this._getMethodId(),\n action: 'set_external_checkout',\n card_information: this._getCardInformation(cardInformation),\n ...(buyNowCartId && { cart_id: buyNowCartId }),\n },\n });\n }\n\n private _updateBillingAddress(\n paymentData: GooglePaymentData,\n ): Promise {\n const remoteBillingAddress = this._store.getState().billingAddress.getBillingAddress();\n\n if (!remoteBillingAddress) {\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n\n const googlePayAddressMapped = this._mapGooglePayAddressToBillingAddress(\n paymentData,\n remoteBillingAddress.id,\n remoteBillingAddress.email,\n );\n\n return this._store.dispatch(\n this._billingAddressActionCreator.updateAddress(googlePayAddressMapped),\n );\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { GooglePayHostWindow, GooglePaySDK } from './googlepay';\n\nexport default class GooglePayScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _window: GooglePayHostWindow = window,\n ) {}\n\n load(): Promise {\n return this._scriptLoader.loadScript('https://pay.google.com/gp/p/js/pay.js').then(() => {\n if (!this._window.google) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.google;\n });\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { BillingAddressActionCreator, BillingAddressRequestSender } from '../../../billing';\nimport { CheckoutRequestSender, CheckoutStore } from '../../../checkout';\nimport { ConsignmentActionCreator, ConsignmentRequestSender } from '../../../shipping';\nimport { SubscriptionsActionCreator, SubscriptionsRequestSender } from '../../../subscription';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport PaymentMethodRequestSender from '../../payment-method-request-sender';\n\nimport { GooglePayInitializer } from './googlepay';\nimport GooglePayPaymentProcessor from './googlepay-payment-processor';\nimport GooglePayScriptLoader from './googlepay-script-loader';\n\nexport default function createGooglePayPaymentProcessor(\n store: CheckoutStore,\n initializer: GooglePayInitializer,\n): GooglePayPaymentProcessor {\n const requestSender = createRequestSender();\n const scriptLoader = getScriptLoader();\n\n return new GooglePayPaymentProcessor(\n store,\n new PaymentMethodActionCreator(new PaymentMethodRequestSender(requestSender)),\n new GooglePayScriptLoader(scriptLoader),\n initializer,\n new BillingAddressActionCreator(\n new BillingAddressRequestSender(requestSender),\n new SubscriptionsActionCreator(new SubscriptionsRequestSender(requestSender)),\n ),\n new ConsignmentActionCreator(\n new ConsignmentRequestSender(requestSender),\n new CheckoutRequestSender(requestSender),\n ),\n requestSender,\n );\n}\n","import { round } from 'lodash';\n\nimport { Checkout } from '../../../checkout';\nimport PaymentMethod from '../../payment-method';\n\nimport {\n BillingAddressFormat,\n GooglePayInitializer,\n GooglePaymentData,\n GooglePayPaymentDataRequestV2,\n TokenizePayload,\n TotalPriceStatusType,\n} from './googlepay';\n\nexport default class GooglePayAdyenV2Initializer implements GooglePayInitializer {\n initialize(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): Promise {\n return Promise.resolve(\n this._getGooglePayPaymentDataRequest(checkout, paymentMethod, hasShippingAddress),\n );\n }\n\n teardown(): Promise {\n return Promise.resolve();\n }\n\n parseResponse(paymentData: GooglePaymentData): Promise {\n const {\n paymentMethodData: {\n type,\n tokenizationData: { token },\n info: { cardNetwork: cardType, cardDetails: lastFour },\n },\n } = paymentData;\n\n return Promise.resolve({\n type,\n nonce: token,\n details: {\n cardType,\n lastFour,\n },\n });\n }\n\n private _getGooglePayPaymentDataRequest(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): GooglePayPaymentDataRequestV2 {\n const currencyCode = checkout?.cart.currency.code || '';\n const totalPrice = checkout?.outstandingBalance\n ? round(checkout.outstandingBalance, 2).toFixed(2)\n : '';\n\n const {\n initializationData: {\n gatewayMerchantId,\n storeCountry: countryCode,\n googleMerchantName: merchantName,\n googleMerchantId: merchantId,\n platformToken: authJwt,\n },\n supportedCards,\n } = paymentMethod;\n\n return {\n apiVersion: 2,\n apiVersionMinor: 0,\n merchantInfo: {\n authJwt,\n merchantId,\n merchantName,\n },\n allowedPaymentMethods: [\n {\n type: 'CARD',\n parameters: {\n allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n allowedCardNetworks: supportedCards.map((card) =>\n card === 'MC' ? 'MASTERCARD' : card,\n ),\n billingAddressRequired: true,\n billingAddressParameters: {\n format: BillingAddressFormat.Full,\n phoneNumberRequired: true,\n },\n },\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY',\n parameters: {\n gateway: 'adyen',\n gatewayMerchantId,\n },\n },\n },\n ],\n transactionInfo: {\n countryCode,\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n emailRequired: true,\n shippingAddressRequired: !hasShippingAddress,\n shippingAddressParameters: {\n phoneNumberRequired: true,\n },\n };\n }\n}\n","import { round } from 'lodash';\n\nimport { Checkout } from '../../../checkout';\nimport PaymentMethod from '../../payment-method';\n\nimport {\n BillingAddressFormat,\n GooglePayInitializer,\n GooglePaymentData,\n GooglePayPaymentDataRequestV2,\n TokenizePayload,\n TotalPriceStatusType,\n} from './googlepay';\n\nexport default class GooglePayAdyenV3Initializer implements GooglePayInitializer {\n initialize(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): Promise {\n return Promise.resolve(\n this._getGooglePayPaymentDataRequest(checkout, paymentMethod, hasShippingAddress),\n );\n }\n\n teardown(): Promise {\n return Promise.resolve();\n }\n\n parseResponse(paymentData: GooglePaymentData): Promise {\n const {\n paymentMethodData: {\n type,\n tokenizationData: { token },\n info: { cardNetwork: cardType, cardDetails: lastFour },\n },\n } = paymentData;\n\n return Promise.resolve({\n type,\n nonce: token,\n details: {\n cardType,\n lastFour,\n },\n });\n }\n\n private _getGooglePayPaymentDataRequest(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): GooglePayPaymentDataRequestV2 {\n const currencyCode = checkout?.cart.currency.code || '';\n const totalPrice = checkout?.outstandingBalance\n ? round(checkout.outstandingBalance, 2).toFixed(2)\n : '';\n\n const {\n initializationData: {\n gatewayMerchantId,\n storeCountry: countryCode,\n googleMerchantName: merchantName,\n googleMerchantId: merchantId,\n platformToken: authJwt,\n },\n supportedCards,\n } = paymentMethod;\n\n return {\n apiVersion: 2,\n apiVersionMinor: 0,\n merchantInfo: {\n authJwt,\n merchantId,\n merchantName,\n },\n allowedPaymentMethods: [\n {\n type: 'CARD',\n parameters: {\n allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n allowedCardNetworks: supportedCards.map((card) =>\n card === 'MC' ? 'MASTERCARD' : card,\n ),\n billingAddressRequired: true,\n billingAddressParameters: {\n format: BillingAddressFormat.Full,\n phoneNumberRequired: true,\n },\n },\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY',\n parameters: {\n gateway: 'adyen',\n gatewayMerchantId,\n },\n },\n },\n ],\n transactionInfo: {\n countryCode,\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n emailRequired: true,\n shippingAddressRequired: !hasShippingAddress,\n shippingAddressParameters: {\n phoneNumberRequired: true,\n },\n };\n }\n}\n","import { round } from 'lodash';\n\nimport { PaymentMethod } from '../..';\nimport { Checkout } from '../../../checkout';\n\nimport {\n BillingAddressFormat,\n GooglePayInitializer,\n GooglePaymentData,\n GooglePayPaymentDataRequestV2,\n TokenizationSpecification,\n TokenizePayload,\n TotalPriceStatusType,\n} from './googlepay';\n\nconst baseRequest = {\n apiVersion: 2,\n apiVersionMinor: 0,\n};\n\nexport default class GooglePayAuthorizeNetInitializer implements GooglePayInitializer {\n initialize(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): Promise {\n return Promise.resolve(\n this._getGooglePaymentDataRequest(checkout, paymentMethod, hasShippingAddress),\n );\n }\n\n teardown(): Promise {\n return Promise.resolve();\n }\n\n parseResponse(paymentData: GooglePaymentData): Promise {\n const {\n paymentMethodData: {\n type,\n tokenizationData: { token },\n info: { cardNetwork: cardType, cardDetails: lastFour },\n },\n } = paymentData;\n\n return Promise.resolve({\n type,\n nonce: btoa(token),\n details: {\n cardType,\n lastFour,\n },\n });\n }\n\n private _getGooglePaymentDataRequest(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): GooglePayPaymentDataRequestV2 {\n const currencyCode = checkout?.cart.currency.code || '';\n const totalPrice = checkout?.outstandingBalance\n ? round(checkout.outstandingBalance, 2).toFixed(2)\n : '';\n\n const {\n initializationData: {\n paymentGatewayId: gatewayMerchantId,\n storeCountry: countryCode,\n googleMerchantName: merchantName,\n googleMerchantId: merchantId,\n platformToken: authJwt,\n },\n supportedCards,\n } = paymentMethod;\n\n const paymentGatewaySpecification = this._getPaymentGatewaySpecification(gatewayMerchantId);\n const cardPaymentMethod = this._getCardPaymentMethod(\n paymentGatewaySpecification,\n supportedCards,\n );\n\n return {\n ...baseRequest,\n allowedPaymentMethods: [cardPaymentMethod],\n transactionInfo: {\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n currencyCode,\n countryCode,\n },\n merchantInfo: {\n merchantName,\n merchantId,\n authJwt,\n },\n emailRequired: true,\n shippingAddressRequired: !hasShippingAddress,\n shippingAddressParameters: {\n phoneNumberRequired: true,\n },\n };\n }\n\n private _getPaymentGatewaySpecification(gatewayMerchantId: string) {\n return {\n type: 'PAYMENT_GATEWAY',\n parameters: {\n gateway: 'authorizenet',\n gatewayMerchantId,\n },\n };\n }\n\n private _getCardPaymentMethod(\n tokenizationSpecification: TokenizationSpecification,\n supportedCards: string[],\n ) {\n return {\n type: 'CARD',\n parameters: {\n allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n allowedCardNetworks: supportedCards.map((card) =>\n card === 'MC' ? 'MASTERCARD' : card,\n ),\n billingAddressRequired: true,\n billingAddressParameters: {\n format: BillingAddressFormat.Full,\n phoneNumberRequired: true,\n },\n },\n tokenizationSpecification,\n };\n }\n}\n","import { round } from 'lodash';\n\nimport { Checkout } from '../../../checkout';\nimport PaymentMethod from '../../payment-method';\n\nimport {\n BillingAddressFormat,\n GooglePayInitializer,\n GooglePaymentData,\n GooglePayPaymentDataRequestV2,\n TokenizePayload,\n TotalPriceStatusType,\n} from './googlepay';\n\nexport default class GooglePayBNZInitializer implements GooglePayInitializer {\n initialize(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): Promise {\n return Promise.resolve(\n this._getGooglePayPaymentDataRequest(checkout, paymentMethod, hasShippingAddress),\n );\n }\n\n teardown(): Promise {\n return Promise.resolve();\n }\n\n parseResponse(paymentData: GooglePaymentData): Promise {\n const {\n paymentMethodData: {\n type,\n tokenizationData: { token },\n info: { cardNetwork: cardType, cardDetails: lastFour },\n },\n } = paymentData;\n\n return Promise.resolve({\n nonce: btoa(token),\n type,\n details: {\n cardType,\n lastFour,\n },\n });\n }\n\n private _getGooglePayPaymentDataRequest(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): GooglePayPaymentDataRequestV2 {\n const currencyCode = checkout?.cart.currency.code || '';\n const totalPrice = checkout?.outstandingBalance\n ? round(checkout.outstandingBalance, 2).toFixed(2)\n : '';\n\n const {\n initializationData: {\n gatewayMerchantId,\n googleMerchantName: merchantName,\n googleMerchantId: merchantId,\n platformToken: authJwt,\n },\n supportedCards,\n } = paymentMethod;\n\n return {\n apiVersion: 2,\n apiVersionMinor: 0,\n merchantInfo: {\n authJwt,\n merchantId,\n merchantName,\n },\n allowedPaymentMethods: [\n {\n type: 'CARD',\n parameters: {\n allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n allowedCardNetworks: supportedCards.map((card) =>\n card === 'MC' ? 'MASTERCARD' : card,\n ),\n billingAddressRequired: true,\n billingAddressParameters: {\n format: BillingAddressFormat.Full,\n phoneNumberRequired: true,\n },\n },\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY',\n parameters: {\n gateway: 'cybersource',\n gatewayMerchantId,\n },\n },\n },\n ],\n transactionInfo: {\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n emailRequired: true,\n shippingAddressRequired: !hasShippingAddress,\n shippingAddressParameters: {\n phoneNumberRequired: true,\n },\n };\n }\n}\n","import { round } from 'lodash';\n\nimport { Checkout } from '../../../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../../../common/error/errors';\nimport PaymentMethod from '../../payment-method';\nimport { BraintreeSDKCreator, GooglePayBraintreeSDK } from '../braintree';\n\nimport {\n BillingAddressFormat,\n GooglePayInitializer,\n GooglePaymentData,\n GooglePayPaymentDataRequestV2,\n TokenizePayload,\n TotalPriceStatusType,\n} from './googlepay';\nimport {\n GooglePayBraintreeDataRequest,\n GooglePayBraintreePaymentDataRequestV1,\n} from './googlepay-braintree';\n\nexport default class GooglePayBraintreeInitializer implements GooglePayInitializer {\n private _googlePaymentInstance!: GooglePayBraintreeSDK;\n\n constructor(private _braintreeSDKCreator: BraintreeSDKCreator) {}\n\n initialize(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): Promise {\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._braintreeSDKCreator.initialize(paymentMethod.clientToken);\n\n return this._braintreeSDKCreator\n .getGooglePaymentComponent()\n .then((googleBraintreePaymentInstance) => {\n this._googlePaymentInstance = googleBraintreePaymentInstance;\n\n return this._createGooglePayPayload(\n checkout,\n paymentMethod.initializationData,\n hasShippingAddress,\n );\n });\n }\n\n teardown(): Promise {\n return this._braintreeSDKCreator.teardown();\n }\n\n parseResponse(paymentData: GooglePaymentData): Promise {\n const payload = JSON.parse(paymentData.paymentMethodData.tokenizationData.token)\n .androidPayCards[0];\n\n return Promise.resolve({\n nonce: payload.nonce,\n type: payload.type,\n description: payload.description,\n details: {\n cardType: payload.details.cardType,\n lastFour: payload.details.lastFour,\n lastTwo: payload.details.lastTwo,\n },\n binData: payload.binData,\n });\n }\n\n private _createGooglePayPayload(\n checkout: Checkout | undefined,\n initializationData: any,\n hasShippingAddress: boolean,\n ): GooglePayPaymentDataRequestV2 {\n if (!initializationData.platformToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const currencyCode = checkout?.cart.currency.code || '';\n const totalPrice = checkout?.outstandingBalance\n ? round(checkout.outstandingBalance, 2).toFixed(2)\n : '';\n\n const googlePayBraintreePaymentDataRequest: GooglePayBraintreeDataRequest = {\n merchantInfo: {\n authJwt: initializationData.platformToken,\n merchantName: initializationData.googleMerchantName,\n merchantId: initializationData.googleMerchantId,\n },\n transactionInfo: {\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n cardRequirements: {\n billingAddressRequired: true,\n billingAddressFormat: 'FULL',\n },\n shippingAddressRequired: !hasShippingAddress,\n emailRequired: true,\n phoneNumberRequired: true,\n };\n\n return this._mapGooglePayBraintreeDataRequestToGooglePayDataRequestV2(\n this._googlePaymentInstance.createPaymentDataRequest(\n googlePayBraintreePaymentDataRequest,\n ),\n );\n }\n\n private _mapGooglePayBraintreeDataRequestToGooglePayDataRequestV2(\n googlePayBraintreeDataRequestV1: GooglePayBraintreePaymentDataRequestV1,\n ): GooglePayPaymentDataRequestV2 {\n return {\n apiVersion: 2,\n apiVersionMinor: 0,\n merchantInfo: {\n authJwt: googlePayBraintreeDataRequestV1.merchantInfo.authJwt,\n merchantId: googlePayBraintreeDataRequestV1.merchantInfo.merchantId,\n merchantName: googlePayBraintreeDataRequestV1.merchantInfo.merchantName,\n },\n allowedPaymentMethods: [\n {\n type: 'CARD',\n parameters: {\n allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n allowedCardNetworks:\n googlePayBraintreeDataRequestV1.cardRequirements.allowedCardNetworks,\n billingAddressRequired: true,\n billingAddressParameters: {\n format: BillingAddressFormat.Full,\n phoneNumberRequired: true,\n },\n },\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY',\n parameters: {\n gateway: 'braintree',\n 'braintree:apiVersion': 'v1',\n 'braintree:authorizationFingerprint':\n googlePayBraintreeDataRequestV1.paymentMethodTokenizationParameters\n .parameters['braintree:authorizationFingerprint'],\n 'braintree:merchantId':\n googlePayBraintreeDataRequestV1.paymentMethodTokenizationParameters\n .parameters['braintree:merchantId'],\n 'braintree:sdkVersion':\n googlePayBraintreeDataRequestV1.paymentMethodTokenizationParameters\n .parameters['braintree:sdkVersion'],\n },\n },\n },\n ],\n transactionInfo: googlePayBraintreeDataRequestV1.transactionInfo,\n emailRequired: true,\n shippingAddressRequired: googlePayBraintreeDataRequestV1.shippingAddressRequired,\n shippingAddressParameters: {\n phoneNumberRequired: googlePayBraintreeDataRequestV1.phoneNumberRequired,\n },\n };\n }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\nimport { round } from 'lodash';\n\nimport { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Checkout } from '../../../checkout';\nimport { InvalidArgumentError } from '../../../common/error/errors';\nimport { ContentType } from '../../../common/http-request';\nimport PaymentMethod from '../../payment-method';\nimport { CheckoutcomGooglePayToken, CheckoutcomToken } from '../checkoutcom';\n\nimport {\n BillingAddressFormat,\n GooglePayInitializer,\n GooglePaymentData,\n GooglePayPaymentDataRequestV2,\n TokenizePayload,\n TotalPriceStatusType,\n} from './googlepay';\n\nexport default class GooglePayCheckoutcomInitializer implements GooglePayInitializer {\n private _publishableKey = '';\n private _testMode = true;\n private _errorMessage = 'Unable to parse response from GooglePay.';\n\n constructor(private _requestSender: RequestSender) {}\n\n async initialize(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): Promise {\n this._publishableKey = paymentMethod.initializationData.checkoutcomkey;\n this._testMode = !!paymentMethod.config.testMode;\n\n return this._mapGooglePayCheckoutcomDataRequestToGooglePayDataRequestV2(\n checkout,\n paymentMethod.initializationData,\n hasShippingAddress,\n );\n }\n\n teardown(): Promise {\n return Promise.resolve();\n }\n\n async parseResponse(paymentData: GooglePaymentData): Promise {\n let token;\n\n try {\n token = JSON.parse(paymentData.paymentMethodData.tokenizationData.token);\n } catch (err) {\n throw new InvalidArgumentError(this._errorMessage);\n }\n\n if (!token.signature || !token.protocolVersion || !token.signedMessage) {\n throw new PaymentMethodFailedError(this._errorMessage);\n }\n\n const finalToken = await this._convertToken(this._testMode, this._publishableKey, token);\n\n const payload: TokenizePayload = {\n nonce: finalToken.token,\n type: 'CreditCard',\n description: paymentData.paymentMethodData.description,\n details: {\n cardType: paymentData.paymentMethodData.info.cardNetwork,\n lastFour: paymentData.paymentMethodData.info.cardDetails,\n },\n };\n\n if (finalToken.token_format) {\n payload.tokenFormat = finalToken.token_format;\n }\n\n return payload;\n }\n\n private async _convertToken(\n testMode: boolean,\n checkoutcomkey: string,\n token: CheckoutcomGooglePayToken,\n ): Promise {\n const checkoutcomToken: CheckoutcomToken = await this._requestCheckoutcomTokenize(\n testMode,\n checkoutcomkey,\n {\n type: 'googlepay',\n token_data: token,\n },\n );\n\n if (!checkoutcomToken || !checkoutcomToken.token) {\n throw new PaymentMethodFailedError('Unable to parse response from Checkout.com');\n }\n\n return checkoutcomToken;\n }\n\n private async _requestCheckoutcomTokenize(\n testMode: boolean,\n checkoutcomKey: string,\n data = {},\n ): Promise {\n const TEST_URL = 'https://api.sandbox.checkout.com/tokens';\n const LIVE_URL = 'https://api.checkout.com/tokens';\n\n const url = testMode ? TEST_URL : LIVE_URL;\n\n const response = await this._requestSender.post(url, {\n credentials: false,\n body: data,\n headers: {\n 'Content-Type': ContentType.Json,\n Authorization: checkoutcomKey,\n 'X-XSRF-TOKEN': null,\n },\n });\n\n return response.body as CheckoutcomToken;\n }\n\n private _mapGooglePayCheckoutcomDataRequestToGooglePayDataRequestV2(\n checkout: Checkout | undefined,\n initializationData: any,\n hasShippingAddress: boolean,\n ): GooglePayPaymentDataRequestV2 {\n const currencyCode = checkout?.cart.currency.code || '';\n const totalPrice = checkout?.outstandingBalance\n ? round(checkout.outstandingBalance, 2).toFixed(2)\n : '';\n\n return {\n apiVersion: 2,\n apiVersionMinor: 0,\n merchantInfo: {\n authJwt: initializationData.platformToken,\n merchantId: initializationData.googleMerchantId,\n merchantName: initializationData.googleMerchantName,\n },\n allowedPaymentMethods: [\n {\n type: 'CARD',\n parameters: {\n allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n allowedCardNetworks: ['AMEX', 'DISCOVER', 'JCB', 'MASTERCARD', 'VISA'],\n billingAddressRequired: true,\n billingAddressParameters: {\n format: BillingAddressFormat.Full,\n phoneNumberRequired: true,\n },\n },\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY',\n parameters: {\n gateway: 'checkoutltd',\n gatewayMerchantId: initializationData.checkoutcomkey,\n },\n },\n },\n ],\n transactionInfo: {\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n emailRequired: true,\n shippingAddressRequired: !hasShippingAddress,\n shippingAddressParameters: {\n phoneNumberRequired: true,\n },\n };\n }\n}\n","import { round } from 'lodash';\n\nimport { Checkout } from '../../../checkout';\nimport PaymentMethod from '../../payment-method';\n\nimport {\n BillingAddressFormat,\n GooglePayInitializer,\n GooglePaymentData,\n GooglePayPaymentDataRequestV2,\n TokenizePayload,\n TotalPriceStatusType,\n} from './googlepay';\n\nexport default class GooglePayCybersourceV2Initializer implements GooglePayInitializer {\n initialize(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): Promise {\n return Promise.resolve(\n this._getGooglePayPaymentDataRequest(checkout, paymentMethod, hasShippingAddress),\n );\n }\n\n teardown(): Promise {\n return Promise.resolve();\n }\n\n parseResponse(paymentData: GooglePaymentData): Promise {\n const {\n paymentMethodData: {\n type,\n tokenizationData: { token },\n info: { cardNetwork: cardType, cardDetails: lastFour },\n },\n } = paymentData;\n\n return Promise.resolve({\n nonce: btoa(token),\n type,\n details: {\n cardType,\n lastFour,\n },\n });\n }\n\n private _getGooglePayPaymentDataRequest(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): GooglePayPaymentDataRequestV2 {\n const currencyCode = checkout?.cart.currency.code || '';\n const totalPrice = checkout?.outstandingBalance\n ? round(checkout.outstandingBalance, 2).toFixed(2)\n : '';\n\n const {\n initializationData: {\n gatewayMerchantId,\n googleMerchantName: merchantName,\n googleMerchantId: merchantId,\n platformToken: authJwt,\n },\n supportedCards,\n } = paymentMethod;\n\n return {\n apiVersion: 2,\n apiVersionMinor: 0,\n merchantInfo: {\n authJwt,\n merchantId,\n merchantName,\n },\n allowedPaymentMethods: [\n {\n type: 'CARD',\n parameters: {\n allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n allowedCardNetworks: supportedCards.map((card) =>\n card === 'MC' ? 'MASTERCARD' : card,\n ),\n billingAddressRequired: true,\n billingAddressParameters: {\n format: BillingAddressFormat.Full,\n phoneNumberRequired: true,\n },\n },\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY',\n parameters: {\n gateway: 'cybersource',\n gatewayMerchantId,\n },\n },\n },\n ],\n transactionInfo: {\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n emailRequired: true,\n shippingAddressRequired: !hasShippingAddress,\n shippingAddressParameters: {\n phoneNumberRequired: true,\n },\n };\n }\n}\n","import { round } from 'lodash';\n\nimport { Checkout } from '../../../checkout';\nimport PaymentMethod from '../../payment-method';\n\nimport {\n BillingAddressFormat,\n GooglePayInitializer,\n GooglePaymentData,\n GooglePayPaymentDataRequestV2,\n TokenizePayload,\n TotalPriceStatusType,\n} from './googlepay';\n\nexport default class GooglePayOrbitalInitializer implements GooglePayInitializer {\n initialize(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): Promise {\n return Promise.resolve(\n this._getGooglePayPaymentDataRequest(checkout, paymentMethod, hasShippingAddress),\n );\n }\n\n teardown(): Promise {\n return Promise.resolve();\n }\n\n parseResponse(paymentData: GooglePaymentData): Promise {\n const {\n paymentMethodData: {\n type,\n tokenizationData: { token },\n info: { cardNetwork: cardType, cardDetails: lastFour },\n },\n } = paymentData;\n\n return Promise.resolve({\n nonce: btoa(token),\n type,\n details: {\n cardType,\n lastFour,\n },\n });\n }\n\n private _getGooglePayPaymentDataRequest(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): GooglePayPaymentDataRequestV2 {\n const currencyCode = checkout?.cart.currency.code || '';\n const totalPrice = checkout?.outstandingBalance\n ? round(checkout.outstandingBalance, 2).toFixed(2)\n : '';\n\n const {\n initializationData: {\n gatewayMerchantId,\n googleMerchantName: merchantName,\n googleMerchantId: merchantId,\n platformToken: authJwt,\n },\n supportedCards,\n } = paymentMethod;\n\n return {\n apiVersion: 2,\n apiVersionMinor: 0,\n merchantInfo: {\n authJwt,\n merchantId,\n merchantName,\n },\n allowedPaymentMethods: [\n {\n type: 'CARD',\n parameters: {\n allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n allowedCardNetworks: supportedCards.map((card) =>\n card === 'MC' ? 'MASTERCARD' : card,\n ),\n billingAddressRequired: true,\n billingAddressParameters: {\n format: BillingAddressFormat.Full,\n phoneNumberRequired: true,\n },\n },\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY',\n parameters: {\n gateway: 'chase',\n gatewayMerchantId,\n },\n },\n },\n ],\n transactionInfo: {\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n emailRequired: true,\n shippingAddressRequired: !hasShippingAddress,\n shippingAddressParameters: {\n phoneNumberRequired: true,\n },\n };\n }\n}\n","import { round } from 'lodash';\n\nimport { Checkout } from '../../../checkout';\nimport { InvalidArgumentError } from '../../../common/error/errors';\nimport PaymentMethod from '../../payment-method';\n\nimport {\n BillingAddressFormat,\n GooglePayInitializer,\n GooglePaymentData,\n GooglePayPaymentDataRequestV2,\n TokenizePayload,\n TotalPriceStatusType,\n} from './googlepay';\n\nexport default class GooglePayStripeInitializer implements GooglePayInitializer {\n initialize(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): Promise {\n return Promise.resolve(\n this._getGooglePayPaymentDataRequest(checkout, paymentMethod, hasShippingAddress),\n );\n }\n\n teardown(): Promise {\n return Promise.resolve();\n }\n\n parseResponse(paymentData: GooglePaymentData): Promise {\n try {\n const payload = JSON.parse(paymentData.paymentMethodData.tokenizationData.token);\n\n return Promise.resolve({\n nonce: payload.id,\n type: payload.type,\n details: {\n cardType: payload.card.brand,\n lastFour: payload.card.last4,\n },\n });\n } catch (err) {\n throw new InvalidArgumentError('Unable to parse response from Google Pay.');\n }\n }\n\n private _getGooglePayPaymentDataRequest(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): GooglePayPaymentDataRequestV2 {\n const currencyCode = checkout?.cart.currency.code || '';\n const totalPrice = checkout?.outstandingBalance\n ? round(checkout.outstandingBalance, 2).toFixed(2)\n : '';\n const consignments = checkout?.consignments || [];\n\n const {\n initializationData: {\n googleMerchantName: merchantName,\n googleMerchantId: merchantId,\n platformToken: authJwt,\n stripeVersion,\n stripePublishableKey,\n stripeConnectedAccount,\n bopis,\n },\n supportedCards,\n } = paymentMethod;\n\n const isPickup = consignments.every((consignment) => consignment.selectedPickupOption);\n\n return {\n apiVersion: 2,\n apiVersionMinor: 0,\n merchantInfo: {\n authJwt,\n merchantId,\n merchantName,\n },\n allowedPaymentMethods: [\n {\n type: 'CARD',\n parameters: {\n allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n allowedCardNetworks: supportedCards.map((card) =>\n card === 'MC' ? 'MASTERCARD' : card,\n ),\n billingAddressRequired: true,\n billingAddressParameters: {\n format: BillingAddressFormat.Full,\n phoneNumberRequired: true,\n },\n },\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY',\n parameters: {\n gateway: 'stripe',\n 'stripe:version': stripeVersion,\n 'stripe:publishableKey': `${stripePublishableKey}/${stripeConnectedAccount}`,\n },\n },\n },\n ],\n transactionInfo: {\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n emailRequired: true,\n shippingAddressRequired:\n bopis?.enabled && isPickup && bopis?.requiredAddress === 'none'\n ? false\n : !hasShippingAddress,\n shippingAddressParameters: {\n phoneNumberRequired: true,\n },\n };\n }\n}\n","import { round } from 'lodash';\n\nimport { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Checkout } from '../../../checkout';\nimport { InvalidArgumentError } from '../../../common/error/errors';\nimport PaymentMethod from '../../payment-method';\n\nimport {\n BillingAddressFormat,\n GooglePayInitializer,\n GooglePaymentData,\n GooglePayPaymentDataRequestV2,\n TokenizePayload,\n TotalPriceStatusType,\n} from './googlepay';\n\nexport default class GooglePayStripeUPEInitializer implements GooglePayInitializer {\n initialize(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): Promise {\n return Promise.resolve(\n this._getGooglePayPaymentDataRequest(checkout, paymentMethod, hasShippingAddress),\n );\n }\n\n teardown(): Promise {\n return Promise.resolve();\n }\n\n parseResponse(paymentData: GooglePaymentData): Promise {\n let payload;\n\n try {\n payload = JSON.parse(paymentData.paymentMethodData.tokenizationData.token);\n } catch (err) {\n throw new InvalidArgumentError('Unable to parse response from Google Pay.');\n }\n\n if (\n !payload.id ||\n !payload.type ||\n !payload.card ||\n !payload.card.brand ||\n !payload.card.last4\n ) {\n throw new PaymentMethodFailedError('Unable to parse response from Google Pay.');\n }\n\n return Promise.resolve({\n nonce: payload.id,\n type: payload.type,\n details: {\n cardType: payload.card.brand,\n lastFour: payload.card.last4,\n },\n });\n }\n\n private _getGooglePayPaymentDataRequest(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): GooglePayPaymentDataRequestV2 {\n const currencyCode = checkout?.cart.currency.code || '';\n const decimalPlaces = checkout?.cart.currency.decimalPlaces || 2;\n const totalPrice = checkout?.outstandingBalance\n ? round(checkout.outstandingBalance, decimalPlaces).toFixed(decimalPlaces)\n : '';\n\n const {\n initializationData: {\n googleMerchantName: merchantName,\n googleMerchantId: merchantId,\n platformToken: authJwt,\n stripeVersion,\n stripePublishableKey,\n stripeConnectedAccount,\n },\n supportedCards,\n } = paymentMethod;\n\n return {\n apiVersion: 2,\n apiVersionMinor: 0,\n merchantInfo: {\n authJwt,\n merchantId,\n merchantName,\n },\n allowedPaymentMethods: [\n {\n type: 'CARD',\n parameters: {\n allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n allowedCardNetworks: supportedCards.map((card) =>\n card === 'MC' ? 'MASTERCARD' : card,\n ),\n billingAddressRequired: true,\n billingAddressParameters: {\n format: BillingAddressFormat.Full,\n phoneNumberRequired: true,\n },\n },\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY',\n parameters: {\n gateway: 'stripe',\n 'stripe:version': stripeVersion,\n 'stripe:publishableKey': `${stripePublishableKey}/${stripeConnectedAccount}`,\n },\n },\n },\n ],\n transactionInfo: {\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n emailRequired: true,\n shippingAddressRequired: !hasShippingAddress,\n shippingAddressParameters: {\n phoneNumberRequired: true,\n },\n };\n }\n}\n","import { round } from 'lodash';\n\nimport { Checkout } from '../../../checkout';\nimport PaymentMethod from '../../payment-method';\n\nimport {\n BillingAddressFormat,\n GooglePayInitializer,\n GooglePaymentData,\n GooglePayPaymentDataRequestV2,\n TokenizePayload,\n TotalPriceStatusType,\n} from './googlepay';\n\nexport default class GooglePayWorldpayAccessInitializer implements GooglePayInitializer {\n initialize(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): Promise {\n return Promise.resolve(\n this._getGooglePayPaymentDataRequest(checkout, paymentMethod, hasShippingAddress),\n );\n }\n\n teardown(): Promise {\n return Promise.resolve();\n }\n\n parseResponse(paymentData: GooglePaymentData): Promise {\n const {\n paymentMethodData: {\n type,\n tokenizationData: { token },\n info: { cardNetwork: cardType, cardDetails: lastFour },\n },\n } = paymentData;\n\n return Promise.resolve({\n nonce: btoa(token),\n type,\n details: {\n cardType,\n lastFour,\n },\n });\n }\n\n private _getGooglePayPaymentDataRequest(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): GooglePayPaymentDataRequestV2 {\n const currencyCode = checkout?.cart.currency.code || '';\n const totalPrice = checkout?.outstandingBalance\n ? round(checkout.outstandingBalance, 2).toFixed(2)\n : '';\n\n const {\n initializationData: {\n gatewayMerchantId,\n storeCountry: countryCode,\n googleMerchantName: merchantName,\n googleMerchantId: merchantId,\n platformToken: authJwt,\n },\n supportedCards,\n } = paymentMethod;\n\n return {\n apiVersion: 2,\n apiVersionMinor: 0,\n merchantInfo: {\n authJwt,\n merchantId,\n merchantName,\n },\n allowedPaymentMethods: [\n {\n type: 'CARD',\n parameters: {\n allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n allowedCardNetworks: supportedCards.map((card) =>\n card === 'MC' ? 'MASTERCARD' : card,\n ),\n billingAddressRequired: true,\n billingAddressParameters: {\n format: BillingAddressFormat.Full,\n phoneNumberRequired: true,\n },\n },\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY',\n parameters: {\n gateway: 'worldpay',\n gatewayMerchantId,\n },\n },\n },\n ],\n transactionInfo: {\n countryCode,\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n emailRequired: true,\n shippingAddressRequired: !hasShippingAddress,\n shippingAddressParameters: {\n phoneNumberRequired: true,\n },\n };\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { Masterpass, MasterpassHostWindow } from './masterpass';\n\ninterface MasterpassScriptLoaderParams {\n useMasterpassSrc: boolean;\n language: string;\n testMode?: boolean;\n checkoutId?: string;\n}\n\nexport default class MasterpassScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n public _window: MasterpassHostWindow = window,\n ) {}\n\n async load({\n useMasterpassSrc,\n language,\n testMode,\n checkoutId,\n }: MasterpassScriptLoaderParams): Promise {\n if (useMasterpassSrc) {\n const subdomain = testMode ? 'sandbox.' : '';\n const params = [`locale=${language}`, `checkoutid=${checkoutId}`];\n\n const sourceUrl = [\n `https://${subdomain}src.mastercard.com/srci/integration/merchant.js`,\n params.join('&'),\n ].join('?');\n\n await this._scriptLoader.loadScript(sourceUrl);\n\n if (!this._window.masterpass) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.masterpass;\n }\n\n await this._scriptLoader.loadScript(\n `//${testMode ? 'sandbox.' : ''}masterpass.com/integration/merchant.js`,\n );\n\n if (!this._window.masterpass) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.masterpass;\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport {\n StripeElements,\n StripeElementsOptions,\n StripeHostWindow,\n StripeUPEClient,\n} from './stripe-upe';\n\nexport default class StripeUPEScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, private _window: StripeHostWindow = window) {}\n\n async getStripeClient(\n stripePublishableKey: string,\n stripeAccount: string,\n locale?: string,\n ): Promise {\n let stripeClient = this._window.bcStripeClient;\n\n if (!stripeClient) {\n const stripe = await this.load();\n\n stripeClient = stripe(stripePublishableKey, {\n stripeAccount,\n locale,\n betas: [\n 'payment_element_beta_2',\n 'alipay_pm_beta_1',\n 'link_default_integration_beta_1',\n 'shipping_address_element_beta_1',\n 'address_element_beta_1',\n ],\n apiVersion: '2020-03-02;alipay_beta=v1;link_beta=v1',\n });\n\n Object.assign(this._window, { bcStripeClient: stripeClient });\n }\n\n return stripeClient;\n }\n\n getElements(stripeClient: StripeUPEClient, options: StripeElementsOptions): StripeElements {\n let stripeElements = this._window.bcStripeElements;\n\n if (!stripeElements) {\n stripeElements = stripeClient.elements(options);\n\n Object.assign(this._window, { bcStripeElements: stripeElements });\n } else {\n stripeElements.fetchUpdates();\n stripeElements.update(options);\n }\n\n return stripeElements;\n }\n\n private async load() {\n await this._scriptLoader.loadScript('https://js.stripe.com/v3/');\n\n if (!this._window.Stripe) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.Stripe;\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\n/**\n * @todo Convert this file into TypeScript properly\n */\nexport default class RemoteCheckoutRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n initializeBilling(\n methodName: string,\n params?: { referenceId: string },\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/remote-checkout/${methodName}/billing`;\n\n return this._requestSender.get(url, { params, timeout, headers: SDK_VERSION_HEADERS });\n }\n\n initializeShipping(\n methodName: string,\n params?: { referenceId: string },\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/remote-checkout/${methodName}/shipping`;\n\n return this._requestSender.get(url, { params, timeout, headers: SDK_VERSION_HEADERS });\n }\n\n initializePayment(\n methodName: string,\n params?: InitializePaymentOptions,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/remote-checkout/${methodName}/payment`;\n\n return this._requestSender.get(url, { params, timeout, headers: SDK_VERSION_HEADERS });\n }\n\n loadSettings(methodName: string, { timeout }: RequestOptions = {}): Promise> {\n const url = `/remote-checkout/${methodName}/settings`;\n\n return this._requestSender.get(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n\n signOut(methodName: string, { timeout }: RequestOptions = {}): Promise> {\n const url = `/remote-checkout/${methodName}/signout`;\n\n return this._requestSender.get(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n\n generateToken({ timeout }: RequestOptions = {}): Promise> {\n const url = '/remote-checkout-token';\n\n return this._requestSender.get(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n\n trackAuthorizationEvent({ timeout }: RequestOptions = {}): Promise> {\n const url =\n '/remote-checkout/events/shopper-checkout-service-provider-authorization-requested';\n\n return this._requestSender.post(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n\n forgetCheckout({ timeout }: RequestOptions = {}): Promise> {\n const url = `/remote-checkout/forget-checkout`;\n\n return this._requestSender.post(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n}\n\nexport interface InitializePaymentOptions {\n authorizationToken?: string;\n customerMessage?: string;\n referenceId?: string;\n useStoreCredit?: boolean;\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { AmazonPayRemoteCheckout } from './methods';\n\nexport enum RemoteCheckoutActionType {\n ForgetCheckoutRemoteCustomerRequested = 'FORGET_CHECKOUT_REMOTE_CUSTOMER_REQUESTED',\n ForgetCheckoutRemoteCustomerSucceeded = 'FORGET_CHECKOUT_REMOTE_CUSTOMER_SUCCEEDED',\n ForgetCheckoutRemoteCustomerFailed = 'FORGET_CHECKOUT_REMOTE_CUSTOMER_FAILED',\n\n InitializeRemoteBillingRequested = 'INITIALIZE_REMOTE_BILLING_REQUESTED',\n InitializeRemoteBillingSucceeded = 'INITIALIZE_REMOTE_BILLING_SUCCEEDED',\n InitializeRemoteBillingFailed = 'INITIALIZE_REMOTE_BILLING_FAILED',\n\n InitializeRemoteShippingRequested = 'INITIALIZE_REMOTE_SHIPPING_REQUESTED',\n InitializeRemoteShippingSucceeded = 'INITIALIZE_REMOTE_SHIPPING_SUCCEEDED',\n InitializeRemoteShippingFailed = 'INITIALIZE_REMOTE_SHIPPING_FAILED',\n\n InitializeRemotePaymentRequested = 'INITIALIZE_REMOTE_PAYMENT_REQUESTED',\n InitializeRemotePaymentSucceeded = 'INITIALIZE_REMOTE_PAYMENT_SUCCEEDED',\n InitializeRemotePaymentFailed = 'INITIALIZE_REMOTE_PAYMENT_FAILED',\n\n LoadRemoteSettingsRequested = 'LOAD_REMOTE_SETTINGS_REQUESTED',\n LoadRemoteSettingsSucceeded = 'LOAD_REMOTE_SETTINGS_SUCCEEDED',\n LoadRemoteSettingsFailed = 'LOAD_REMOTE_SETTINGS_FAILED',\n\n SignOutRemoteCustomerRequested = 'SIGN_OUT_REMOTE_CUSTOMER_REQUESTED',\n SignOutRemoteCustomerSucceeded = 'SIGN_OUT_REMOTE_CUSTOMER_SUCCEEDED',\n SignOutRemoteCustomerFailed = 'SIGN_OUT_REMOTE_CUSTOMER_FAILED',\n\n UpdateRemoteCheckout = 'UPDATE_REMOTE_CHECKOUT',\n}\n\nexport type RemoteCheckoutAction =\n | ForgetCheckoutRemoteCustomerAction\n | InitializeRemoteBillingAction\n | InitializeRemoteShippingAction\n | InitializeRemotePaymentAction\n | SignOutRemoteCustomerAction\n | LoadRemoteSettingsAction\n | UpdateRemoteCheckoutAction;\n\nexport type ForgetCheckoutRemoteCustomerAction =\n | ForgetCheckoutRemoteCustomerRequestedAction\n | ForgetCheckoutRemoteCustomerSucceededAction\n | ForgetCheckoutRemoteCustomerFailedAction;\n\nexport interface ForgetCheckoutRemoteCustomerRequestedAction extends Action {\n type: RemoteCheckoutActionType.ForgetCheckoutRemoteCustomerRequested;\n}\n\nexport interface ForgetCheckoutRemoteCustomerSucceededAction extends Action {\n type: RemoteCheckoutActionType.ForgetCheckoutRemoteCustomerSucceeded;\n}\n\nexport interface ForgetCheckoutRemoteCustomerFailedAction extends Action {\n type: RemoteCheckoutActionType.ForgetCheckoutRemoteCustomerFailed;\n}\n\nexport type InitializeRemoteBillingAction =\n | InitializeRemoteBillingSucceededAction\n | InitializeRemoteBillingFailedAction\n | InitializeRemoteBillingRequestedAction;\n\nexport interface InitializeRemoteBillingSucceededAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemoteBillingSucceeded;\n}\n\nexport interface InitializeRemoteBillingFailedAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemoteBillingFailed;\n}\n\nexport interface InitializeRemoteBillingRequestedAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemoteBillingRequested;\n}\n\nexport type InitializeRemoteShippingAction =\n | InitializeRemoteShippingSucceededAction\n | InitializeRemoteShippingFailedAction\n | InitializeRemoteShippingRequestedAction;\n\nexport interface InitializeRemoteShippingSucceededAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemoteShippingSucceeded;\n}\n\nexport interface InitializeRemoteShippingFailedAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemoteShippingFailed;\n}\n\nexport interface InitializeRemoteShippingRequestedAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemoteShippingRequested;\n}\n\nexport type InitializeRemotePaymentAction =\n | InitializeRemotePaymentSucceededAction\n | InitializeRemotePaymentFailedAction\n | InitializeRemotePaymentRequestedAction;\n\nexport interface InitializeRemotePaymentSucceededAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemotePaymentSucceeded;\n}\n\nexport interface InitializeRemotePaymentFailedAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemotePaymentFailed;\n}\n\nexport interface InitializeRemotePaymentRequestedAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemotePaymentRequested;\n}\n\nexport type SignOutRemoteCustomerAction =\n | SignOutRemoteCustomerSucceededAction\n | SignOutRemoteCustomerFailedAction\n | SignOutRemoteCustomerRequestedAction;\n\nexport interface SignOutRemoteCustomerSucceededAction extends Action {\n type: RemoteCheckoutActionType.SignOutRemoteCustomerSucceeded;\n}\n\nexport interface SignOutRemoteCustomerFailedAction extends Action {\n type: RemoteCheckoutActionType.SignOutRemoteCustomerFailed;\n}\n\nexport interface SignOutRemoteCustomerRequestedAction extends Action {\n type: RemoteCheckoutActionType.SignOutRemoteCustomerRequested;\n}\n\nexport type LoadRemoteSettingsAction =\n | LoadRemoteSettingsSucceededAction\n | LoadRemoteSettingsRequestedAction\n | LoadRemoteSettingsFailedAction;\n\nexport interface LoadRemoteSettingsSucceededAction extends Action {\n type: RemoteCheckoutActionType.LoadRemoteSettingsSucceeded;\n}\n\nexport interface LoadRemoteSettingsRequestedAction extends Action {\n type: RemoteCheckoutActionType.LoadRemoteSettingsRequested;\n}\n\nexport interface LoadRemoteSettingsFailedAction extends Action {\n type: RemoteCheckoutActionType.LoadRemoteSettingsFailed;\n}\n\nexport interface UpdateRemoteCheckoutAction extends Action {\n type: RemoteCheckoutActionType.UpdateRemoteCheckout;\n}\n","import { Action, createAction, createErrorAction } from '@bigcommerce/data-store';\nimport { concat, defer, Observable, Observer, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { CheckoutActionCreator } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\n\nimport { RemoteCheckoutActionType } from './remote-checkout-actions';\nimport RemoteCheckoutRequestSender, {\n InitializePaymentOptions,\n} from './remote-checkout-request-sender';\nimport { RemoteCheckoutStateData } from './remote-checkout-state';\n\n/**\n * @todo Convert this file into TypeScript properly\n * i.e.: Action\n */\nexport default class RemoteCheckoutActionCreator {\n constructor(\n private _remoteCheckoutRequestSender: RemoteCheckoutRequestSender,\n private _checkoutActionCreator: CheckoutActionCreator,\n ) {}\n\n initializeBilling(\n methodId: string,\n params?: { referenceId: string },\n options?: RequestOptions,\n ): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(\n createAction(RemoteCheckoutActionType.InitializeRemoteBillingRequested, undefined, {\n methodId,\n }),\n );\n\n this._remoteCheckoutRequestSender\n .initializeBilling(methodId, params, options)\n .then(({ body = {} }) => {\n observer.next(\n createAction(\n RemoteCheckoutActionType.InitializeRemoteBillingSucceeded,\n body,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n RemoteCheckoutActionType.InitializeRemoteBillingFailed,\n response,\n { methodId },\n ),\n );\n });\n });\n }\n\n initializeShipping(\n methodId: string,\n params?: { referenceId: string },\n options?: RequestOptions,\n ): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(\n createAction(\n RemoteCheckoutActionType.InitializeRemoteShippingRequested,\n undefined,\n { methodId },\n ),\n );\n\n this._remoteCheckoutRequestSender\n .initializeShipping(methodId, params, options)\n .then(({ body = {} }) => {\n observer.next(\n createAction(\n RemoteCheckoutActionType.InitializeRemoteShippingSucceeded,\n body,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n RemoteCheckoutActionType.InitializeRemoteShippingFailed,\n response,\n { methodId },\n ),\n );\n });\n });\n }\n\n initializePayment(\n methodId: string,\n params?: InitializePaymentOptions,\n options?: RequestOptions,\n ): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(\n createAction(RemoteCheckoutActionType.InitializeRemotePaymentRequested, undefined, {\n methodId,\n }),\n );\n\n this._remoteCheckoutRequestSender\n .initializePayment(methodId, params, options)\n .then(({ body = {} }) => {\n observer.next(\n createAction(\n RemoteCheckoutActionType.InitializeRemotePaymentSucceeded,\n body,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n RemoteCheckoutActionType.InitializeRemotePaymentFailed,\n response,\n { methodId },\n ),\n );\n });\n });\n }\n\n loadSettings(methodId: string, options?: RequestOptions): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(\n createAction(RemoteCheckoutActionType.LoadRemoteSettingsRequested, undefined, {\n methodId,\n }),\n );\n\n this._remoteCheckoutRequestSender\n .loadSettings(methodId, options)\n .then(({ body }) => {\n observer.next(\n createAction(RemoteCheckoutActionType.LoadRemoteSettingsSucceeded, body, {\n methodId,\n }),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n RemoteCheckoutActionType.LoadRemoteSettingsFailed,\n response,\n { methodId },\n ),\n );\n });\n });\n }\n\n signOut(methodId: string, options?: RequestOptions): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(\n createAction(RemoteCheckoutActionType.SignOutRemoteCustomerRequested, undefined, {\n methodId,\n }),\n );\n\n this._remoteCheckoutRequestSender\n .signOut(methodId, options)\n .then(() => {\n observer.next(\n createAction(\n RemoteCheckoutActionType.SignOutRemoteCustomerSucceeded,\n undefined,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n RemoteCheckoutActionType.SignOutRemoteCustomerFailed,\n response,\n { methodId },\n ),\n );\n });\n });\n }\n\n forgetCheckout(methodId: string, options?: RequestOptions): Observable {\n return concat(\n of(\n createAction(\n RemoteCheckoutActionType.ForgetCheckoutRemoteCustomerRequested,\n undefined,\n { methodId },\n ),\n ),\n defer(async () => {\n await this._remoteCheckoutRequestSender.forgetCheckout(options);\n await this._checkoutActionCreator.loadCurrentCheckout();\n\n return createAction(\n RemoteCheckoutActionType.ForgetCheckoutRemoteCustomerSucceeded,\n undefined,\n { methodId },\n );\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(\n RemoteCheckoutActionType.ForgetCheckoutRemoteCustomerFailed,\n error,\n { methodId },\n ),\n ),\n );\n }\n\n updateCheckout(\n methodId: K,\n data: Partial,\n ): Action {\n return createAction(RemoteCheckoutActionType.UpdateRemoteCheckout, data, { methodId });\n }\n}\n","import StandardError from './standard-error';\n\n/**\n * Throw this error if we try to call a method that is only a stub and has not\n * been fully implemented.\n */\nexport default class NotImplementedError extends StandardError {\n constructor(message?: string) {\n super(message || 'Not implemented.');\n\n this.name = 'NotImplementedError';\n this.type = 'not_implemented';\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, NotImplementedError } from '../../../common/error/errors';\nimport { PaymentMethodActionCreator } from '../../../payment';\nimport {\n AmazonPayV2PaymentProcessor,\n AmazonPayV2Placement,\n} from '../../../payment/strategies/amazon-pay-v2';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport {\n CustomerInitializeOptions,\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class AmazonPayV2CustomerStrategy implements CustomerStrategy {\n constructor(\n private _store: CheckoutStore,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n private _amazonPayV2PaymentProcessor: AmazonPayV2PaymentProcessor,\n ) {}\n\n async initialize(options: CustomerInitializeOptions): Promise {\n const { methodId, amazonpay } = options;\n\n if (!methodId || !amazonpay?.container) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" or \"containerId\" argument is not provided.',\n );\n }\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n\n await this._amazonPayV2PaymentProcessor.initialize(getPaymentMethodOrThrow(methodId));\n\n this._amazonPayV2PaymentProcessor.renderAmazonPayButton({\n checkoutState: this._store.getState(),\n containerId: amazonpay.container,\n methodId,\n placement: AmazonPayV2Placement.Checkout,\n });\n\n return this._store.getState();\n }\n\n async deinitialize(): Promise {\n await this._amazonPayV2PaymentProcessor.deinitialize();\n\n return this._store.getState();\n }\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via Amazon, the shopper must click on \"Amazon Pay\" button.',\n );\n }\n\n async signOut(options?: CustomerRequestOptions): Promise {\n const state = this._store.getState();\n const payment = state.payment.getPaymentId();\n\n if (!payment) {\n return Promise.resolve(this._store.getState());\n }\n\n await this._amazonPayV2PaymentProcessor.signout();\n\n return this._store.dispatch(\n this._remoteCheckoutActionCreator.signOut(payment.providerId, options),\n );\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotImplementedError,\n} from '../../../common/error/errors';\nimport { PaymentMethod, PaymentMethodActionCreator } from '../../../payment';\nimport {\n BraintreeVisaCheckoutPaymentProcessor,\n VisaCheckoutPaymentSuccessPayload,\n VisaCheckoutScriptLoader,\n} from '../../../payment/strategies/braintree';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport {\n CustomerInitializeOptions,\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategyActionCreator from '../../customer-strategy-action-creator';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class BraintreeVisaCheckoutCustomerStrategy implements CustomerStrategy {\n private _paymentMethod?: PaymentMethod;\n private _buttonClassName = 'visa-checkout-wrapper';\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _customerStrategyActionCreator: CustomerStrategyActionCreator,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n private _braintreeVisaCheckoutPaymentProcessor: BraintreeVisaCheckoutPaymentProcessor,\n private _visaCheckoutScriptLoader: VisaCheckoutScriptLoader,\n private _formPoster: FormPoster,\n ) {}\n\n initialize(options: CustomerInitializeOptions): Promise {\n const { braintreevisacheckout: visaCheckoutOptions, methodId } = options;\n\n if (!visaCheckoutOptions || !methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"options.braintreevisacheckout\" argument is not provided.',\n );\n }\n\n return this._store\n .dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId))\n .then((state) => {\n this._paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n const checkout = state.checkout.getCheckout();\n const storeConfig = state.config.getStoreConfig();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n if (!this._paymentMethod || !this._paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { container, onError = () => {} } = visaCheckoutOptions;\n\n const initOptions = {\n locale: storeConfig.storeProfile.storeLanguage,\n collectShipping: true,\n subtotal: checkout.subtotal,\n currencyCode: storeConfig.currency.code,\n };\n\n return Promise.all([\n this._visaCheckoutScriptLoader.load(this._paymentMethod.config.testMode),\n this._braintreeVisaCheckoutPaymentProcessor.initialize(\n this._paymentMethod.clientToken,\n initOptions,\n ),\n ])\n .then(([visaCheckout, initOptions]) => {\n const signInButton = this._createSignInButton(\n container,\n this._buttonClassName,\n );\n\n visaCheckout.init(initOptions);\n visaCheckout.on(\n 'payment.success',\n (paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) =>\n this._paymentInstrumentSelected(paymentSuccessPayload).catch(\n (error) => onError(error),\n ),\n );\n visaCheckout.on('payment.error', (_, error) => onError(error));\n\n return signInButton;\n })\n .then((signInButton) => {\n signInButton.style.visibility = 'visible';\n });\n })\n .then(() => this._store.getState());\n }\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via VisaCheckout, the shopper must click on \"Visa Checkout\" button.',\n );\n }\n\n signOut(options?: CustomerRequestOptions): Promise {\n return this._store.dispatch(\n this._remoteCheckoutActionCreator.signOut('braintreevisacheckout', options),\n );\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n this._paymentMethod = undefined;\n\n return this._braintreeVisaCheckoutPaymentProcessor\n .deinitialize()\n .then(() => this._store.getState());\n }\n\n private _paymentInstrumentSelected(paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) {\n const state = this._store.getState();\n\n if (!this._paymentMethod) {\n throw new Error('Payment method not initialized');\n }\n\n const { id: methodId } = this._paymentMethod;\n\n return this._store.dispatch(\n this._customerStrategyActionCreator.widgetInteraction(\n () => {\n return this._braintreeVisaCheckoutPaymentProcessor\n .handleSuccess(\n paymentSuccessPayload,\n state.shippingAddress.getShippingAddress(),\n state.billingAddress.getBillingAddress(),\n )\n .then(async () => {\n await this._store.dispatch(\n this._checkoutActionCreator.loadCurrentCheckout(),\n );\n this._onPaymentSelectComplete();\n });\n },\n { methodId },\n ),\n { queueId: 'widgetInteraction' },\n );\n }\n\n private _onPaymentSelectComplete(): void {\n this._formPoster.postForm('/checkout.php', {\n headers: {\n Accept: 'text/html',\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n });\n }\n\n private _createSignInButton(containerId: string, buttonClass: string): HTMLElement {\n const container = document.querySelector(`#${containerId}`);\n\n if (!container) {\n throw new Error('Need a container to place the button');\n }\n\n return (\n (container.querySelector(`.${buttonClass}`) as HTMLElement) ||\n this._insertVisaCheckoutButton(container, buttonClass)\n );\n }\n\n private _insertVisaCheckoutButton(container: Element, buttonClass: string): HTMLElement {\n const buttonSource =\n 'https://secure.checkout.visa.com/wallet-services-web/xo/button.png?acceptCanadianVisaDebit=false&cobrand=true&height=34&width=178';\n const buttonTemplate = `\n \n Tell Me More`;\n\n const visaCheckoutButton = document.createElement('div');\n\n visaCheckoutButton.style.display = 'flex';\n visaCheckoutButton.style.flexDirection = 'column';\n visaCheckoutButton.style.visibility = 'hidden';\n visaCheckoutButton.className = buttonClass;\n visaCheckoutButton.innerHTML = buttonTemplate;\n\n container.appendChild(visaCheckoutButton);\n\n return visaCheckoutButton;\n }\n}\n","import { LegacyAddress } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BraintreeDetails } from '../../../payment/strategies/braintree';\n\nexport default function mapToLegacyBillingAddress(\n details: BraintreeDetails,\n): Partial {\n const { billingAddress, email, firstName, lastName, phone, shippingAddress } = details;\n\n const address = billingAddress || shippingAddress;\n\n return {\n email,\n first_name: firstName,\n last_name: lastName,\n phone_number: phone,\n address_line_1: address?.line1,\n address_line_2: address?.line2,\n city: address?.city,\n state: address?.state,\n country_code: address?.countryCode,\n postal_code: address?.postalCode,\n };\n}\n","import { LegacyAddress } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BraintreeDetails } from '../../../payment/strategies/braintree';\n\nexport default function mapToLegacyShippingAddress(\n details: BraintreeDetails,\n): Partial {\n const { email, phone, shippingAddress } = details;\n\n const recipientName = shippingAddress?.recipientName || '';\n const [firstName, lastName] = recipientName.split(' ');\n\n return {\n email,\n first_name: firstName || '',\n last_name: lastName || '',\n phone_number: phone,\n address_line_1: shippingAddress?.line1,\n address_line_2: shippingAddress?.line2,\n city: shippingAddress?.city,\n state: shippingAddress?.state,\n country_code: shippingAddress?.countryCode,\n postal_code: shippingAddress?.postalCode,\n };\n}\n","import { Address } from '../../../address';\n\nimport { BraintreeShippingAddressOverride } from './braintree';\n\nexport default function mapToBraintreeShippingAddressOverride(\n address: Address,\n): BraintreeShippingAddressOverride {\n return {\n recipientName: `${address.firstName} ${address.lastName}`,\n line1: address.address1,\n line2: address.address2,\n city: address.city,\n state: address.stateOrProvinceCode,\n postalCode: address.postalCode,\n countryCode: address.countryCode,\n phone: address.phone,\n };\n}\n","export interface PaypalSDK {\n Button: PaypalButton;\n checkout: PaypalExpressCheckout;\n FUNDING: PaypalFundingTypeList;\n Messages(options: MessagingOptions): MessagingRender;\n Buttons(options: PaypalButtonOptions): PaypalButtonRender;\n}\n\nexport interface PaypalFundingTypeList {\n CARD?: string;\n CREDIT?: string;\n PAYPAL?: string;\n PAYLATER?: string;\n}\n\nexport interface PaypalButton {\n render(options: PaypalButtonOptions, container: string): void;\n}\n\nexport interface PaypalButtonRender {\n render(container: string): void;\n isEligible(): boolean;\n}\n\nexport interface MessagingRender {\n render(container: string): void;\n}\n\nexport interface MessagingOptions {\n amount: number;\n placement: string;\n}\n\nexport interface PaypalButtonOptions {\n env?: string;\n commit?: boolean;\n style?: PaypalStyleOptions;\n funding?: PaypalFundingType;\n fundingSource?: string;\n client?: PaypalClientToken;\n payment?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onAuthorize?(data: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n createOrder?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onApprove?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n}\n\nexport interface PaypalClientToken {\n production?: string;\n sandbox?: string;\n}\n\nexport interface PaypalFundingType {\n allowed?: string[];\n disallowed?: string[];\n}\n\nexport enum PaypalButtonStyleLayoutOption {\n HORIZONTAL = 'horizontal',\n VERTICAL = 'vertical',\n}\n\nexport enum PaypalButtonStyleSizeOption {\n SMALL = 'small',\n MEDIUM = 'medium',\n LARGE = 'large',\n RESPONSIVE = 'responsive',\n}\n\nexport enum PaypalButtonStyleColorOption {\n GOLD = 'gold',\n BLUE = 'blue',\n SIlVER = 'silver',\n BLACK = 'black',\n}\n\nexport enum PaypalButtonStyleLabelOption {\n CHECKOUT = 'checkout',\n PAY = 'pay',\n BUYNOW = 'buynow',\n PAYPAL = 'paypal',\n CREDIT = 'credit',\n}\n\nexport enum PaypalButtonStyleShapeOption {\n PILL = 'pill',\n RECT = 'rect',\n}\n\nexport interface PaypalStyleOptions {\n layout?: PaypalButtonStyleLayoutOption;\n size?: PaypalButtonStyleSizeOption;\n color?: PaypalButtonStyleColorOption;\n label?: PaypalButtonStyleLabelOption;\n shape?: PaypalButtonStyleShapeOption;\n tagline?: boolean;\n fundingicons?: boolean;\n height?: number;\n}\n\nexport interface PaypalActions {\n payment: PaypalPaymentActions;\n request: PaypalRequestActions;\n}\n\nexport interface PaypalPaymentActions {\n get(id: string): Promise;\n}\n\nexport interface PaypalRequestActions {\n post(url: string, payload?: object, options?: object): Promise<{ id: string }>;\n}\n\nexport interface PaypalTransaction {\n amount?: PaypalAmount;\n payee?: PaypalPayee;\n description?: string;\n note_to_payee?: string;\n item_list?: PaypalItemList;\n}\n\nexport interface PaypalItemList {\n items?: PaypalItem[];\n shipping_address?: PaypalAddress;\n}\n\nexport interface PaypalItem {\n sku?: string;\n name?: string;\n description?: string;\n quantity: string;\n price: string;\n currency: string;\n tax?: string;\n}\n\nexport interface PaypalAmount {\n currency: string;\n total: string;\n}\n\nexport interface PaypalPayer {\n payer_info: object;\n}\n\nexport interface PaypalPayee {\n email?: string;\n merchant_id?: string;\n}\n\nexport interface PaypalAddress {\n line1: string;\n line2?: string;\n city?: string;\n country_code: string;\n postal_code?: string;\n state?: string;\n phone?: string;\n type?: string;\n}\n\nexport interface PaypalPaymentPayload {\n payment: PaypalPaymentPayload;\n payer: PaypalPayer;\n transactions?: PaypalTransaction[];\n}\n\nexport interface PaypalAuthorizeData {\n payerId: string;\n paymentId?: string;\n billingToken?: string;\n // the PayPal side of things uses uppercase ID instead of camel case Id\n payerID?: string;\n paymentID?: string;\n}\n\nexport interface PaypalExpressCheckout {\n initXO(): void;\n startFlow(url: string): void;\n closeFlow(): void;\n setup(merchantId: string, options: PaypalExpressCheckoutOptions): void;\n}\n\nexport interface PaypalExpressCheckoutOptions {\n button: string;\n environment: string;\n}\n\nexport interface PaypalHostWindow extends Window {\n paypal?: PaypalSDK;\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport mapToLegacyBillingAddress from '../../../checkout-buttons/strategies/braintree/map-to-legacy-billing-address';\nimport mapToLegacyShippingAddress from '../../../checkout-buttons/strategies/braintree/map-to-legacy-shipping-address';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../../../common/error/errors';\nimport { PaymentMethodActionCreator } from '../../../payment';\nimport {\n BraintreeError,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeSDKCreator,\n BraintreeTokenizePayload,\n mapToBraintreeShippingAddressOverride,\n} from '../../../payment/strategies/braintree';\nimport {\n PaypalAuthorizeData,\n PaypalButtonStyleColorOption,\n PaypalButtonStyleLabelOption,\n PaypalHostWindow,\n} from '../../../payment/strategies/paypal';\nimport CustomerActionCreator from '../../customer-action-creator';\nimport CustomerCredentials from '../../customer-credentials';\nimport {\n CustomerInitializeOptions,\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nimport BraintreePaypalCreditCustomerInitializeOptions from './braintree-paypal-credit-customer-options';\n\nexport default class BraintreePaypalCreditCustomerStrategy implements CustomerStrategy {\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _customerActionCreator: CustomerActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _braintreeSDKCreator: BraintreeSDKCreator,\n private _formPoster: FormPoster,\n private _window: PaypalHostWindow,\n ) {}\n\n async initialize(options: CustomerInitializeOptions): Promise {\n const { braintreepaypalcredit, methodId } = options;\n const { container, buttonHeight = 40 } = braintreepaypalcredit || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!braintreepaypalcredit) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypalcredit\" argument is not provided.`,\n );\n }\n\n if (!container) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"braintreepaypalcredit.container\" argument is not provided.`,\n );\n }\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const currencyCode = state.cart.getCartOrThrow().currency.code;\n const paypalCheckoutOptions: Partial = {\n currency: currencyCode,\n intent: paymentMethod.initializationData?.intent,\n isCreditEnabled: paymentMethod.initializationData?.isCreditEnabled,\n };\n\n const paypalCheckoutCallback = (braintreePaypalCheckout: BraintreePaypalCheckout) =>\n this._renderPayPalButton(\n braintreePaypalCheckout,\n braintreepaypalcredit,\n methodId,\n Boolean(paymentMethod.config.testMode),\n buttonHeight,\n );\n const paypalCheckoutErrorCallback = (error: BraintreeError) =>\n this._handleError(error, braintreepaypalcredit);\n\n this._braintreeSDKCreator.initialize(paymentMethod.clientToken);\n await this._braintreeSDKCreator.getPaypalCheckout(\n paypalCheckoutOptions,\n paypalCheckoutCallback,\n paypalCheckoutErrorCallback,\n );\n\n return this._store.getState();\n }\n\n deinitialize(): Promise {\n this._braintreeSDKCreator.teardown();\n\n return Promise.resolve(this._store.getState());\n }\n\n signIn(\n credentials: CustomerCredentials,\n options?: CustomerRequestOptions,\n ): Promise {\n return this._store.dispatch(\n this._customerActionCreator.signInCustomer(credentials, options),\n );\n }\n\n signOut(options?: CustomerRequestOptions): Promise {\n return this._store.dispatch(this._customerActionCreator.signOutCustomer(options));\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n\n private _renderPayPalButton(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypalcredit: BraintreePaypalCreditCustomerInitializeOptions,\n methodId: string,\n testMode: boolean,\n buttonHeight: number,\n ): void {\n const { container } = braintreepaypalcredit;\n const { paypal } = this._window;\n\n let hasRenderedSmartButton = false;\n\n if (paypal) {\n const fundingSources = [paypal.FUNDING.PAYLATER, paypal.FUNDING.CREDIT];\n const commonButtonStyle = {\n height: buttonHeight,\n color: PaypalButtonStyleColorOption.GOLD,\n };\n\n fundingSources.forEach((fundingSource) => {\n const buttonStyle =\n fundingSource === paypal.FUNDING.CREDIT\n ? { label: PaypalButtonStyleLabelOption.CREDIT, ...commonButtonStyle }\n : commonButtonStyle;\n\n if (!hasRenderedSmartButton) {\n const paypalButtonRender = paypal.Buttons({\n env: testMode ? 'sandbox' : 'production',\n commit: false,\n fundingSource,\n style: buttonStyle,\n createOrder: () =>\n this._setupPayment(\n braintreePaypalCheckout,\n braintreepaypalcredit,\n methodId,\n ),\n onApprove: (authorizeData: PaypalAuthorizeData) =>\n this._tokenizePayment(\n authorizeData,\n braintreePaypalCheckout,\n braintreepaypalcredit,\n methodId,\n ),\n });\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${container}`);\n hasRenderedSmartButton = true;\n }\n }\n });\n }\n\n if (!paypal || !hasRenderedSmartButton) {\n this._removeElement(container);\n }\n }\n\n private async _setupPayment(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypalcredit: BraintreePaypalCreditCustomerInitializeOptions,\n methodId: string,\n ): Promise {\n try {\n const state = await this._store.dispatch(\n this._checkoutActionCreator.loadDefaultCheckout(),\n );\n\n const customer = state.customer.getCustomer();\n const amount = state.checkout.getCheckoutOrThrow().outstandingBalance;\n const currencyCode = state.cart.getCartOrThrow().currency.code;\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n const address = customer?.addresses[0];\n const shippingAddressOverride = address\n ? mapToBraintreeShippingAddressOverride(address)\n : undefined;\n\n return await braintreePaypalCheckout.createPayment({\n flow: 'checkout',\n enableShippingAddress: true,\n shippingAddressEditable: false,\n shippingAddressOverride,\n amount,\n currency: currencyCode,\n offerCredit: true,\n intent: paymentMethod.initializationData?.intent,\n });\n } catch (error) {\n this._handleError(error, braintreepaypalcredit);\n }\n }\n\n private async _tokenizePayment(\n authorizeData: PaypalAuthorizeData,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypalcredit: BraintreePaypalCreditCustomerInitializeOptions,\n methodId: string,\n ): Promise {\n try {\n const { deviceData } = await this._braintreeSDKCreator.getDataCollector({\n paypal: true,\n });\n const tokenizePayload = await braintreePaypalCheckout.tokenizePayment(authorizeData);\n const { details, nonce } = tokenizePayload;\n\n this._formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n provider: methodId,\n action: 'set_external_checkout',\n nonce,\n device_data: deviceData,\n billing_address: JSON.stringify(mapToLegacyBillingAddress(details)),\n shipping_address: JSON.stringify(mapToLegacyShippingAddress(details)),\n });\n\n return tokenizePayload;\n } catch (error) {\n this._handleError(error, braintreepaypalcredit);\n }\n }\n\n private _handleError(\n error: BraintreeError,\n braintreepaypalcredit: BraintreePaypalCreditCustomerInitializeOptions,\n ): void {\n const { container, onError } = braintreepaypalcredit;\n\n this._removeElement(container);\n\n if (onError) {\n onError(error);\n } else {\n throw error;\n }\n }\n\n private _removeElement(elementId?: string): void {\n const element = elementId && document.getElementById(elementId);\n\n if (element) {\n element.remove();\n }\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotImplementedError,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { SDK_VERSION_HEADERS } from '../../../common/http-request';\nimport { PaymentMethod, PaymentMethodActionCreator } from '../../../payment';\nimport { ChasePayScriptLoader, ChasePaySuccessPayload } from '../../../payment/strategies/chasepay';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport {\n CustomerInitializeOptions,\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class ChasePayCustomerStrategy implements CustomerStrategy {\n private _paymentMethod?: PaymentMethod;\n\n constructor(\n private _store: CheckoutStore,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n private _chasePayScriptLoader: ChasePayScriptLoader,\n private _requestSender: RequestSender,\n private _formPoster: FormPoster,\n ) {}\n\n initialize(options: CustomerInitializeOptions): Promise {\n const { chasepay: chasePayOptions, methodId } = options;\n\n if (!chasePayOptions || !methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"options.chasepay\" argument is not provided.',\n );\n }\n\n return this._store\n .dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId))\n .then((state) => {\n this._paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n const cart = state.cart.getCart();\n const storeConfig = state.config.getStoreConfig();\n\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n if (\n !this._paymentMethod ||\n !this._paymentMethod.initializationData.digitalSessionId\n ) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { container } = chasePayOptions;\n\n return this._chasePayScriptLoader\n .load(this._paymentMethod.config.testMode)\n .then((JPMC) => {\n const ChasePay = JPMC.ChasePay;\n\n ChasePay.configure({\n language: storeConfig.storeProfile.storeLanguage,\n });\n\n if (ChasePay.isChasePayUp) {\n ChasePay.insertButtons({\n containers: [container],\n });\n }\n\n ChasePay.on(ChasePay.EventType.START_CHECKOUT, () => {\n this._store\n .dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n )\n .then(() => {\n const state = this._store.getState();\n const method = state.paymentMethods.getPaymentMethod(methodId);\n const sessionId =\n method &&\n method.initializationData &&\n method.initializationData.digitalSessionId;\n\n if (sessionId) {\n ChasePay.startCheckout(sessionId);\n }\n });\n });\n\n ChasePay.on(\n ChasePay.EventType.COMPLETE_CHECKOUT,\n (payload: ChasePaySuccessPayload) => {\n const state = this._store.getState();\n const method = state.paymentMethods.getPaymentMethod(methodId);\n const requestId =\n method &&\n method.initializationData &&\n method.initializationData.merchantRequestId;\n\n if (requestId) {\n this._setExternalCheckoutData(payload, requestId).then(() => {\n this._reloadPage();\n });\n }\n },\n );\n });\n })\n .then(() => this._store.getState());\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via Chase Pay®, the shopper must click on \"Chase Pay®\" button.',\n );\n }\n\n signOut(options?: CustomerRequestOptions): Promise {\n const state = this._store.getState();\n const payment = state.payment.getPaymentId();\n\n if (!payment) {\n return Promise.resolve(this._store.getState());\n }\n\n return this._store.dispatch(\n this._remoteCheckoutActionCreator.signOut(payment.providerId, options),\n );\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n\n private _setExternalCheckoutData(\n payload: ChasePaySuccessPayload,\n requestId: string,\n ): Promise> {\n const url = `checkout.php?provider=chasepay&action=set_external_checkout`;\n const options = {\n headers: {\n Accept: 'text/html',\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n ...SDK_VERSION_HEADERS,\n },\n body: {\n sessionToken: payload.sessionToken,\n merchantRequestId: requestId,\n },\n method: 'post',\n };\n\n return this._requestSender.sendRequest(url, options);\n }\n\n private _reloadPage() {\n this._formPoster.postForm('/checkout.php', {\n headers: {\n Accept: 'text/html',\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...SDK_VERSION_HEADERS,\n },\n params: {\n fromChasePay: true,\n },\n });\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport CustomerActionCreator from '../../customer-action-creator';\nimport CustomerCredentials from '../../customer-credentials';\nimport {\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class DefaultCustomerStrategy implements CustomerStrategy {\n constructor(\n private _store: CheckoutStore,\n private _customerActionCreator: CustomerActionCreator,\n ) {}\n\n signIn(\n credentials: CustomerCredentials,\n options?: CustomerRequestOptions,\n ): Promise {\n return this._store.dispatch(\n this._customerActionCreator.signInCustomer(credentials, options),\n );\n }\n\n signOut(options?: CustomerRequestOptions): Promise {\n return this._store.dispatch(this._customerActionCreator.signOutCustomer(options));\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n\n initialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n}\n","enum GooglePayCustomerMethodType {\n GOOGLEPAY_ADYENV2 = 'googlepayadyenv2',\n GOOGLEPAY_ADYENV3 = 'googlepayadyenv3',\n GOOGLEPAY_AUTHORIZENET = 'googlepayauthorizenet',\n GOOGLEPAY_BNZ = 'googlepaybnz',\n GOOGLEPAY_BRAINTREE = 'googlepaybraintree',\n GOOGLEPAY_CHECKOUTCOM = 'googlepaycheckoutcom',\n GOOGLEPAY_CYBERSOURCEV2 = 'googlepaycybersourcev2',\n GOOGLEPAY_ORBITAL = 'googlepayorbital',\n GOOGLEPAY_STRIPE = 'googlepaystripe',\n GOOGLEPAY_STRIPEUPE = 'googlepaystripeupe',\n GOOGLEPAY_WORLDPAYACCESS = 'googlepayworldpayaccess',\n}\n\nexport default GooglePayCustomerMethodType;\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotImplementedError,\n} from '../../../common/error/errors';\nimport { SDK_VERSION_HEADERS } from '../../../common/http-request';\nimport { bindDecorator as bind } from '../../../common/utility';\nimport { GooglePayPaymentProcessor } from '../../../payment/strategies/googlepay';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport { getShippableItemsCount } from '../../../shipping';\nimport {\n CustomerInitializeOptions,\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nimport GooglePayCustomerInitializeOptions from './googlepay-customer-initialize-options';\nimport { default as MethodType } from './googlepay-customer-method-type';\n\nexport default class GooglePayCustomerStrategy implements CustomerStrategy {\n private _walletButton?: HTMLElement;\n\n constructor(\n private _store: CheckoutStore,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n private _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n private _formPoster: FormPoster,\n ) {}\n\n initialize(options: CustomerInitializeOptions): Promise {\n const { methodId } = options;\n\n const googlePayOptions = this._getGooglePayOptions(options);\n\n if (!methodId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n return this._googlePayPaymentProcessor\n .initialize(methodId)\n .then(() => {\n this._walletButton = this._createSignInButton(\n googlePayOptions.container,\n googlePayOptions,\n );\n })\n .then(() => this._store.getState());\n }\n\n deinitialize(): Promise {\n if (this._walletButton && this._walletButton.parentNode) {\n this._walletButton.parentNode.removeChild(this._walletButton);\n this._walletButton = undefined;\n }\n\n return this._googlePayPaymentProcessor.deinitialize().then(() => this._store.getState());\n }\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via Google Pay, the shopper must click on \"Google Pay\" button.',\n );\n }\n\n signOut(options?: CustomerRequestOptions): Promise {\n const state = this._store.getState();\n const payment = state.payment.getPaymentId();\n\n if (!payment) {\n return Promise.resolve(this._store.getState());\n }\n\n return this._store.dispatch(\n this._remoteCheckoutActionCreator.forgetCheckout(payment.providerId, options),\n );\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n\n private _createSignInButton(\n containerId: string,\n buttonOptions: GooglePayCustomerInitializeOptions,\n ): HTMLElement {\n const container = document.querySelector(`#${containerId}`);\n const { buttonType, buttonColor } = buttonOptions;\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to create sign-in button without valid container ID.',\n );\n }\n\n const button = this._googlePayPaymentProcessor.createButton(\n this._handleWalletButtonClick,\n buttonType,\n buttonColor,\n );\n\n container.appendChild(button);\n\n return button;\n }\n\n private _getGooglePayOptions(\n options: CustomerInitializeOptions,\n ): GooglePayCustomerInitializeOptions {\n if (options.methodId === MethodType.GOOGLEPAY_ADYENV2 && options.googlepayadyenv2) {\n return options.googlepayadyenv2;\n }\n\n if (options.methodId === MethodType.GOOGLEPAY_ADYENV3 && options.googlepayadyenv3) {\n return options.googlepayadyenv3;\n }\n\n if (\n options.methodId === MethodType.GOOGLEPAY_AUTHORIZENET &&\n options.googlepayauthorizenet\n ) {\n return options.googlepayauthorizenet;\n }\n\n if (options.methodId === MethodType.GOOGLEPAY_BNZ && options.googlepaybnz) {\n return options.googlepaybnz;\n }\n\n if (options.methodId === MethodType.GOOGLEPAY_BRAINTREE && options.googlepaybraintree) {\n return options.googlepaybraintree;\n }\n\n if (options.methodId === MethodType.GOOGLEPAY_CHECKOUTCOM && options.googlepaycheckoutcom) {\n return options.googlepaycheckoutcom;\n }\n\n if (\n options.methodId === MethodType.GOOGLEPAY_CYBERSOURCEV2 &&\n options.googlepaycybersourcev2\n ) {\n return options.googlepaycybersourcev2;\n }\n\n if (options.methodId === MethodType.GOOGLEPAY_ORBITAL && options.googlepayorbital) {\n return options.googlepayorbital;\n }\n\n if (options.methodId === MethodType.GOOGLEPAY_STRIPE && options.googlepaystripe) {\n return options.googlepaystripe;\n }\n\n if (options.methodId === MethodType.GOOGLEPAY_STRIPEUPE && options.googlepaystripeupe) {\n return options.googlepaystripeupe;\n }\n if (\n options.methodId === MethodType.GOOGLEPAY_WORLDPAYACCESS &&\n options.googlepayworldpayaccess\n ) {\n return options.googlepayworldpayaccess;\n }\n\n throw new InvalidArgumentError();\n }\n\n @bind\n private async _handleWalletButtonClick(event: Event): Promise {\n event.preventDefault();\n\n const cart = this._store.getState().cart.getCartOrThrow();\n const hasPhysicalItems = getShippableItemsCount(cart) > 0;\n\n const payloadToUpdate = {\n transactionInfo: {\n currencyCode: cart.currency.code,\n totalPrice: String(cart.cartAmount),\n },\n };\n\n this._googlePayPaymentProcessor.updatePaymentDataRequest(payloadToUpdate);\n\n try {\n const paymentData = await this._googlePayPaymentProcessor.displayWallet();\n\n await this._googlePayPaymentProcessor.handleSuccess(paymentData);\n\n if (hasPhysicalItems && paymentData.shippingAddress) {\n await this._googlePayPaymentProcessor.updateShippingAddress(\n paymentData.shippingAddress,\n );\n }\n\n await this._onPaymentSelectComplete();\n } catch (error) {\n if (error && error.message !== 'CANCELED') {\n throw error;\n }\n }\n }\n\n private _onPaymentSelectComplete(): void {\n const checkoutUrl = this._store.getState().config.getStoreConfigOrThrow().links.siteLink;\n\n this._formPoster.postForm(\n window.location.pathname === '/embedded-checkout'\n ? `${checkoutUrl}/checkout`\n : '/checkout.php',\n {\n headers: {\n Accept: 'text/html',\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...SDK_VERSION_HEADERS,\n },\n },\n );\n }\n}\n","export default function getCallbackUrl(origin: string): string {\n return `${window.location.origin}/checkout.php?action=set_external_checkout&provider=masterpass&gateway=stripe&origin=${origin}`;\n}\n","export const supportedLocales: { [language: string]: string[] } = {\n es: ['es_es', 'es_mx', 'es_pe', 'es_co', 'es_ar', 'es_cl'],\n en: [\n 'en_us',\n 'en_gb',\n 'en_ca',\n 'en_es',\n 'en_fr',\n 'en_ie',\n 'en_sg',\n 'en_au',\n 'en_nz',\n 'en_my',\n 'en_hk',\n 'en_th',\n 'en_ae',\n 'en_sa',\n 'en_qa',\n 'en_kw',\n 'en_za',\n ],\n pt: ['pt_br'],\n zu: ['zu_za'],\n ar: ['ar_sa', 'ar_ae', 'ar_qa', 'ar_kw'],\n zh: ['zh_sg', 'zh_hk'],\n ms: ['ms_my'],\n uk: ['uk_ua'],\n sv: ['sv_se'],\n hr: ['hr_hr'],\n pl: ['pl_pl'],\n nl: ['nl_be'],\n it: ['it_it'],\n de: ['de_de'],\n fr: ['fr_fr', 'fr_ca'],\n};\n","import { supportedLocales } from './masterpass-supported-locales';\n\nexport default function formatLocale(localeLanguage: string): string {\n const [language, country] = localeLanguage.replace('-', '_').toLowerCase().split('_');\n const formattedLocale = `${language}_${country}`;\n const countryLocales = supportedLocales[language];\n\n if (!countryLocales) {\n return 'en_us';\n }\n\n return countryLocales.indexOf(formattedLocale) > -1 ? formattedLocale : countryLocales[0];\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotImplementedError,\n} from '../../../common/error/errors';\nimport { PaymentMethod, PaymentMethodActionCreator } from '../../../payment';\nimport {\n formatLocale,\n getCallbackUrl,\n MasterpassScriptLoader,\n} from '../../../payment/strategies/masterpass';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport {\n CustomerInitializeOptions,\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class MasterpassCustomerStrategy implements CustomerStrategy {\n private _signInButton?: HTMLElement;\n private _paymentMethod?: PaymentMethod;\n\n constructor(\n private _store: CheckoutStore,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n private _masterpassScriptLoader: MasterpassScriptLoader,\n private _locale: string,\n ) {}\n\n initialize(options: CustomerInitializeOptions): Promise {\n const { masterpass: masterpassOptions, methodId } = options;\n\n if (!masterpassOptions || !methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"options.masterpass\" argument is not provided.',\n );\n }\n\n return this._store\n .dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId))\n .then((state) => {\n this._paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n if (!this._paymentMethod || !this._paymentMethod.initializationData.checkoutId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const cart = state.cart.getCart();\n\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n const { container } = masterpassOptions;\n\n const payload = {\n checkoutId: this._paymentMethod.initializationData.checkoutId,\n allowedCardTypes: this._paymentMethod.initializationData.allowedCardTypes,\n amount: cart.cartAmount.toString(),\n currency: cart.currency.code,\n cartId: cart.id,\n suppressShippingAddress: false,\n callbackUrl: getCallbackUrl('checkout'),\n };\n\n const masterpassScriptLoaderParams = {\n useMasterpassSrc: this._paymentMethod.initializationData.isMasterpassSrcEnabled,\n language: formatLocale(this._locale),\n testMode: this._paymentMethod.config.testMode,\n checkoutId: this._paymentMethod.initializationData.checkoutId,\n };\n\n return this._masterpassScriptLoader\n .load(masterpassScriptLoaderParams)\n .then((Masterpass) => {\n this._signInButton = this._createSignInButton(container);\n\n this._signInButton.addEventListener('click', () => {\n Masterpass.checkout(payload);\n });\n });\n })\n .then(() => this._store.getState());\n }\n\n deinitialize(): Promise {\n this._paymentMethod = undefined;\n\n if (this._signInButton && this._signInButton.parentNode) {\n this._signInButton.parentNode.removeChild(this._signInButton);\n this._signInButton = undefined;\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via Masterpass, the shopper must click on \"Masterpass\" button.',\n );\n }\n\n signOut(options?: CustomerRequestOptions): Promise {\n const state = this._store.getState();\n const payment = state.payment.getPaymentId();\n\n if (!payment) {\n return Promise.resolve(this._store.getState());\n }\n\n return this._store.dispatch(\n this._remoteCheckoutActionCreator.signOut(payment.providerId, options),\n );\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n\n private _createSignInButton(containerId: string): HTMLElement {\n const container = document.querySelector(`#${containerId}`);\n\n if (!this._paymentMethod || !this._paymentMethod.initializationData.checkoutId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to create sign-in button without valid container ID.',\n );\n }\n\n const button = document.createElement('input');\n\n button.type = 'image';\n\n if (this._paymentMethod.initializationData.isMasterpassSrcEnabled) {\n const subdomain = this._paymentMethod.config.testMode ? 'sandbox.' : '';\n const { checkoutId } = this._paymentMethod.initializationData;\n\n const params = [\n `locale=${formatLocale(this._locale)}`,\n `paymentmethod=master,visa,amex,discover`,\n `checkoutid=${checkoutId}`,\n ];\n\n button.src = [\n `https://${subdomain}src.mastercard.com/assets/img/btn/src_chk_btn_126x030px.svg`,\n params.join('&'),\n ].join('?');\n } else {\n button.src =\n 'https://static.masterpass.com/dyn/img/btn/global/mp_chk_btn_160x037px.svg';\n }\n\n container.appendChild(button);\n\n return button;\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { NotImplementedError } from '../../../common/error/errors';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport {\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class SquareCustomerStrategy implements CustomerStrategy {\n constructor(\n private _store: CheckoutStore,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n ) {}\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via Masterpass, the shopper must click on \"Masterpass\" button.',\n );\n }\n\n signOut(options?: CustomerRequestOptions): Promise {\n const state = this._store.getState();\n const payment = state.payment.getPaymentId();\n\n if (!payment) {\n return Promise.resolve(this._store.getState());\n }\n\n return this._store.dispatch(\n this._remoteCheckoutActionCreator.signOut(payment.providerId, options),\n );\n }\n\n initialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n}\n","import { CustomFont, PaymentIntent, StripeConfigurationOptions } from '../stripev3';\n\nexport { StripeAdditionalAction } from '../stripev3';\n\nexport interface StripeError {\n /**\n * type of error. When the error type is card_error or validation_error, you can display the error message in error.message directly to your user.\n */\n type: string;\n /**\n * A human-readable message providing more details about the error. For card errors, these messages can be shown to your users.\n */\n message?: string;\n\n /**\n * The PaymentIntent object.\n */\n payment_intent: PaymentIntent;\n}\n\nexport interface StripeElement {\n /**\n * The `element.mount` method attaches your element to the DOM.\n */\n mount(domElement: string | HTMLElement): void;\n\n /**\n * Removes the element from the DOM and destroys it.\n * A destroyed element can not be re-activated or re-mounted to the DOM.\n */\n destroy(): void;\n\n /**\n * Unmounts the element from the DOM.\n * Call `element.mount` to re-attach it to the DOM.\n */\n unmount(): void;\n\n /**\n * The change event is triggered when the Element's value changes. The event payload always contains certain keys,\n * in addition to some Element-specific keys.\n * https://stripe.com/docs/js/element/events/on_change?type=paymentElement\n */\n on(event: 'change' | 'ready', handler: (event: StripeEventType) => void): void;\n}\n\nexport interface StripeEvent {\n complete: boolean;\n elementType: string;\n empty: boolean;\n}\n\nexport interface StripeCustomerEvent extends StripeEvent {\n collapsed?: boolean;\n authenticated: boolean;\n value: {\n email: string;\n };\n}\n\nexport interface StripeShippingEvent extends StripeEvent {\n mode?: string;\n isNewAddress?: boolean;\n phoneFieldRequired: boolean;\n value: {\n address: {\n city: string;\n country: string;\n line1: string;\n line2?: string;\n postal_code: string;\n state: string;\n };\n name?: string;\n firstName?: string;\n lastName?: string;\n phone?: string;\n };\n fields?: {\n phone: string;\n };\n display?: {\n name: string;\n };\n}\n\nexport type StripeEventType = StripeShippingEvent | StripeCustomerEvent;\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n * https://stripe.com/docs/api/payment_intents/confirm#confirm_payment_intent-shipping\n */\nexport interface AddressOptions {\n city?: string;\n country?: string;\n state?: string;\n postal_code?: string;\n line1?: string;\n line2?: string;\n}\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n * https://stripe.com/docs/js/elements_object/create_payment_element\n */\nexport interface AddressProperties {\n city?: AutoOrNever;\n country?: AutoOrNever;\n state?: AutoOrNever;\n postalCode?: AutoOrNever;\n line1?: AutoOrNever;\n line2?: AutoOrNever;\n}\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n */\nexport interface BillingDetailsOptions {\n name?: string;\n email?: string;\n address?: AddressOptions;\n phone?: string;\n}\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n */\nexport interface BillingDetailsProperties {\n name?: AutoOrNever;\n email?: AutoOrNever;\n address?: AutoOrNever | AddressProperties;\n phone?: AutoOrNever;\n}\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n */\nexport interface PaymentMethodDataOptions {\n billing_details: BillingDetailsOptions;\n}\n\n/**\n * Parameters that will be passed on to the Stripe API to confirm the PaymentIntent.\n */\nexport interface StripeUPEConfirmParams {\n /**\n * If you are [handling next actions yourself](https://stripe.com/docs/payments/payment-intents/verifying-status#next-actions), pass in a return_url. If the subsequent action\n * is redirect_to_url, this URL will be used on the return path for the redirect.\n *\n * @recommended\n */\n return_url?: string;\n payment_method_data?: PaymentMethodDataOptions;\n}\n\n/**\n * Data to be sent with a `stripe.confirmPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/js/payment_intents/confirm_payment) for a full list of parameters.\n */\nexport interface StripeConfirmPaymentData {\n /**\n * The Elements instance that was used to create the Payment Element.\n */\n elements: StripeElements;\n\n /**\n * Parameters that will be passed on to the Stripe API to confirm the PaymentIntent.\n */\n confirmParams?: StripeUPEConfirmParams;\n\n /**\n * By default, confirmPayment will always redirect to your return_url after a successful confirmation.\n * If you set redirect: \"if_required\", then confirmPayment will only redirect if your user chooses a redirect-based payment method.\n */\n redirect?: StripeStringConstants.ALWAYS | StripeStringConstants.IF_REQUIRED;\n}\n\nexport interface FieldsOptions {\n billingDetails?: AutoOrNever | BillingDetailsProperties;\n phone?: string;\n}\n\nexport interface WalletOptions {\n applePay?: AutoOrNever;\n googlePay?: AutoOrNever;\n}\n\n/**\n * All available options are here https://stripe.com/docs/js/elements_object/create_payment_element\n */\nexport interface StripeElementsCreateOptions {\n mode?: string;\n fields?: FieldsOptions;\n wallets?: WalletOptions;\n allowedCountries?: string[];\n defaultValues?: ShippingDefaultValues | CustomerDefaultValues;\n validation?: validationElement;\n display?: { name: DisplayName };\n}\n\ninterface validationElement {\n phone?: validationRequiredElement;\n}\n\ninterface validationRequiredElement {\n required?: string;\n}\n\ninterface ShippingDefaultValues {\n name?: string;\n firstName?: string;\n lastName?: string;\n phone: string;\n address: {\n line1: string;\n line2: string;\n city: string;\n state: string;\n postal_code: string;\n country: string;\n };\n}\n\n/*\nDecide which mode you are going to use the Address Element\nShipping: is used with the Payment Element and Link Authentication Element, it will automatically pass shipping\ninformation when confirming Payment Intent or Setup Intent.\nBilling: is used with the Payment Element, it will automatically pass the billing information when confirming\nPayment Intent or Setup Intent.\n */\nexport enum StripeFormMode {\n SHIPPING = 'shipping',\n BILLING = 'billing',\n}\n\nexport enum DisplayName {\n SPLIT = 'split',\n FULL = 'full',\n ORGANIZATION = 'organization',\n}\n\ninterface CustomerDefaultValues {\n mode: StripeFormMode;\n email: string;\n allowedCountries?: string[];\n display?: {\n name: DisplayName;\n };\n}\n\nexport interface StripeElements {\n /**\n * Creates an Elements instance, which manages a group of elements.\n * https://stripe.com/docs/js/elements_object/create\n */\n create(elementType: StripeElementType, options?: StripeElementsCreateOptions): StripeElement;\n\n /**\n * Looks up a previously created element.\n * https://stripe.com/docs/js/elements_object/get_payment_element or\n * https://stripe.com/docs/js/elements_object/get_link_authentication_element\n */\n getElement(elementType: StripeElementType): StripeElement | null;\n\n /**\n * Updates options on an existing instance of Elements.\n * https://stripe.com/docs/js/elements_object/update\n */\n update(options?: StripeUpdateElementsOptions): StripeElement;\n\n /**\n * Fetches updates from the associated PaymentIntent or SetupIntent on an existing instance of Elements,\n * and reflects these updates in the Payment Element.\n * https://stripe.com/docs/js/elements_object/fetch_updates\n */\n fetchUpdates(): void;\n}\n\n/**\n * All available options are here https://stripe.com/docs/stripe-js/appearance-api#supported-css-properties\n */\nexport interface StripeUPEAppearanceOptions {\n variables?: {\n colorPrimary?: string;\n colorBackground?: string;\n colorText?: string;\n colorDanger?: string;\n colorTextSecondary?: string;\n colorTextPlaceholder?: string;\n colorIcon?: string;\n colorIconCardError?: string;\n colorIconRedirect?: string;\n spacingUnit?: string;\n borderRadius?: string;\n };\n\n rules?: {\n '.Input'?: {\n borderColor?: string;\n color?: string;\n boxShadow?: string;\n };\n };\n}\n\nexport interface StripeElementsOptions {\n /**\n * An array of custom fonts, which elements created from the Elements object can use.\n * Fonts can be specified as [CssFontSource](https://stripe.com/docs/js/appendix/css_font_source_object)\n * or [CustomFontSource](https://stripe.com/docs/js/appendix/custom_font_source_object) objects.\n */\n fonts?: CustomFont[];\n\n /**\n * A [locale](https://stripe.com/docs/js/appendix/supported_locales) to display placeholders and\n * error strings in. Default is auto (Stripe detects the locale of the browser).\n * Setting the locale does not affect the behavior of postal code validation—a valid postal code\n * for the billing country of the card is still required.\n */\n locale?: string;\n\n /**\n * The client secret of this PaymentIntent. Used for client-side retrieval using a publishable key.\n * The client secret can be used to complete a payment from your frontend.\n * It should not be stored, logged, embedded in URLs, or exposed to anyone other than the customer.\n * Make sure that you have TLS enabled on any page that includes the client secret.\n * Refer to our docs to accept a payment and learn about how client_secret should be handled.\n */\n clientSecret: string;\n\n /**\n * Match the design of your site with the appearance option.\n * The layout of each Element stays consistent, but you can modify colors, fonts, borders, padding, and more.\n */\n appearance?: StripeUPEAppearanceOptions;\n}\n\nexport interface StripeUpdateElementsOptions {\n /**\n * A [locale](https://stripe.com/docs/js/appendix/supported_locales) to display placeholders and\n * error strings in. Default is auto (Stripe detects the locale of the browser).\n * Setting the locale does not affect the behavior of postal code validation—a valid postal code\n * for the billing country of the card is still required.\n */\n locale?: string;\n\n /**\n * Match the design of your site with the appearance option.\n * The layout of each Element stays consistent, but you can modify colors, fonts, borders, padding, and more.\n */\n appearance?: StripeUPEAppearanceOptions;\n}\n\nexport interface StripeUPEClient {\n /**\n * Use confirmPayment to confirm a PaymentIntent using data collected by the Payment Element.\n * When called, confirmPayment will attempt to complete any required actions,\n * such as authenticating your user by displaying a 3DS dialog or redirecting them to a bank authorization page.\n */\n confirmPayment(options: StripeConfirmPaymentData): Promise;\n\n /**\n * When called, it will confirm the PaymentIntent with data you provide and carry out 3DS or other next actions if they are required.\n */\n confirmCardPayment(clientSecret: string): Promise;\n\n /**\n * Retrieve a PaymentIntent using its client secret.\n */\n retrievePaymentIntent(clientSecret: string): Promise;\n\n /**\n * Create an `Elements` instance, which manages a group of elements.\n */\n elements(options: StripeElementsOptions): StripeElements;\n}\n\ninterface StripeUpeResult {\n paymentIntent?: PaymentIntent;\n error?: StripeError;\n}\n\nexport interface StripeHostWindow extends Window {\n bcStripeClient?: StripeUPEClient;\n bcStripeElements?: StripeElements;\n Stripe?(stripePublishableKey: string, options?: StripeConfigurationOptions): StripeUPEClient;\n}\n\nexport enum StripePaymentMethodType {\n CreditCard = 'card',\n SOFORT = 'sofort',\n EPS = 'eps',\n GRABPAY = 'grabpay',\n BANCONTACT = 'bancontact',\n IDEAL = 'ideal',\n GIROPAY = 'giropay',\n ALIPAY = 'alipay',\n KLARNA = 'klarna',\n}\n\ntype AutoOrNever = StripeStringConstants.AUTO | StripeStringConstants.NEVER;\n\nexport enum StripeStringConstants {\n NEVER = 'never',\n AUTO = 'auto',\n ALWAYS = 'always',\n PAYMENT = 'payment',\n IF_REQUIRED = 'if_required',\n}\n\nexport enum StripeElementType {\n PAYMENT = 'payment',\n AUTHENTICATION = 'linkAuthentication',\n SHIPPING = 'address',\n}\n","import { createAction } from '@bigcommerce/data-store';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../../../common/error/errors';\nimport { PaymentMethodActionCreator } from '../../../payment';\nimport {\n StripeElements,\n StripeElementType,\n StripeEventType,\n StripeFormMode,\n StripeScriptLoader,\n StripeUPEAppearanceOptions,\n StripeUPEClient,\n} from '../../../payment/strategies/stripe-upe';\nimport { ConsignmentActionCreator } from '../../../shipping';\nimport CustomerActionCreator from '../../customer-action-creator';\nimport { CustomerActionType } from '../../customer-actions';\nimport CustomerCredentials from '../../customer-credentials';\nimport {\n CustomerInitializeOptions,\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class StripeUPECustomerStrategy implements CustomerStrategy {\n private _stripeElements?: StripeElements;\n\n constructor(\n private _store: CheckoutStore,\n private _stripeUPEScriptLoader: StripeScriptLoader,\n private _customerActionCreator: CustomerActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _consignmentActionCreator: ConsignmentActionCreator,\n ) {}\n\n async initialize(options: CustomerInitializeOptions): Promise {\n let stripeUPEClient: StripeUPEClient;\n\n if (!options.stripeupe) {\n throw new InvalidArgumentError(\n `Unable to proceed because \"options\" argument is not provided.`,\n );\n }\n\n const { container, gatewayId, methodId, onEmailChange, getStyles, isLoading } =\n options.stripeupe;\n\n Object.entries(options.stripeupe).forEach(([key, value]) => {\n if (!value) {\n throw new InvalidArgumentError(\n `Unable to proceed because \"${key}\" argument is not provided.`,\n );\n }\n });\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n customer: { getCustomerOrThrow },\n } = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n }),\n );\n const {\n clientToken,\n initializationData: { stripePublishableKey, stripeConnectedAccount } = {},\n } = getPaymentMethodOrThrow(methodId, gatewayId);\n const { email, isStripeLinkAuthenticated } = getCustomerOrThrow();\n\n if (!email) {\n if (!stripePublishableKey || !clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n let appearance: StripeUPEAppearanceOptions | undefined;\n const styles = typeof getStyles === 'function' && getStyles();\n\n if (styles) {\n appearance = {\n variables: {\n colorPrimary: styles.fieldInnerShadow,\n colorBackground: styles.fieldBackground,\n colorText: styles.labelText,\n colorDanger: styles.fieldErrorText,\n colorTextSecondary: styles.labelText,\n colorTextPlaceholder: styles.fieldPlaceholderText,\n },\n rules: {\n '.Input': {\n borderColor: styles.fieldBorder,\n color: styles.fieldText,\n boxShadow: styles.fieldInnerShadow,\n },\n },\n };\n } else {\n appearance = {};\n }\n\n stripeUPEClient = await this._stripeUPEScriptLoader.getStripeClient(\n stripePublishableKey,\n stripeConnectedAccount,\n );\n\n this._stripeElements = this._stripeUPEScriptLoader.getElements(stripeUPEClient, {\n clientSecret: clientToken,\n appearance,\n });\n\n const {\n billingAddress: { getBillingAddress },\n consignments: { getConsignments },\n } = this._store.getState();\n const consignments = getConsignments();\n const id = consignments?.[0]?.id;\n const { email: billingEmail } = getBillingAddress() || {};\n const options = billingEmail\n ? { defaultValues: { mode: StripeFormMode.SHIPPING, email: billingEmail } }\n : {};\n const linkAuthenticationElement =\n this._stripeElements.getElement(StripeElementType.AUTHENTICATION) ||\n this._stripeElements.create(StripeElementType.AUTHENTICATION, options);\n\n linkAuthenticationElement.on('change', (event: StripeEventType) => {\n if (!('authenticated' in event)) {\n throw new MissingDataError(MissingDataErrorType.MissingCustomer);\n }\n\n this._store.dispatch(\n createAction(CustomerActionType.StripeLinkAuthenticated, event.authenticated),\n );\n event.complete\n ? onEmailChange(event.authenticated, event.value.email)\n : onEmailChange(false, '');\n\n if (isLoading) {\n isLoading(false);\n }\n\n if (isStripeLinkAuthenticated === undefined && event.authenticated && id) {\n this._store.dispatch(this._consignmentActionCreator.deleteConsignment(id));\n }\n });\n\n linkAuthenticationElement.mount(`#${container}`);\n }\n\n return this._store.getState();\n }\n\n deinitialize(): Promise {\n this._stripeElements?.getElement(StripeElementType.AUTHENTICATION)?.unmount();\n\n return Promise.resolve(this._store.getState());\n }\n\n signIn(\n credentials: CustomerCredentials,\n options?: CustomerRequestOptions,\n ): Promise {\n return this._store.dispatch(\n this._customerActionCreator.signInCustomer(credentials, options),\n );\n }\n\n signOut(options?: CustomerRequestOptions): Promise {\n return this._store.dispatch(this._customerActionCreator.signOutCustomer(options));\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport class ExtensionNotFoundError extends StandardError {\n constructor(message?: string) {\n super(message || 'Unable to proceed due to no extension configured for this region.');\n\n this.name = 'ExtensionNotFoundError';\n this.type = 'extension_not_found';\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Extension } from './extension';\n\nexport enum ExtensionActionType {\n LoadExtensionsRequested = 'LOAD_EXTENSIONS_REQUESTED',\n LoadExtensionsSucceeded = 'LOAD_EXTENSIONS_SUCCEEDED',\n LoadExtensionsFailed = 'LOAD_EXTENSIONS_FAILED',\n RenderExtensionRequested = 'RENDER_EXTENSION_REQUESTED',\n RenderExtensionSucceeded = 'RENDER_EXTENSION_SUCCEEDED',\n RenderExtensionFailed = 'RENDER_EXTENSION_FAILED',\n}\n\nexport type ExtensionAction =\n | LoadExtensionsRequestedAction\n | LoadExtensionsSucceededAction\n | LoadExtensionsFailedAction\n | RenderExtensionRequestedAction\n | RenderExtensionSucceededAction\n | RenderExtensionFailedAction;\n\nexport interface LoadExtensionsRequestedAction extends Action {\n type: ExtensionActionType.LoadExtensionsRequested;\n}\n\nexport interface LoadExtensionsSucceededAction extends Action {\n type: ExtensionActionType.LoadExtensionsSucceeded;\n}\n\nexport interface LoadExtensionsFailedAction extends Action {\n type: ExtensionActionType.LoadExtensionsFailed;\n}\n\nexport interface RenderExtensionRequestedAction extends Action {\n type: ExtensionActionType.RenderExtensionRequested;\n}\n\nexport interface RenderExtensionSucceededAction extends Action {\n type: ExtensionActionType.RenderExtensionSucceeded;\n}\n\nexport interface RenderExtensionFailedAction extends Action {\n type: ExtensionActionType.RenderExtensionFailed;\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport class InvalidExtensionConfigError extends StandardError {\n constructor(message?: string) {\n super(\n message || 'Unable to proceed due to invalid configuration provided for the extension.',\n );\n\n this.name = 'InvalidExtensionConfigError';\n this.type = 'invalid_extension_config';\n }\n}\n","import { InvalidExtensionConfigError } from './errors';\nimport { Extension } from './extension';\n\nexport class ExtensionIframe {\n private _iframe: HTMLIFrameElement;\n\n constructor(\n private _containerId: string,\n private _extension: Extension,\n private _cartId: string,\n ) {\n const url = new URL(this._extension.url);\n\n url.searchParams.set('extensionId', this._extension.id);\n url.searchParams.set('cartId', this._cartId);\n\n this._iframe = document.createElement('iframe');\n this._iframe.src = url.toString();\n this._iframe.style.border = 'none';\n this._iframe.style.height = '100%';\n this._iframe.style.overflow = 'hidden';\n this._iframe.style.width = '100%';\n }\n\n attach(): void {\n const container = document.getElementById(this._containerId);\n\n if (!container) {\n throw new InvalidExtensionConfigError(\n 'Unable to proceed because the provided container ID is invalid.',\n );\n }\n\n container.appendChild(this._iframe);\n }\n\n detach(): void {\n if (!this._iframe.parentElement) {\n return;\n }\n\n this._iframe.parentElement.removeChild(this._iframe);\n }\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { RequestOptions } from '../common/http-request';\n\nimport { ExtensionNotFoundError } from './errors';\nimport { ExtensionRegion } from './extension';\nimport { ExtensionAction, ExtensionActionType } from './extension-actions';\nimport { ExtensionIframe } from './extension-iframe';\nimport { ExtensionRequestSender } from './extension-request-sender';\n\nexport class ExtensionActionCreator {\n constructor(private _requestSender: ExtensionRequestSender) {}\n\n loadExtensions(\n options?: RequestOptions,\n ): ThunkAction {\n return () =>\n Observable.create((observer: Observer) => {\n observer.next(createAction(ExtensionActionType.LoadExtensionsRequested));\n\n this._requestSender\n .loadExtensions(options)\n .then((response) => {\n const extensions = response.body;\n\n observer.next(\n createAction(ExtensionActionType.LoadExtensionsSucceeded, extensions),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(ExtensionActionType.LoadExtensionsFailed, response),\n );\n });\n });\n }\n\n renderExtension(\n container: string,\n region: ExtensionRegion,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const { id: cartId } = state.cart.getCartOrThrow();\n const extension = state.extensions.getExtensionByRegion(region);\n\n if (!extension) {\n throw new ExtensionNotFoundError(\n `Unable to proceed due to no extension configured for ${region}.`,\n );\n }\n\n observer.next(createAction(ExtensionActionType.RenderExtensionRequested));\n\n try {\n const iframe = new ExtensionIframe(container, extension, cartId);\n\n iframe.attach();\n\n observer.next(createAction(ExtensionActionType.RenderExtensionSucceeded));\n observer.complete();\n } catch (error) {\n observer.error(\n createErrorAction(ExtensionActionType.RenderExtensionFailed, error),\n );\n }\n });\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { ContentType, RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nimport { Extension } from './extension';\n\nexport const EXTENSIONS_API_URL = '/api/storefront/checkout-extensions';\n\nexport class ExtensionRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n loadExtensions({ timeout, params }: RequestOptions = {}): Promise> {\n return this._requestSender.get(EXTENSIONS_API_URL, {\n timeout,\n headers: {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n },\n params,\n });\n }\n}\n","import InvalidArgumentError from './invalid-argument-error';\n\n/**\n * This error should be thrown when we are unable to submit a payment because\n * the caller has not provided all the required fields, i.e.: if an argument is\n * missing or it is not the expected data type.\n */\nexport default class PaymentArgumentInvalidError extends InvalidArgumentError {\n constructor(invalidFields?: string[]) {\n let message = 'Unable to submit payment for the order because the payload is invalid.';\n\n if (invalidFields) {\n message = `${message} Make sure the following fields are provided correctly: ${invalidFields.join(\n ', ',\n )}.`;\n }\n\n super(message);\n\n this.name = 'PaymentArgumentInvalidError';\n }\n}\n","import {\n FormattedPayload,\n FormattedVaultedInstrument,\n HostedVaultedInstrument,\n PaymentInstrument,\n VaultedInstrument,\n} from './payment';\n\nexport default function isVaultedInstrument(\n instrument: PaymentInstrument,\n): instrument is VaultedInstrument {\n return Boolean((instrument as VaultedInstrument).instrumentId);\n}\n\nexport function isHostedVaultedInstrument(\n instrument: PaymentInstrument,\n): instrument is HostedVaultedInstrument {\n return (\n Boolean((instrument as HostedVaultedInstrument).instrumentId) &&\n !Object.prototype.hasOwnProperty.call(instrument, 'ccNumber') &&\n !Object.prototype.hasOwnProperty.call(instrument, 'ccCvv')\n );\n}\n\nexport function isFormattedVaultedInstrument(\n instrument: PaymentInstrument,\n): instrument is FormattedPayload {\n const formattedInstrument = (instrument as FormattedPayload)\n .formattedPayload;\n\n if (!formattedInstrument) {\n return false;\n }\n\n return (\n typeof formattedInstrument.bigpay_token === 'string' ||\n Boolean(formattedInstrument.bigpay_token && formattedInstrument.bigpay_token.token)\n );\n}\n","import BrowserInfo from './browser-info';\n\nexport default function getBrowserInfo(): BrowserInfo {\n const { navigator } = window;\n\n let language: string;\n\n if (navigator.language) {\n language = navigator.language;\n } else {\n language = (navigator as any).userLanguage;\n }\n\n return {\n color_depth: window.screen.colorDepth || 24,\n java_enabled: typeof navigator.javaEnabled === 'function' ? navigator.javaEnabled() : false,\n language,\n screen_height: window.screen.height,\n screen_width: window.screen.width,\n time_zone_offset: new Date().getTimezoneOffset().toString(),\n };\n}\n","import StandardError from './standard-error';\n\n/**\n * Throw this error if we are trying to make an order finalization request for a\n * payment method that does not require such procedure.\n */\nexport default class OrderFinalizationNotRequiredError extends StandardError {\n constructor() {\n super('The current order does not need to be finalized at this stage.');\n\n this.name = 'OrderFinalizationNotRequiredError';\n this.type = 'order_finalization_not_required';\n }\n}\n","import RequestError from './request-error';\n\n// Have to use `as` https://stackoverflow.com/questions/73987044/typeguarding-an-unknown-nested-object should be fixed in 4.8+\nconst isRequestError = (error: unknown): error is RequestError => {\n return typeof error === 'object' && error !== null && 'body' in error;\n};\n\nexport default isRequestError;\n","import StandardError from './standard-error';\n\nexport interface PaymentInvalidFormErrorDetails {\n [key: string]: Array<{ message: string; type: string }>;\n}\n\nexport default class PaymentInvalidFormError extends StandardError {\n constructor(public details: PaymentInvalidFormErrorDetails, message?: string) {\n super(message || 'Unable to proceed because the payment form contains invalid data.');\n\n this.name = 'PaymentInvalidFormError';\n this.type = 'payment_invalid_form';\n }\n}\n","export enum AdyenActionType {\n /*\n * The payment qualifies for 3D Secure 2, and will go through either the frictionless\n * or the challenge flow.\n * */\n ThreeDS2Fingerprint = 'threeDS2Fingerprint',\n\n /*\n * The payment qualifies for 3D Secure 2, and the issuer is initiating a challenge flow.\n * */\n ThreeDS2Challenge = 'threeDS2Challenge',\n\n /*\n * We will initiate a 3D Secure 1 fallback, because the issuer does not support 3D Secure 2.\n * */\n Redirect = 'redirect',\n\n /*\n * The Component presents the QR code and calls the onAdditionalDetails event.\n * */\n QRCode = 'qrCode',\n\n /*\n * The Component displays the voucher which the shopper uses to complete the payment.\n * */\n Voucher = 'voucher',\n}\n\nexport enum AdyenComponentType {\n SecuredFields = 'securedfields',\n}\n\nexport enum AdyenPaymentMethodType {\n ACH = 'ach',\n AliPay = 'alipay',\n Bancontact = 'bcmc',\n CreditCard = 'scheme',\n Klarna = 'klarna',\n KlarnaPayNow = 'klarna_paynow',\n KlarnaAccount = 'klarna_account',\n IDEAL = 'ideal',\n GiroPay = 'giropay',\n GooglePay = 'paywithgoogle',\n SEPA = 'sepadirectdebit',\n Sofort = 'directEbanking',\n Vipps = 'vipps',\n WeChatPayQR = 'wechatpayQR',\n}\n\nexport enum HTTPMethod {\n POST = 'POST',\n}\n\nexport enum ResultCode {\n ChallengeShopper = 'ChallengeShopper',\n Error = 'Error',\n IdentifyShopper = 'IdentifyShopper',\n}\n\ninterface AdyenPaymentMethodState {\n type: string;\n}\n\ninterface CardDataPaymentMethodState {\n paymentMethod: CardPaymentMethodState;\n}\n\ninterface WechatDataPaymentMethodState {\n paymentMethod: AdyenPaymentMethodState;\n}\n\ninterface CardPaymentMethodState extends AdyenPaymentMethodState {\n encryptedCardNumber: string;\n encryptedExpiryMonth: string;\n encryptedExpiryYear: string;\n encryptedSecurityCode: string;\n holderName: string;\n}\n\nexport interface AdyenAction {\n method: HTTPMethod;\n\n /**\n * Value that you need to submit in your /payments/details request when handling\n * the redirect.\n */\n paymentData: string;\n\n paymentMethodType: AdyenPaymentMethodType;\n\n /*\n * The Component performs additional front-end actions depending on the action.type.\n * Your next steps depend on the type of action that the Component performs.\n */\n type: AdyenActionType;\n\n /**\n * The HTTP request method that you should use. After the shopper completes the payment,\n * they will be redirected back to your returnURL using the same method.\n */\n url: string;\n}\n\nexport interface AdyenAdditionalAction {\n resultCode: ResultCode;\n action: string;\n}\n\nexport interface AdyenAdditionalActionCallbacks {\n /**\n * A callback that gets called before adyen component is loaded\n */\n onBeforeLoad?(shopperInteraction?: boolean): void;\n\n /**\n * A callback that gets called when adyen component is loaded\n */\n onLoad?(cancel?: () => void): void;\n\n /**\n * A callback that gets called when adyen component verification\n * is completed\n */\n onComplete?(): void;\n}\n\nexport interface AdyenAdditionalActionErrorResponse {\n provider_data: AdyenAdditionalAction;\n errors: [\n {\n code: string;\n },\n ];\n}\n\nexport interface AdyenAdditionalActionOptions extends AdyenAdditionalActionCallbacks {\n /**\n * The location to insert the additional action component.\n */\n containerId: string;\n\n /**\n * Specify Three3DS2Challenge Widget Size\n *\n * Values\n * '01' = 250px x 400px\n * '02' = 390px x 400px\n * '03' = 500px x 600px\n * '04' = 600px x 400px\n * '05' = 100% x 100%\n */\n widgetSize?: string;\n}\n\nexport interface AdyenAdditionalActionState {\n data: AdyenAdditionalAction;\n isValid?: boolean;\n}\n\nexport interface AdyenBaseCardComponentOptions {\n /**\n * Array of card brands that will be recognized by the component.\n *\n */\n brands?: string[];\n\n /**\n * Set a style object to customize the input fields. See Styling Secured Fields\n * for a list of supported properties.\n */\n styles?: StyleOptions;\n}\n\nexport interface AdyenComponentEvents {\n /**\n * Called when the shopper enters data in the card input fields.\n * Here you have the option to override your main Adyen Checkout configuration.\n */\n onChange?(state: AdyenComponentState, component: AdyenComponent): void;\n\n /**\n * Called in case of an invalid card number, invalid expiry date, or\n * incomplete field. Called again when errors are cleared.\n */\n onError?(state: AdyenV2ValidationState, component: AdyenComponent): void;\n\n onFieldValid?(state: AdyenV2ValidationState, component: AdyenComponent): void;\n}\n\nexport interface AdyenClient {\n create(type: string, componentOptions?: AdyenComponentOptions): AdyenComponent;\n\n createFromAction(\n action: AdyenAction,\n componentOptions?:\n | ThreeDS2DeviceFingerprintComponentOptions\n | ThreeDS2ChallengeComponentOptions,\n ): AdyenComponent;\n}\n\nexport interface AdyenComponent {\n componentRef?: {\n showValidation(): void;\n };\n props?: {\n type?: string;\n };\n state?: CardState;\n mount(containerId: string): HTMLElement;\n unmount(): void;\n}\n\nexport interface AdyenConfiguration {\n /*\n * Use test, and then change this to live when you're ready to accept live payments.\n */\n environment?: string;\n\n /*\n * The shopper's locale. This is used to set the language rendered in the Components.\n */\n locale?: string;\n\n /*\n * The Origin Key of your website.\n */\n originKey?: string;\n\n /*\n * The Client Key of your Adyen account.\n */\n clientKey?: string;\n\n /*\n * Supported from Components version 3.0.0 and later. The full paymentMethods response,\n * returned in step 1. We recommend that you pass this on the AdyenCheckout instance.\n * Otherwise, you need to pass the specific payment method details separately for each\n * Component.\n */\n paymentMethodsResponse?: PaymentMethodsResponse;\n\n /**\n * If your shoppers use a language that isn't supported by the Components, you can create your own localization.\n * To create a localization:\n * Add a translations object to your payment page, specifying:\n * The localization you want to create.\n * An object containing the fields that are used in the Components, as well as the text you want displayed for each field.\n *\n * \"en\": {\n * \"paymentMethods.moreMethodsButton\": \"More payment methods\",\n * \"payButton\": \"Pay\",\n * \"storeDetails\": \"Save for my next payment\",\n * ...\n * }\n */\n translations?: {\n [index: string]: {\n [index: string]: string;\n };\n };\n\n /*\n * Specify the function that you created, for example, handleOnChange. If you wish\n * to override this function, you can also define an onChange event on the Component\n * level.\n */\n onChange?(state: CardState, component?: AdyenComponent): void;\n\n onAdditionalDetails?(state: CardState, component?: AdyenComponent): void;\n}\n\nexport interface AdyenPlaceholderData {\n holderName?: string;\n prefillCardHolderName?: boolean;\n billingAddress?: {\n street: string;\n houseNumberOrName: string;\n postalCode: string;\n city: string;\n stateOrProvince: string;\n country: string;\n };\n}\n\nexport interface AdyenCreditCardComponentOptions\n extends AdyenBaseCardComponentOptions,\n AdyenComponentEvents {\n /**\n * Set an object containing the details array for type: scheme from\n * the /paymentMethods response.\n */\n details?: InputDetail[];\n\n /**\n * Set to true to show the checkbox to save card details for the next payment.\n */\n enableStoreDetails?: boolean;\n\n /**\n * Set to true to request the name of the card holder.\n */\n hasHolderName?: boolean;\n\n /**\n * Set to true to require the card holder name.\n */\n holderNameRequired?: boolean;\n\n /**\n * Information to prefill fields.\n */\n data?: AdyenPlaceholderData;\n\n /**\n * Defaults to ['mc','visa','amex']. Configure supported card types to\n * facilitate brand recognition used in the Secured Fields onBrand callback.\n * See list of available card types. If a shopper enters a card type not\n * specified in the GroupTypes configuration, the onBrand callback will not be invoked.\n */\n groupTypes?: string[];\n\n /**\n * Specify the sample values you want to appear for card detail input fields.\n */\n placeholders?: CreditCardPlaceHolder | SepaPlaceHolder;\n}\n\nexport interface AdyenCustomCardComponentOptions\n extends AdyenBaseCardComponentOptions,\n AdyenComponentEvents {\n /**\n * Specify aria attributes for the input fields for web accessibility.\n */\n ariaLabels?: CustomCardAriaLabels;\n\n /**\n * Automatically shift the focus from date field to the CVC field.\n */\n autofocus?: boolean;\n}\n\nexport interface AdyenError {\n errorCode: string;\n message: string;\n}\n\nexport interface AdyenHostWindow extends Window {\n AdyenCheckout?: new (configuration: AdyenConfiguration) => AdyenClient;\n}\n\nexport interface AdyenIdealComponentOptions extends AdyenBaseCardComponentOptions {\n /**\n * Optional. Set to **false** to remove the bank logos from the iDEAL form.\n */\n showImage?: boolean;\n}\n\nexport interface AdyenStoredPaymentMethod {\n /**\n * The brand of the card.\n */\n brand?: string;\n\n /**\n * The month the card expires.\n */\n expiryMonth?: string;\n\n /**\n * The year the card expires.\n */\n expiryYear?: string;\n\n /**\n * The unique payment method code.\n */\n holderName?: string;\n\n /**\n * A unique identifier of this stored payment method.\n */\n id?: string;\n\n /**\n * The last four digits of the PAN.\n */\n lastFour?: string;\n\n /**\n * The display name of the stored payment method.\n */\n name: string;\n\n /**\n * The shopper’s email address.\n */\n shopperEmail?: string;\n\n /**\n * The supported shopper interactions for this stored payment method.\n */\n supportedShopperInteractions?: string[];\n\n /**\n * The type of payment method.\n */\n type?: string;\n}\n\nexport interface AdyenThreeDS2Options extends AdyenAdditionalActionCallbacks {\n /**\n * Specify Three3DS2Challenge Widget Size\n *\n * Values\n * '01' = 250px x 400px\n * '02' = 390px x 400px\n * '03' = 500px x 600px\n * '04' = 600px x 400px\n * '05' = 100% x 100%\n */\n widgetSize?: string;\n}\n\nexport interface Bank {\n /**\n * The bank account number (without separators).\n */\n bankAccountNumber?: string;\n\n /**\n * The bank city.\n */\n bankCity?: string;\n\n /**\n * The location id of the bank. The field value is nil in most cases.\n */\n bankLocationId?: string;\n\n /**\n * The name of the bank.\n */\n bankName?: string;\n\n /**\n * The Business Identifier Code (BIC) is the SWIFT address assigned to\n * a bank. The field value is nil in most cases.\n */\n bic?: string;\n\n /**\n * Country code where the bank is located.\n * A valid value is an ISO two-character country code (e.g. 'NL').\n */\n countryCode?: string;\n\n /**\n * The International Bank Account Number (IBAN).\n */\n iban?: string;\n\n /**\n * The name of the bank account holder. If you submit a name with non-Latin\n * characters, we automatically replace some of them with corresponding Latin\n * characters to meet the FATF recommendations. For example:\n * χ12 is converted to ch12.\n * üA is converted to euA.\n * Peter Møller is converted to Peter Mller, because banks don't accept 'ø'.\n * After replacement, the ownerName must have at least three alphanumeric characters\n * (A-Z, a-z, 0-9), and at least one of them must be a valid Latin character\n * (A-Z, a-z). For example:\n * John17 - allowed.\n * J17 - allowed.\n * 171 - not allowed.\n * John-7 - allowed.\n */\n ownerName?: string;\n\n /**\n * The bank account holder's tax ID.\n */\n taxId?: string;\n}\n\nexport interface Card {\n /**\n * The card verification code (1-20 characters). Depending on the card brand, it\n * is known also as:\n * CVV2/CVC2 – length: 3 digits\n * CID – length: 4 digits\n */\n cvc?: string;\n\n /**\n * The card expiry month. Format: 2 digits, zero-padded for single digits. For example:\n * 03 = March\n * 11 = November\n * Required\n */\n expiryMonth: string;\n\n /**\n * The card expiry year. Format: 4 digits. For example: 2020\n * Required\n */\n expiryYear: string;\n\n /**\n * The name of the cardholder, as printed on the card.\n * Required\n */\n holderName: string;\n\n /**\n * The issue number of the card (for some UK debit cards only).\n */\n issueNumber?: string;\n\n /**\n * The card number (4-19 characters). Do not use any separators. When this value is\n * returned in a response, only the last 4 digits of the card number are returned.\n * Required\n */\n number: string;\n\n /**\n * The month component of the start date (for some UK debit cards only).\n */\n startNumber?: string;\n\n /**\n * The year component of the start date (for some UK debit cards only).\n */\n startYear?: string;\n}\n\nexport interface CardState {\n data: CardDataPaymentMethodState;\n isValid?: boolean;\n issuer?: string;\n valid?: { [key: string]: boolean };\n errors?: CardStateErrors;\n}\n\nexport interface CardStateErrors {\n [key: string]: string;\n}\n\nexport interface WechatState {\n data: WechatDataPaymentMethodState;\n}\n\nexport interface CreditCardPlaceHolder {\n encryptedCardNumber?: string;\n encryptedExpiryDate?: string;\n encryptedSecurityCode: string;\n}\n\ninterface AccountDataPaymentMethodState {\n paymentMethod: AdyenPaymentMethodState;\n}\n\nexport interface AccountState {\n data: AccountDataPaymentMethodState;\n}\n\nexport interface CssProperties {\n background?: string;\n caretColor?: string;\n color?: string;\n display?: string;\n font?: string;\n fontFamily?: string;\n fontSize?: string;\n fontSizeAdjust?: string;\n fontSmoothing?: string;\n fontStretch?: string;\n fontStyle?: string;\n fontVariant?: string;\n fontVariantAlternates?: string;\n fontVariantCaps?: string;\n fontVariantEastAsian?: string;\n fontVariantLigatures?: string;\n fontVariantNumeric?: string;\n fontWeight?: string;\n letterSpacing?: string;\n lineHeight?: string;\n mozOsxFontSmoothing?: string;\n mozTransition?: string;\n outline?: string;\n opacity?: string | number;\n padding?: string;\n textAlign?: string;\n textShadow?: string;\n transition?: string;\n webkitFontSmoothing?: string;\n webkitTransition?: string;\n}\n\nexport interface CustomCardAriaLabel {\n label?: string;\n iframeTitle?: string;\n}\n\nexport interface CustomCardAriaLabels {\n lang?: string;\n encryptedCardNumber?: CustomCardAriaLabel;\n encryptedExpiryDate?: CustomCardAriaLabel;\n encryptedSecurityCode?: CustomCardAriaLabel;\n}\n\nexport interface Group {\n /**\n * The name of the group.\n */\n name?: string;\n\n /**\n * Echo data to be used if the payment method is displayed as part of this group.\n */\n paymentMethodData?: string;\n\n /**\n * The unique code of the group.\n */\n type?: string;\n}\n\nexport interface InputDetail {\n /**\n * Configuration parameters for the required input.\n */\n configuration?: object;\n\n /**\n * Input details can also be provided recursively.\n */\n details?: SubInputDetail[];\n\n /**\n * In case of a select, the URL from which to query the items.\n */\n itemSearchUrl?: string;\n\n /**\n * In case of a select, the items to choose from.\n */\n items?: Item[];\n\n /**\n * The value to provide in the result.\n */\n key?: string;\n\n /**\n * True if this input value is optional.\n */\n optional?: boolean;\n\n /**\n * The type of the required input.\n */\n type?: string;\n\n /**\n * The value can be pre-filled, if available.\n */\n value?: string;\n}\n\nexport interface Item {\n /**\n * The value to provide in the result.\n */\n id?: string;\n\n /**\n * The display name.\n */\n name?: string;\n}\n\nexport interface PaymentMethod {\n /**\n * List of possible brands. For example: visa, mc.\n */\n brands?: string[];\n\n /**\n * The configuration of the payment method.\n */\n configuration?: object;\n\n /**\n * All input details to be provided to complete the payment with this payment\n * method.\n */\n details?: InputDetail[];\n\n /**\n * The group where this payment method belongs to.\n */\n group?: Group;\n\n /**\n * The displayable name of this payment method.\n */\n name?: string;\n\n /**\n * Echo data required to send in next calls.\n */\n paymentMethodData?: string;\n\n /**\n * Indicates whether this payment method supports tokenization or not.\n */\n supportsRecurring?: boolean;\n\n /**\n * The unique payment method code.\n */\n type?: string;\n}\n\nexport interface PaymentMethodGroup {\n /**\n * The type to submit for any payment method in this group.\n */\n groupType?: string;\n\n /**\n * The human-readable name of this group.\n */\n name?: string;\n\n /**\n * The types of payment methods that belong in this group.\n */\n types?: string[];\n}\n\nexport interface PaymentMethodsResponse {\n /**\n * Groups of payment methods.\n */\n groups?: PaymentMethodGroup[];\n\n /**\n * Detailed list of one-click payment methods.\n */\n oneClickPaymentMethods?: RecurringDetail;\n\n /**\n * Detailed list of payment methods required to generate payment forms.\n */\n paymentMethods?: PaymentMethod[];\n\n /**\n * List of all stored payment methods.\n */\n storedPaymentMethods?: AdyenStoredPaymentMethod[];\n}\n\nexport interface RecurringDetail extends PaymentMethod {\n /**\n * The reference that uniquely identifies the recurring detail.\n */\n recurringDetailReference?: string;\n\n /**\n * Contains information on previously stored payment details.\n */\n storedDetails?: StoredDetails;\n}\n\nexport interface SepaPlaceHolder {\n ownerName?: string;\n ibanNumber?: string;\n}\n\nexport interface StoredDetails {\n /**\n * The stored bank account.\n */\n bank?: Bank;\n\n /**\n * The stored card information.\n */\n card?: Card;\n\n /**\n * The email associated with stored payment details.\n */\n emailAddress?: string;\n}\n\nexport interface StyleOptions {\n /**\n * Base styling applied to the iframe. All styling extends from this style.\n */\n base?: CssProperties;\n\n /**\n * Styling applied when a field fails validation.\n */\n error?: CssProperties;\n\n /**\n * Styling applied to the field's placeholder values.\n */\n placeholder?: CssProperties;\n\n /**\n * Styling applied once a field passes validation.\n */\n validated?: CssProperties;\n}\n\nexport interface SubInputDetail {\n /**\n * Configuration parameters for the required input.\n */\n configuration?: object;\n\n /**\n * In case of a select, the items to choose from.\n */\n items?: Item[];\n\n /**\n * The value to provide in the result.\n */\n key?: string;\n\n /**\n * True if this input is optional to provide.\n */\n optional?: boolean;\n\n /**\n * The type of the required input.\n */\n type?: string;\n\n /**\n * The value can be pre-filled, if available.\n */\n value?: string;\n}\n\nexport interface ThreeDS2ChallengeComponentOptions {\n size?: string;\n onAdditionalDetails?(state: AdyenAdditionalActionState, component?: AdyenComponent): void;\n onError(error: AdyenError): void;\n}\n\nexport interface ThreeDS2DeviceFingerprintComponentOptions {\n onAdditionalDetails?(state: AdyenAdditionalActionState, component?: AdyenComponent): void;\n onError(error: AdyenError): void;\n}\n\nexport type AdyenComponentState = CardState | WechatState;\n\nexport interface AdyenV2ValidationState {\n valid: boolean;\n fieldType?: AdyenV2CardFields;\n endDigits?: string;\n encryptedFieldName?: string;\n i18n?: string;\n error?: string;\n errorKey?: string;\n}\n\nexport enum AdyenV2CardFields {\n CardNumber = 'encryptedCardNumber',\n SecurityCode = 'encryptedSecurityCode',\n ExpiryDate = 'encryptedExpiryDate',\n}\n\nexport type AdyenComponentOptions =\n | AdyenCreditCardComponentOptions\n | AdyenIdealComponentOptions\n | AdyenCustomCardComponentOptions;\n\nexport function isCardState(param: any): param is CardState {\n return (\n (param && typeof param.data.paymentMethod.encryptedSecurityCode === 'string') ||\n typeof param.data.paymentMethod.encryptedExpiryMonth === 'string'\n );\n}\n\nexport function isAccountState(param: any): param is AccountState {\n const bankSupported = ['ideal', 'sepadirectdebit', 'directEbanking', 'giropay'];\n\n return bankSupported.indexOf(param.data.paymentMethod.type) !== -1;\n}\n\nexport interface AdyenPaymentMethodInitializationData {\n originKey?: string;\n clientKey?: string;\n environment?: string;\n paymentMethodsResponse?: PaymentMethodsResponse;\n prefillCardHolderName?: boolean;\n}\n","import { some } from 'lodash';\n\nimport {\n BillingAddress,\n getBrowserInfo,\n HostedInstrument,\n InvalidArgumentError,\n isRequestError,\n isVaultedInstrument,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n PaymentMethod,\n PaymentMethodCancelledError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n AdyenAction,\n AdyenActionType,\n AdyenAdditionalAction,\n AdyenAdditionalActionState,\n AdyenClient,\n AdyenComponent,\n AdyenComponentState,\n AdyenComponentType,\n AdyenError,\n AdyenPaymentMethodInitializationData,\n AdyenPaymentMethodType,\n AdyenPlaceholderData,\n CardStateErrors,\n isAccountState,\n isCardState,\n} from './adyenv2';\nimport AdyenV2PaymentInitializeOptions, {\n WithAdyenV2PaymentInitializeOptions,\n} from './adyenv2-initialize-options';\nimport AdyenV2ScriptLoader from './adyenv2-script-loader';\n\nexport default class AdyenV2PaymentStrategy implements PaymentStrategy {\n private _adyenClient?: AdyenClient;\n private _cardVerificationComponent?: AdyenComponent;\n private _componentState?: AdyenComponentState;\n private _paymentComponent?: AdyenComponent;\n private _paymentInitializeOptions?: AdyenV2PaymentInitializeOptions;\n\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _scriptLoader: AdyenV2ScriptLoader,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithAdyenV2PaymentInitializeOptions,\n ): Promise {\n const { adyenv2 } = options;\n\n if (!adyenv2) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.adyenv2\" argument is not provided.',\n );\n }\n\n this._paymentInitializeOptions = adyenv2;\n\n const paymentMethod = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(options.methodId);\n const { originKey, clientKey, environment, paymentMethodsResponse } =\n paymentMethod.initializationData || {};\n const clientSideAuthentication = {\n key: '',\n value: '',\n };\n\n if (originKey) {\n clientSideAuthentication.key = 'originKey';\n clientSideAuthentication.value = originKey;\n } else {\n clientSideAuthentication.key = 'clientKey';\n clientSideAuthentication.value = clientKey || '';\n }\n\n this._adyenClient = await this._scriptLoader.load({\n environment,\n locale: this._paymentIntegrationService.getState().getLocale(),\n [clientSideAuthentication.key]: clientSideAuthentication.value,\n paymentMethodsResponse,\n translations: {\n es: { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-AR': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-ES': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-MX': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-CL': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-CO': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-PE': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n },\n });\n\n this._paymentComponent = await this._mountPaymentComponent(paymentMethod);\n\n if (\n paymentMethod.method === AdyenPaymentMethodType.CreditCard ||\n paymentMethod.method === AdyenPaymentMethodType.Bancontact\n ) {\n this._cardVerificationComponent = await this._mountCardVerificationComponent();\n }\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment && payment.paymentData;\n const shouldSaveInstrument =\n paymentData && (paymentData as HostedInstrument).shouldSaveInstrument;\n const shouldSetAsDefaultInstrument =\n paymentData && (paymentData as HostedInstrument).shouldSetAsDefaultInstrument;\n\n if (!payment) {\n return Promise.reject(new PaymentArgumentInvalidError(['payment']));\n }\n\n this._validateCardData();\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n const componentState = this._componentState;\n\n if (!componentState) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (paymentData && isVaultedInstrument(paymentData)) {\n let bigpayToken = {};\n\n if (isCardState(componentState)) {\n const {\n encryptedCardNumber,\n encryptedSecurityCode,\n encryptedExpiryMonth,\n encryptedExpiryYear,\n } = componentState.data.paymentMethod;\n\n bigpayToken = {\n credit_card_number_confirmation: encryptedCardNumber,\n expiry_month: encryptedExpiryMonth,\n expiry_year: encryptedExpiryYear,\n verification_value: encryptedSecurityCode,\n };\n }\n\n if (isCardState(componentState) || isAccountState(componentState)) {\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n formattedPayload: {\n bigpay_token: {\n ...bigpayToken,\n token: paymentData.instrumentId,\n },\n origin: window.location.origin,\n browser_info: getBrowserInfo(),\n set_as_default_stored_instrument:\n shouldSetAsDefaultInstrument || null,\n },\n },\n });\n\n return;\n } catch (error) {\n await this._processAdditionalAction(\n error,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n\n return;\n }\n }\n }\n\n try {\n await this._paymentIntegrationService.submitPayment({\n methodId: payment.methodId,\n paymentData: {\n formattedPayload: {\n credit_card_token: {\n token: JSON.stringify({\n ...componentState.data.paymentMethod,\n origin: window.location.origin,\n }),\n },\n browser_info: getBrowserInfo(),\n vault_payment_instrument: shouldSaveInstrument || null,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n },\n },\n });\n } catch (error) {\n await this._processAdditionalAction(\n error,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this._componentState = undefined;\n\n if (this._paymentComponent) {\n this._paymentComponent.unmount();\n this._paymentComponent = undefined;\n }\n\n if (this._cardVerificationComponent) {\n this._cardVerificationComponent.unmount();\n this._cardVerificationComponent = undefined;\n }\n\n return Promise.resolve();\n }\n\n private _getAdyenClient(): AdyenClient {\n if (!this._adyenClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._adyenClient;\n }\n\n private _getPaymentInitializeOptions(): AdyenV2PaymentInitializeOptions {\n if (!this._paymentInitializeOptions) {\n throw new InvalidArgumentError(\n '\"options.adyenv2\" argument was not provided during initialization.',\n );\n }\n\n return this._paymentInitializeOptions;\n }\n\n private _getThreeDS2ChallengeWidgetSize(): string {\n const { additionalActionOptions, threeDS2Options } = this._getPaymentInitializeOptions();\n const widgetSize = additionalActionOptions.widgetSize || threeDS2Options?.widgetSize;\n\n if (!widgetSize) {\n return '05';\n }\n\n return widgetSize;\n }\n\n private _handleAction(additionalAction: AdyenAdditionalAction): Promise {\n return new Promise((resolve, reject) => {\n const { threeDS2ContainerId, additionalActionOptions } =\n this._getPaymentInitializeOptions();\n const { onBeforeLoad, containerId, onLoad, onComplete } = additionalActionOptions;\n const adyenAction: AdyenAction = JSON.parse(additionalAction.action);\n\n const additionalActionComponent = this._getAdyenClient().createFromAction(adyenAction, {\n onAdditionalDetails: (additionalActionState: AdyenAdditionalActionState) => {\n const paymentPayload = {\n methodId: adyenAction.paymentMethodType,\n paymentData: {\n nonce: JSON.stringify(additionalActionState.data),\n },\n };\n\n if (onComplete) {\n onComplete();\n }\n\n resolve(paymentPayload);\n },\n size: this._getThreeDS2ChallengeWidgetSize(),\n onError: (error: AdyenError) => reject(error),\n });\n\n if (onBeforeLoad) {\n onBeforeLoad(\n adyenAction.type === AdyenActionType.ThreeDS2Challenge ||\n adyenAction.type === AdyenActionType.QRCode,\n );\n }\n\n additionalActionComponent.mount(`#${containerId || threeDS2ContainerId}`);\n\n if (onLoad) {\n onLoad(() => {\n reject(new PaymentMethodCancelledError());\n additionalActionComponent.unmount();\n });\n }\n });\n }\n\n private _mapAdyenPlaceholderData(\n billingAddress?: BillingAddress,\n prefillCardHolderName?: boolean,\n ): AdyenPlaceholderData {\n if (!billingAddress) {\n return {};\n }\n\n const {\n firstName,\n lastName,\n address1: street,\n address2: houseNumberOrName,\n postalCode,\n city,\n stateOrProvinceCode: stateOrProvince,\n countryCode: country,\n } = billingAddress;\n\n return {\n holderName: prefillCardHolderName ? `${firstName} ${lastName}` : '',\n billingAddress: {\n street,\n houseNumberOrName,\n postalCode,\n city,\n stateOrProvince,\n country,\n },\n };\n }\n\n private _mountCardVerificationComponent(): Promise {\n const adyenv2 = this._getPaymentInitializeOptions();\n const adyenClient = this._getAdyenClient();\n let cardVerificationComponent: AdyenComponent;\n\n return new Promise((resolve, reject) => {\n if (adyenv2.cardVerificationContainerId) {\n cardVerificationComponent = adyenClient.create(AdyenComponentType.SecuredFields, {\n ...adyenv2.options,\n styles: {\n ...adyenv2.options?.styles,\n placeholder: {\n color: 'transparent',\n caretColor: '#000',\n ...adyenv2.options?.styles?.placeholder,\n },\n },\n onChange: (componentState) => this._updateComponentState(componentState),\n onError: (validateState) => adyenv2.validateCardFields(validateState),\n onFieldValid: (validateState) => adyenv2.validateCardFields(validateState),\n });\n\n try {\n cardVerificationComponent.mount(`#${adyenv2.cardVerificationContainerId}`);\n } catch (error) {\n reject(new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized));\n }\n }\n\n resolve(cardVerificationComponent);\n });\n }\n\n private _mountPaymentComponent(paymentMethod: PaymentMethod): Promise {\n let paymentComponent: AdyenComponent;\n const adyenv2 = this._getPaymentInitializeOptions();\n const adyenClient = this._getAdyenClient();\n\n return new Promise((resolve, reject) => {\n switch (paymentMethod.method) {\n case AdyenPaymentMethodType.CreditCard:\n case AdyenPaymentMethodType.ACH:\n case AdyenPaymentMethodType.Bancontact: {\n const billingAddress = this._paymentIntegrationService\n .getState()\n .getBillingAddress();\n const { prefillCardHolderName } = paymentMethod.initializationData;\n paymentComponent = adyenClient.create(paymentMethod.method, {\n ...adyenv2.options,\n onChange: (componentState) => this._updateComponentState(componentState),\n data: this._mapAdyenPlaceholderData(billingAddress, prefillCardHolderName),\n });\n\n try {\n paymentComponent.mount(`#${adyenv2.containerId}`);\n } catch (error) {\n reject(\n new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n break;\n }\n\n case AdyenPaymentMethodType.IDEAL:\n case AdyenPaymentMethodType.SEPA:\n if (!adyenv2.hasVaultedInstruments) {\n paymentComponent = adyenClient.create(paymentMethod.method, {\n ...adyenv2.options,\n onChange: (componentState) =>\n this._updateComponentState(componentState),\n });\n\n try {\n paymentComponent.mount(`#${adyenv2.containerId}`);\n } catch (error) {\n reject(\n new NotInitializedError(\n NotInitializedErrorType.PaymentNotInitialized,\n ),\n );\n }\n } else {\n this._updateComponentState({\n data: {\n paymentMethod: {\n type: paymentMethod.method,\n },\n },\n });\n }\n\n break;\n\n case AdyenPaymentMethodType.AliPay:\n case AdyenPaymentMethodType.GiroPay:\n case AdyenPaymentMethodType.Sofort:\n case AdyenPaymentMethodType.Klarna:\n case AdyenPaymentMethodType.KlarnaPayNow:\n case AdyenPaymentMethodType.KlarnaAccount:\n case AdyenPaymentMethodType.Vipps:\n case AdyenPaymentMethodType.WeChatPayQR:\n this._updateComponentState({\n data: {\n paymentMethod: {\n type: paymentMethod.method,\n },\n },\n });\n }\n\n resolve(paymentComponent);\n });\n }\n\n private async _processAdditionalAction(\n error: unknown,\n shouldSaveInstrument?: boolean,\n shouldSetAsDefaultInstrument?: boolean,\n ): Promise {\n if (\n !isRequestError(error) ||\n !some(error.body.errors, { code: 'additional_action_required' })\n ) {\n throw error;\n }\n\n const payment = await this._handleAction(error.body.provider_data);\n\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n ...payment.paymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n },\n });\n } catch (paymentError) {\n return this._processAdditionalAction(\n paymentError,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n private _updateComponentState(componentState: AdyenComponentState) {\n this._componentState = componentState;\n }\n\n private _validateCardData(): void {\n const adyenv2 = this._getPaymentInitializeOptions();\n const cardComponent = adyenv2.hasVaultedInstruments\n ? this._cardVerificationComponent\n : this._paymentComponent;\n\n if (!cardComponent?.componentRef?.showValidation || !cardComponent.state) {\n return;\n }\n\n cardComponent.componentRef.showValidation();\n\n /**\n * For some reason adyen sdk doesn't return isValid for payment methods with select field in form(iDeal for example)\n * so we need to check state issuer field\n */\n if (\n Object.keys(cardComponent.state).length === 0 ||\n (!cardComponent.state.isValid && !cardComponent.state.issuer)\n ) {\n throw new PaymentInvalidFormError(this._mapCardErrors(cardComponent.state.errors));\n }\n }\n\n private _mapCardErrors(cardStateErrors: CardStateErrors = {}): PaymentInvalidFormErrorDetails {\n const errors: PaymentInvalidFormErrorDetails = {};\n\n Object.keys(cardStateErrors).forEach((key) => {\n errors[key] = [\n {\n message: cardStateErrors[key],\n type: key,\n },\n ];\n });\n\n return errors;\n }\n}\n","import { ScriptLoader, StylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { AdyenClient, AdyenConfiguration, AdyenHostWindow } from './adyenv2';\n\nexport default class AdyenV2ScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _stylesheetLoader: StylesheetLoader,\n private _window: AdyenHostWindow = window,\n ) {}\n\n async load(configuration: AdyenConfiguration): Promise {\n await Promise.all([\n this._stylesheetLoader.loadStylesheet(\n `https://checkoutshopper-${\n configuration.environment ?? ''\n }.adyen.com/checkoutshopper/sdk/3.10.1/adyen.css`,\n ),\n this._scriptLoader.loadScript(\n `https://checkoutshopper-${\n configuration.environment ?? ''\n }.adyen.com/checkoutshopper/sdk/3.10.1/adyen.js`,\n ),\n ]);\n\n if (!this._window.AdyenCheckout) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return new this._window.AdyenCheckout(configuration);\n }\n}\n","import { getScriptLoader, getStylesheetLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport AdyenV2PaymentStrategy from './adyenv2-payment-strategy';\nimport AdyenV2ScriptLoader from './adyenv2-script-loader';\n\nconst createAdyenV2PaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new AdyenV2PaymentStrategy(\n paymentIntegrationService,\n new AdyenV2ScriptLoader(getScriptLoader(), getStylesheetLoader()),\n );\n};\n\nexport default toResolvableModule(createAdyenV2PaymentStrategy, [{ gateway: 'adyenv2' }]);\n","import { HostedInstrument } from './payment';\n\nexport default function isHostedInstrumentLike(\n instrument: unknown,\n): instrument is HostedInstrument {\n return (\n typeof instrument === 'object' &&\n instrument !== null &&\n (typeof (instrument as HostedInstrument).shouldSaveInstrument === 'undefined' ||\n typeof (instrument as HostedInstrument).shouldSaveInstrument === 'boolean') &&\n (typeof (instrument as HostedInstrument).shouldSetAsDefaultInstrument === 'undefined' ||\n typeof (instrument as HostedInstrument).shouldSetAsDefaultInstrument === 'boolean')\n );\n}\n","export enum AdyenActionType {\n /*\n * The payment qualifies for 3D Secure 2, and will go through either the frictionless\n * or the challenge flow.\n * */\n ThreeDS2Fingerprint = 'threeDS2Fingerprint',\n\n /*\n * The payment qualifies for 3D Secure 2, and the issuer is initiating a challenge flow.\n * */\n ThreeDS2 = 'threeDS2',\n\n /*\n * We will initiate a 3D Secure 1 fallback, because the issuer does not support 3D Secure 2.\n * */\n Redirect = 'redirect',\n\n /*\n * The Component presents the QR code and calls the onAdditionalDetails event.\n * */\n QRCode = 'qrCode',\n\n /*\n * The Component displays the voucher which the shopper uses to complete the payment.\n * */\n Voucher = 'voucher',\n\n /*\n * The Component displays the widget which the shopper uses to complete the payment.\n * */\n Sdk = 'sdk',\n}\n\nexport enum AdyenComponentType {\n SecuredFields = 'securedfields',\n}\n\nexport enum AdyenPaymentMethodType {\n ACH = 'ach',\n AliPay = 'alipay',\n Bancontact = 'bcmc',\n CreditCard = 'scheme',\n Klarna = 'klarna',\n KlarnaPayNow = 'klarna_paynow',\n KlarnaAccount = 'klarna_account',\n IDEAL = 'ideal',\n GiroPay = 'giropay',\n GooglePay = 'paywithgoogle',\n SEPA = 'sepadirectdebit',\n Sofort = 'directEbanking',\n Vipps = 'vipps',\n WeChatPayQR = 'wechatpayQR',\n}\n\nexport enum HTTPMethod {\n POST = 'POST',\n}\n\nexport enum ResultCode {\n ChallengeShopper = 'ChallengeShopper',\n Error = 'Error',\n IdentifyShopper = 'IdentifyShopper',\n}\n\ninterface AdyenPaymentMethodState {\n type: string;\n}\n\ninterface WechatDataPaymentMethodState {\n paymentMethod: AdyenPaymentMethodState;\n}\n\ninterface CardPaymentMethodState {\n encryptedCardNumber: string;\n encryptedExpiryMonth: string;\n encryptedExpiryYear: string;\n encryptedSecurityCode: string;\n holderName: string;\n}\n\nexport interface AdyenAction {\n method: HTTPMethod;\n\n /**\n * Value that you need to submit in your /payments/details request when handling\n * the redirect.\n */\n paymentData: string;\n\n paymentMethodType: AdyenPaymentMethodType;\n\n /*\n * The Component performs additional front-end actions depending on the action.type.\n * Your next steps depend on the type of action that the Component performs.\n */\n type: AdyenActionType;\n\n /**\n * The HTTP request method that you should use. After the shopper completes the payment,\n * they will be redirected back to your returnURL using the same method.\n */\n url: string;\n}\n\nexport interface AdyenAdditionalAction {\n resultCode: ResultCode;\n action: string;\n}\n\nexport interface AdyenAdditionalActionCallbacks {\n /**\n * A callback that gets called before adyen component is loaded\n */\n onBeforeLoad?(shopperInteraction?: boolean): void;\n\n /**\n * A callback that gets called when adyen component is loaded\n */\n onLoad?(cancel?: () => void): void;\n\n /**\n * A callback that gets called when adyen component verification\n * is completed\n */\n onComplete?(): void;\n}\n\nexport interface AdyenAdditionalActionErrorResponse {\n provider_data: AdyenAdditionalAction;\n errors: [\n {\n code: string;\n },\n ];\n}\n\nexport interface AdyenAdditionalActionOptions extends AdyenAdditionalActionCallbacks {\n /**\n * The location to insert the additional action component.\n */\n containerId: string;\n\n /**\n * Specify Three3DS2Challenge Widget Size\n *\n * Values\n * '01' = 250px x 400px\n * '02' = 390px x 400px\n * '03' = 500px x 600px\n * '04' = 600px x 400px\n * '05' = 100% x 100%\n */\n widgetSize?: string;\n}\n\nexport interface AdyenAdditionalActionState {\n data: AdyenAdditionalAction;\n isValid?: boolean;\n}\n\nexport interface AdyenBaseCardComponentOptions {\n /**\n * Array of card brands that will be recognized by the component.\n *\n */\n brands?: string[];\n\n /**\n * Set a style object to customize the input fields. See Styling Secured Fields\n * for a list of supported properties.\n */\n styles?: StyleOptions;\n\n showBrandsUnderCardNumber?: boolean;\n}\n\nexport interface AdyenComponentEvents {\n /**\n * Called when the shopper enters data in the card input fields.\n * Here you have the option to override your main Adyen Checkout configuration.\n */\n onChange?(state: AdyenV3ComponentState, component: AdyenComponent): void;\n\n /**\n * Called when the shopper selects the Pay button and payment details are valid.\n */\n onSubmit?(state: AdyenV3ComponentState, component: AdyenComponent): void;\n\n /**\n * Called in case of an invalid card number, invalid expiry date, or\n * incomplete field. Called again when errors are cleared.\n */\n onError?(state: AdyenV3ValidationState, component: AdyenComponent): void;\n\n onFieldValid?(state: AdyenV3ValidationState, component: AdyenComponent): void;\n}\n\nexport interface AdyenClient {\n create(type: string, componentOptions?: AdyenComponentOptions): AdyenComponent;\n\n createFromAction(\n action: AdyenAction,\n componentOptions?:\n | ThreeDS2DeviceFingerprintComponentOptions\n | ThreeDS2ChallengeComponentOptions,\n ): AdyenComponent;\n}\n\nexport interface AdyenComponent {\n componentRef?: {\n showValidation(): void;\n };\n props?: {\n type?: string;\n };\n state?: CardState;\n mount(containerId: string): HTMLElement;\n unmount(): void;\n submit(): void;\n}\n\nexport interface AdyenConfiguration {\n /*\n * Use test, and then change this to live when you're ready to accept live payments.\n */\n environment?: string;\n\n /*\n * The shopper's locale. This is used to set the language rendered in the Components.\n */\n locale?: string;\n\n /*\n * The Origin Key of your website.\n */\n originKey?: string;\n\n /*\n * The Client Key of your Adyen account.\n */\n clientKey?: string;\n\n /*\n * Supported from Components version 3.0.0 and later. The full paymentMethods response,\n * returned in step 1. We recommend that you pass this on the AdyenCheckout instance.\n * Otherwise, you need to pass the specific payment method details separately for each\n * Component.\n */\n paymentMethodsResponse?: PaymentMethodsResponse;\n\n /**\n * Configuration for specific payment methods.\n */\n paymentMethodsConfiguration: {\n klarna: {\n useKlarnaWidget: boolean;\n };\n klarna_account: {\n useKlarnaWidget: boolean;\n };\n klarna_paynow: {\n useKlarnaWidget: boolean;\n };\n };\n\n showPayButton?: boolean;\n\n /**\n * If your shoppers use a language that isn't supported by the Components, you can create your own localization.\n * To create a localization:\n * Add a translations object to your payment page, specifying:\n * The localization you want to create.\n * An object containing the fields that are used in the Components, as well as the text you want displayed for each field.\n *\n * \"en\": {\n * \"paymentMethods.moreMethodsButton\": \"More payment methods\",\n * \"payButton\": \"Pay\",\n * \"storeDetails\": \"Save for my next payment\",\n * ...\n * }\n */\n translations?: {\n [index: string]: {\n [index: string]: string;\n };\n };\n\n /*\n * Specify the function that you created, for example, handleOnChange. If you wish\n * to override this function, you can also define an onChange event on the Component\n * level.\n */\n onChange?(state: CardState, component?: AdyenComponent): void;\n\n onAdditionalDetails?(state: CardState, component?: AdyenComponent): void;\n}\n\nexport interface AdyenPlaceholderData {\n holderName?: string;\n prefillCardHolderName?: boolean;\n billingAddress?: {\n street: string;\n houseNumberOrName: string;\n postalCode: string;\n city: string;\n stateOrProvince: string;\n country: string;\n };\n}\n\nexport interface AdyenV3CreditCardComponentOptions\n extends AdyenBaseCardComponentOptions,\n AdyenComponentEvents {\n /**\n * Set an object containing the details array for type: scheme from\n * the /paymentMethods response.\n */\n details?: InputDetail[];\n\n /**\n * Set to true to show the checkbox to save card details for the next payment.\n */\n enableStoreDetails?: boolean;\n\n /**\n * Set to true to request the name of the card holder.\n */\n hasHolderName?: boolean;\n\n /**\n * Set to true to require the card holder name.\n */\n holderNameRequired?: boolean;\n\n /**\n * Information to prefill fields.\n */\n data?: AdyenPlaceholderData;\n\n /**\n * Defaults to ['mc','visa','amex']. Configure supported card types to\n * facilitate brand recognition used in the Secured Fields onBrand callback.\n * See list of available card types. If a shopper enters a card type not\n * specified in the GroupTypes configuration, the onBrand callback will not be invoked.\n */\n groupTypes?: string[];\n\n /**\n * Specify the sample values you want to appear for card detail input fields.\n */\n placeholders?: CreditCardPlaceHolder | SepaPlaceHolder;\n}\n\nexport interface AdyenCustomCardComponentOptions\n extends AdyenBaseCardComponentOptions,\n AdyenComponentEvents {\n /**\n * Specify aria attributes for the input fields for web accessibility.\n */\n ariaLabels?: CustomCardAriaLabels;\n\n /**\n * Automatically shift the focus from date field to the CVC field.\n */\n autofocus?: boolean;\n}\n\nexport interface AdyenError {\n errorCode: string;\n message: string;\n}\n\ntype AdyenClientConstructor = (configuration: AdyenConfiguration) => Promise;\n\nexport interface AdyenHostWindow extends Window {\n AdyenCheckout?: AdyenClientConstructor;\n}\nexport interface AdyenV3IdealComponentOptions {\n /**\n * Optional. Set to **false** to remove the bank logos from the iDEAL form.\n */\n showImage?: boolean;\n}\n\nexport interface AdyenStoredPaymentMethod {\n /**\n * The brand of the card.\n */\n brand?: string;\n\n /**\n * The month the card expires.\n */\n expiryMonth?: string;\n\n /**\n * The year the card expires.\n */\n expiryYear?: string;\n\n /**\n * The unique payment method code.\n */\n holderName?: string;\n\n /**\n * A unique identifier of this stored payment method.\n */\n id?: string;\n\n /**\n * The last four digits of the PAN.\n */\n lastFour?: string;\n\n /**\n * The display name of the stored payment method.\n */\n name: string;\n\n /**\n * The shopper’s email address.\n */\n shopperEmail?: string;\n\n /**\n * The supported shopper interactions for this stored payment method.\n */\n supportedShopperInteractions?: string[];\n\n /**\n * The type of payment method.\n */\n type?: string;\n}\n\nexport interface Bank {\n /**\n * The bank account number (without separators).\n */\n bankAccountNumber?: string;\n\n /**\n * The bank city.\n */\n bankCity?: string;\n\n /**\n * The location id of the bank. The field value is nil in most cases.\n */\n bankLocationId?: string;\n\n /**\n * The name of the bank.\n */\n bankName?: string;\n\n /**\n * The Business Identifier Code (BIC) is the SWIFT address assigned to\n * a bank. The field value is nil in most cases.\n */\n bic?: string;\n\n /**\n * Country code where the bank is located.\n * A valid value is an ISO two-character country code (e.g. 'NL').\n */\n countryCode?: string;\n\n /**\n * The International Bank Account Number (IBAN).\n */\n iban?: string;\n\n /**\n * The name of the bank account holder. If you submit a name with non-Latin\n * characters, we automatically replace some of them with corresponding Latin\n * characters to meet the FATF recommendations. For example:\n * χ12 is converted to ch12.\n * üA is converted to euA.\n * Peter Møller is converted to Peter Mller, because banks don't accept 'ø'.\n * After replacement, the ownerName must have at least three alphanumeric characters\n * (A-Z, a-z, 0-9), and at least one of them must be a valid Latin character\n * (A-Z, a-z). For example:\n * John17 - allowed.\n * J17 - allowed.\n * 171 - not allowed.\n * John-7 - allowed.\n */\n ownerName?: string;\n\n /**\n * The bank account holder's tax ID.\n */\n taxId?: string;\n}\n\nexport interface Card {\n /**\n * The card verification code (1-20 characters). Depending on the card brand, it\n * is known also as:\n * CVv3/CVC2 – length: 3 digits\n * CID – length: 4 digits\n */\n cvc?: string;\n\n /**\n * The card expiry month. Format: 2 digits, zero-padded for single digits. For example:\n * 03 = March\n * 11 = November\n * Required\n */\n expiryMonth: string;\n\n /**\n * The card expiry year. Format: 4 digits. For example: 2020\n * Required\n */\n expiryYear: string;\n\n /**\n * The name of the cardholder, as printed on the card.\n * Required\n */\n holderName: string;\n\n /**\n * The issue number of the card (for some UK debit cards only).\n */\n issueNumber?: string;\n\n /**\n * The card number (4-19 characters). Do not use any separators. When this value is\n * returned in a response, only the last 4 digits of the card number are returned.\n * Required\n */\n number: string;\n\n /**\n * The month component of the start date (for some UK debit cards only).\n */\n startNumber?: string;\n\n /**\n * The year component of the start date (for some UK debit cards only).\n */\n startYear?: string;\n}\n\nexport interface CardState {\n data: CardDataPaymentMethodState;\n isValid?: boolean;\n valid?: { [key: string]: boolean };\n errors?: CardStateErrors;\n}\n\ninterface CardDataPaymentMethodState {\n paymentMethod: CardPaymentMethodState;\n}\n\nexport interface CardStateErrors {\n [key: string]: string;\n}\n\nexport interface WechatState {\n data: WechatDataPaymentMethodState;\n}\n\nexport interface CreditCardPlaceHolder {\n encryptedCardNumber?: string;\n encryptedExpiryDate?: string;\n encryptedSecurityCode: string;\n}\n\ninterface AccountDataPaymentMethodState {\n paymentMethod: AdyenPaymentMethodState;\n}\n\nexport interface AccountState {\n data: AccountDataPaymentMethodState;\n}\n\nexport interface CssProperties {\n background?: string;\n caretColor?: string;\n color?: string;\n display?: string;\n font?: string;\n fontFamily?: string;\n fontSize?: string;\n fontSizeAdjust?: string;\n fontSmoothing?: string;\n fontStretch?: string;\n fontStyle?: string;\n fontVariant?: string;\n fontVariantAlternates?: string;\n fontVariantCaps?: string;\n fontVariantEastAsian?: string;\n fontVariantLigatures?: string;\n fontVariantNumeric?: string;\n fontWeight?: string;\n letterSpacing?: string;\n lineHeight?: string;\n mozOsxFontSmoothing?: string;\n mozTransition?: string;\n outline?: string;\n opacity?: string | number;\n padding?: string;\n textAlign?: string;\n textShadow?: string;\n transition?: string;\n webkitFontSmoothing?: string;\n webkitTransition?: string;\n}\n\nexport interface CustomCardAriaLabel {\n label?: string;\n iframeTitle?: string;\n}\n\nexport interface CustomCardAriaLabels {\n lang?: string;\n encryptedCardNumber?: CustomCardAriaLabel;\n encryptedExpiryDate?: CustomCardAriaLabel;\n encryptedSecurityCode?: CustomCardAriaLabel;\n}\n\nexport interface Group {\n /**\n * The name of the group.\n */\n name?: string;\n\n /**\n * Echo data to be used if the payment method is displayed as part of this group.\n */\n paymentMethodData?: string;\n\n /**\n * The unique code of the group.\n */\n type?: string;\n}\n\nexport interface InputDetail {\n /**\n * Configuration parameters for the required input.\n */\n configuration?: object;\n\n /**\n * Input details can also be provided recursively.\n */\n details?: SubInputDetail[];\n\n /**\n * In case of a select, the URL from which to query the items.\n */\n itemSearchUrl?: string;\n\n /**\n * In case of a select, the items to choose from.\n */\n items?: Item[];\n\n /**\n * The value to provide in the result.\n */\n key?: string;\n\n /**\n * True if this input value is optional.\n */\n optional?: boolean;\n\n /**\n * The type of the required input.\n */\n type?: string;\n\n /**\n * The value can be pre-filled, if available.\n */\n value?: string;\n}\n\nexport interface Item {\n /**\n * The value to provide in the result.\n */\n id?: string;\n\n /**\n * The display name.\n */\n name?: string;\n}\n\nexport interface PaymentMethod {\n /**\n * List of possible brands. For example: visa, mc.\n */\n brands?: string[];\n\n /**\n * The configuration of the payment method.\n */\n configuration?: object;\n\n /**\n * All input details to be provided to complete the payment with this payment\n * method.\n */\n details?: InputDetail[];\n\n /**\n * The group where this payment method belongs to.\n */\n group?: Group;\n\n /**\n * The displayable name of this payment method.\n */\n name?: string;\n\n /**\n * Echo data required to send in next calls.\n */\n paymentMethodData?: string;\n\n /**\n * Indicates whether this payment method supports tokenization or not.\n */\n supportsRecurring?: boolean;\n\n /**\n * The unique payment method code.\n */\n type?: string;\n}\n\nexport interface PaymentMethodGroup {\n /**\n * The type to submit for any payment method in this group.\n */\n groupType?: string;\n\n /**\n * The human-readable name of this group.\n */\n name?: string;\n\n /**\n * The types of payment methods that belong in this group.\n */\n types?: string[];\n}\n\nexport interface PaymentMethodsResponse {\n /**\n * Groups of payment methods.\n */\n groups?: PaymentMethodGroup[];\n\n /**\n * Detailed list of one-click payment methods.\n */\n oneClickPaymentMethods?: RecurringDetail;\n\n /**\n * Detailed list of payment methods required to generate payment forms.\n */\n paymentMethods?: PaymentMethod[];\n\n /**\n * List of all stored payment methods.\n */\n storedPaymentMethods?: AdyenStoredPaymentMethod[];\n}\n\nexport interface RecurringDetail extends PaymentMethod {\n /**\n * The reference that uniquely identifies the recurring detail.\n */\n recurringDetailReference?: string;\n\n /**\n * Contains information on previously stored payment details.\n */\n storedDetails?: StoredDetails;\n}\n\nexport interface SepaPlaceHolder {\n ownerName?: string;\n ibanNumber?: string;\n}\n\nexport interface StoredDetails {\n /**\n * The stored bank account.\n */\n bank?: Bank;\n\n /**\n * The stored card information.\n */\n card?: Card;\n\n /**\n * The email associated with stored payment details.\n */\n emailAddress?: string;\n}\n\nexport interface StyleOptions {\n /**\n * Base styling applied to the iframe. All styling extends from this style.\n */\n base?: CssProperties;\n\n /**\n * Styling applied when a field fails validation.\n */\n error?: CssProperties;\n\n /**\n * Styling applied to the field's placeholder values.\n */\n placeholder?: CssProperties;\n\n /**\n * Styling applied once a field passes validation.\n */\n validated?: CssProperties;\n}\n\nexport interface SubInputDetail {\n /**\n * Configuration parameters for the required input.\n */\n configuration?: object;\n\n /**\n * In case of a select, the items to choose from.\n */\n items?: Item[];\n\n /**\n * The value to provide in the result.\n */\n key?: string;\n\n /**\n * True if this input is optional to provide.\n */\n optional?: boolean;\n\n /**\n * The type of the required input.\n */\n type?: string;\n\n /**\n * The value can be pre-filled, if available.\n */\n value?: string;\n}\n\nexport interface ThreeDS2ChallengeComponentOptions {\n challengeWindowSize?: string;\n onAdditionalDetails?(state: AdyenAdditionalActionState, component?: AdyenComponent): void;\n onError(error: AdyenError): void;\n}\n\nexport interface ThreeDS2DeviceFingerprintComponentOptions {\n onAdditionalDetails?(state: AdyenAdditionalActionState, component?: AdyenComponent): void;\n onError(error: AdyenError): void;\n}\n\nexport interface AdyenV3ValidationState {\n valid: boolean;\n fieldType?: AdyenV3CardFields;\n endDigits?: string;\n encryptedFieldName?: string;\n i18n?: string;\n error?: string;\n errorKey?: string;\n}\n\nexport enum AdyenV3CardFields {\n CardNumber = 'encryptedCardNumber',\n SecurityCode = 'encryptedSecurityCode',\n ExpiryDate = 'encryptedExpiryDate',\n}\n\nexport type AdyenV3ComponentState = CardState | WechatState;\n\nexport type AdyenComponentOptions =\n | AdyenV3CreditCardComponentOptions\n | AdyenV3IdealComponentOptions\n | AdyenCustomCardComponentOptions;\n\nexport function isCardState(param: unknown): param is CardState {\n return (\n (typeof param === 'object' &&\n !!param &&\n typeof (param as CardState).data.paymentMethod.encryptedSecurityCode === 'string') ||\n typeof (param as CardState).data.paymentMethod.encryptedExpiryMonth === 'string'\n );\n}\n\nexport interface AdyenPaymentMethodInitializationData {\n clientKey?: string;\n environment?: string;\n paymentMethodsResponse?: PaymentMethodsResponse;\n prefillCardHolderName?: boolean;\n}\n","import { some } from 'lodash';\n\nimport {\n BillingAddress,\n getBrowserInfo,\n InvalidArgumentError,\n isHostedInstrumentLike,\n isRequestError,\n isVaultedInstrument,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n PaymentMethod,\n PaymentMethodCancelledError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n AdyenAction,\n AdyenActionType,\n AdyenAdditionalAction,\n AdyenAdditionalActionState,\n AdyenClient,\n AdyenComponent,\n AdyenComponentType,\n AdyenError,\n AdyenPaymentMethodInitializationData,\n AdyenPaymentMethodType,\n AdyenPlaceholderData,\n AdyenV3ComponentState,\n CardStateErrors,\n isCardState,\n} from './adyenv3';\nimport AdyenV3PaymentInitializeOptions, {\n WithAdyenV3PaymentInitializeOptions,\n} from './adyenv3-initialize-options';\nimport AdyenV3ScriptLoader from './adyenv3-script-loader';\n\nexport default class Adyenv3PaymentStrategy implements PaymentStrategy {\n private _adyenClient?: AdyenClient;\n private _cardVerificationComponent?: AdyenComponent;\n private _componentState?: AdyenV3ComponentState;\n private _paymentComponent?: AdyenComponent;\n private _paymentInitializeOptions?: AdyenV3PaymentInitializeOptions;\n\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _scriptLoader: AdyenV3ScriptLoader,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithAdyenV3PaymentInitializeOptions,\n ): Promise {\n const { adyenv3 } = options;\n\n if (!adyenv3) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.adyenv3\" argument is not provided.',\n );\n }\n\n this._paymentInitializeOptions = adyenv3;\n\n const paymentMethod = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(options.methodId);\n const { environment, clientKey, paymentMethodsResponse } =\n paymentMethod.initializationData || {};\n\n this._adyenClient = await this._scriptLoader.load({\n paymentMethodsConfiguration: {\n klarna: {\n useKlarnaWidget: true,\n },\n klarna_account: {\n useKlarnaWidget: true,\n },\n klarna_paynow: {\n useKlarnaWidget: true,\n },\n },\n environment,\n locale: this._paymentIntegrationService.getState().getLocale(),\n clientKey,\n paymentMethodsResponse,\n showPayButton: false,\n translations: {\n es: { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-AR': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-ES': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-MX': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-CL': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-CO': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-PE': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n },\n });\n\n this._paymentComponent = await this._mountPaymentComponent(paymentMethod);\n\n if (\n paymentMethod.method === AdyenPaymentMethodType.CreditCard ||\n paymentMethod.method === AdyenPaymentMethodType.Bancontact\n ) {\n this._cardVerificationComponent = await this._mountCardVerificationComponent();\n }\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const paymentData = payment.paymentData;\n\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = isHostedInstrumentLike(\n paymentData,\n )\n ? paymentData\n : { shouldSaveInstrument: false, shouldSetAsDefaultInstrument: false };\n\n this._validateCardData();\n\n const componentState = this._componentState || {\n data: { paymentMethod: { type: payment.methodId } },\n };\n\n if (\n payment.methodId === 'klarna' ||\n payment.methodId === 'klarna_account' ||\n payment.methodId === 'klarna_paynow'\n ) {\n this._paymentComponent?.submit();\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n if (paymentData && isVaultedInstrument(paymentData)) {\n let bigpayToken = {};\n\n if (isCardState(componentState)) {\n const {\n encryptedCardNumber,\n encryptedSecurityCode,\n encryptedExpiryMonth,\n encryptedExpiryYear,\n } = componentState.data.paymentMethod;\n\n bigpayToken = {\n credit_card_number_confirmation: encryptedCardNumber,\n expiry_month: encryptedExpiryMonth,\n expiry_year: encryptedExpiryYear,\n verification_value: encryptedSecurityCode,\n };\n }\n\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n formattedPayload: {\n bigpay_token: {\n ...bigpayToken,\n token: paymentData.instrumentId,\n },\n origin: window.location.origin,\n browser_info: getBrowserInfo(),\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n },\n },\n });\n\n return;\n } catch (error) {\n await this._processAdditionalAction(\n error,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n\n return;\n }\n }\n\n try {\n await this._paymentIntegrationService.submitPayment({\n methodId: payment.methodId,\n paymentData: {\n formattedPayload: {\n credit_card_token: {\n token: JSON.stringify({\n ...componentState.data.paymentMethod,\n type: payment.methodId,\n origin: window.location.origin,\n }),\n },\n browser_info: getBrowserInfo(),\n vault_payment_instrument: shouldSaveInstrument || null,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n },\n },\n });\n } catch (error) {\n await this._processAdditionalAction(\n error,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this._componentState = undefined;\n\n if (this._paymentComponent) {\n this._paymentComponent.unmount();\n this._paymentComponent = undefined;\n }\n\n if (this._cardVerificationComponent) {\n this._cardVerificationComponent.unmount();\n this._cardVerificationComponent = undefined;\n }\n\n return Promise.resolve();\n }\n\n private _updateComponentState(componentState: AdyenV3ComponentState) {\n this._componentState = componentState;\n }\n\n private _getAdyenClient(): AdyenClient {\n if (!this._adyenClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._adyenClient;\n }\n\n private _getPaymentInitializeOptions(): AdyenV3PaymentInitializeOptions {\n if (!this._paymentInitializeOptions) {\n throw new InvalidArgumentError(\n '\"options.adyenv3\" argument was not provided during initialization.',\n );\n }\n\n return this._paymentInitializeOptions;\n }\n\n private _handleAction(additionalAction: AdyenAdditionalAction): Promise {\n return new Promise((resolve, reject) => {\n const { additionalActionOptions } = this._getPaymentInitializeOptions();\n const { onBeforeLoad, containerId, onLoad, onComplete, widgetSize } =\n additionalActionOptions;\n const adyenAction: AdyenAction = JSON.parse(additionalAction.action);\n\n const additionalActionComponent = this._getAdyenClient().createFromAction(adyenAction, {\n onAdditionalDetails: (additionalActionState: AdyenAdditionalActionState) => {\n const paymentPayload = {\n methodId: adyenAction.paymentMethodType,\n paymentData: {\n nonce: JSON.stringify(additionalActionState.data),\n },\n };\n\n if (onComplete) {\n onComplete();\n }\n\n resolve(paymentPayload);\n },\n challengeWindowSize: widgetSize || '05',\n onError: (error: AdyenError) => reject(error),\n });\n\n if (onBeforeLoad) {\n onBeforeLoad(\n adyenAction.type === AdyenActionType.ThreeDS2 ||\n adyenAction.type === AdyenActionType.QRCode ||\n adyenAction.type === AdyenActionType.Sdk,\n );\n }\n\n additionalActionComponent.mount(`#${containerId}`);\n\n if (onLoad) {\n onLoad(() => {\n reject(new PaymentMethodCancelledError());\n additionalActionComponent.unmount();\n });\n }\n });\n }\n\n private _mapAdyenPlaceholderData(\n billingAddress?: BillingAddress,\n prefillCardHolderName?: boolean,\n ): AdyenPlaceholderData {\n if (!billingAddress) {\n return {};\n }\n\n const {\n firstName,\n lastName,\n address1: street,\n address2: houseNumberOrName,\n postalCode,\n city,\n stateOrProvinceCode: stateOrProvince,\n countryCode: country,\n } = billingAddress;\n\n return {\n holderName: prefillCardHolderName ? `${firstName} ${lastName}` : '',\n billingAddress: {\n street,\n houseNumberOrName,\n postalCode,\n city,\n stateOrProvince,\n country,\n },\n };\n }\n\n private _mountCardVerificationComponent(): Promise {\n const adyenv3 = this._getPaymentInitializeOptions();\n const adyenClient = this._getAdyenClient();\n let cardVerificationComponent: AdyenComponent;\n\n return new Promise((resolve, reject) => {\n if (adyenv3.cardVerificationContainerId) {\n cardVerificationComponent = adyenClient.create(AdyenComponentType.SecuredFields, {\n ...adyenv3.options,\n styles: {\n ...adyenv3.options?.styles,\n placeholder: {\n color: 'transparent',\n caretColor: '#000',\n ...adyenv3.options?.styles?.placeholder,\n },\n },\n onChange: (componentState) => this._updateComponentState(componentState),\n onError: (validateState) => adyenv3.validateCardFields(validateState),\n onFieldValid: (validateState) => adyenv3.validateCardFields(validateState),\n });\n\n try {\n cardVerificationComponent.mount(`#${adyenv3.cardVerificationContainerId}`);\n } catch (error) {\n reject(new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized));\n }\n }\n\n resolve(cardVerificationComponent);\n });\n }\n\n private _mountPaymentComponent(paymentMethod: PaymentMethod): Promise {\n let paymentComponent: AdyenComponent;\n const adyenv3 = this._getPaymentInitializeOptions();\n const adyenClient = this._getAdyenClient();\n\n return new Promise((resolve, reject) => {\n const billingAddress = this._paymentIntegrationService.getState().getBillingAddress();\n\n const { prefillCardHolderName } = paymentMethod.initializationData;\n\n paymentComponent = adyenClient.create(paymentMethod.method, {\n ...adyenv3.options,\n showBrandsUnderCardNumber: false,\n onChange: (componentState) => this._updateComponentState(componentState),\n onSubmit: (componentState) => this._updateComponentState(componentState),\n ...(billingAddress\n ? { data: this._mapAdyenPlaceholderData(billingAddress, prefillCardHolderName) }\n : {}),\n });\n\n try {\n paymentComponent.mount(`#${adyenv3.containerId}`);\n } catch (error) {\n reject(new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized));\n }\n\n resolve(paymentComponent);\n });\n }\n\n private async _processAdditionalAction(\n error: unknown,\n shouldSaveInstrument?: boolean,\n shouldSetAsDefaultInstrument?: boolean,\n ): Promise {\n if (\n !isRequestError(error) ||\n !some(error.body.errors, { code: 'additional_action_required' })\n ) {\n throw error;\n }\n\n const payment = await this._handleAction(error.body.provider_data);\n\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n ...payment.paymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n },\n });\n } catch (paymentError) {\n return this._processAdditionalAction(\n paymentError,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n private _validateCardData(): void {\n const adyenv3 = this._getPaymentInitializeOptions();\n const cardComponent = adyenv3.hasVaultedInstruments\n ? this._cardVerificationComponent\n : this._paymentComponent;\n\n if (!cardComponent?.componentRef?.showValidation || !cardComponent.state) {\n return;\n }\n\n cardComponent.componentRef.showValidation();\n\n if (Object.keys(cardComponent.state).length === 0 || !cardComponent.state.isValid) {\n throw new PaymentInvalidFormError(this._mapCardErrors(cardComponent.state.errors));\n }\n }\n\n private _mapCardErrors(cardStateErrors: CardStateErrors = {}): PaymentInvalidFormErrorDetails {\n const errors: PaymentInvalidFormErrorDetails = {};\n\n Object.keys(cardStateErrors).forEach((key) => {\n errors[key] = [\n {\n message: cardStateErrors[key],\n type: key,\n },\n ];\n });\n\n return errors;\n }\n}\n","import { ScriptLoader, StylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { AdyenClient, AdyenConfiguration, AdyenHostWindow } from './adyenv3';\n\nexport default class AdyenV3ScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _stylesheetLoader: StylesheetLoader,\n private _window: AdyenHostWindow = window,\n ) {}\n\n async load(configuration: AdyenConfiguration): Promise {\n await Promise.all([\n this._stylesheetLoader.loadStylesheet(\n `https://checkoutshopper-${\n configuration.environment ?? ''\n }.adyen.com/checkoutshopper/sdk/5.24.0/adyen.css`,\n ),\n this._scriptLoader.loadScript(\n `https://checkoutshopper-${\n configuration.environment ?? ''\n }.adyen.com/checkoutshopper/sdk/5.24.0/adyen.js`,\n ),\n ]);\n\n if (!this._window.AdyenCheckout) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n const checkout = await this._window.AdyenCheckout(configuration);\n\n return checkout;\n }\n}\n","import { getScriptLoader, getStylesheetLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport AdyenV3PaymentStrategy from './adyenv3-payment-strategy';\nimport AdyenV3ScriptLoader from './adyenv3-script-loader';\n\nconst createAdyenV3PaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new AdyenV3PaymentStrategy(\n paymentIntegrationService,\n new AdyenV3ScriptLoader(getScriptLoader(), getStylesheetLoader()),\n );\n};\n\nexport default toResolvableModule(createAdyenV3PaymentStrategy, [{ gateway: 'adyenv3' }]);\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport {\n Cart,\n Checkout,\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n PaymentRequestOptions,\n PaymentStrategy,\n StoreConfig,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithApplePayPaymentInitializeOptions } from './apple-pay-payment-initialize-options';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst validationEndpoint = (bigPayEndpoint: string) =>\n `${bigPayEndpoint}/api/public/v1/payments/applepay/validate_merchant`;\n\ninterface ApplePayPromise {\n resolve(): void;\n reject(reason?: Error): void;\n}\n\nenum DefaultLabels {\n Shipping = 'Shipping',\n Subtotal = 'Subtotal',\n}\n\nexport default class ApplePayPaymentStrategy implements PaymentStrategy {\n private _shippingLabel: string = DefaultLabels.Shipping;\n private _subTotalLabel: string = DefaultLabels.Subtotal;\n\n constructor(\n private _requestSender: RequestSender,\n private _paymentIntegrationService: PaymentIntegrationService,\n private _sessionFactory: ApplePaySessionFactory,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithApplePayPaymentInitializeOptions,\n ): Promise {\n if (!options?.methodId) {\n throw new InvalidArgumentError(\n 'Unable to submit payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n const { methodId } = options;\n\n this._shippingLabel = options.applepay?.shippingLabel || DefaultLabels.Shipping;\n this._subTotalLabel = options.applepay?.subtotalLabel || DefaultLabels.Subtotal;\n await this._paymentIntegrationService.loadPaymentMethod(methodId);\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment } = payload;\n const state = this._paymentIntegrationService.getState();\n const checkout = state.getCheckoutOrThrow();\n const cart = state.getCartOrThrow();\n const config = state.getStoreConfigOrThrow();\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId } = payment;\n\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n const request = this._getBaseRequest(cart, checkout, config, paymentMethod);\n const applePaySession = this._sessionFactory.create(request);\n\n await this._paymentIntegrationService.submitOrder(\n {\n useStoreCredit: payload.useStoreCredit,\n },\n options,\n );\n\n applePaySession.begin();\n\n return new Promise((resolve, reject) => {\n this._handleApplePayEvents(applePaySession, paymentMethod, {\n resolve,\n reject,\n });\n });\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private _getBaseRequest(\n cart: Cart,\n checkout: Checkout,\n config: StoreConfig,\n paymentMethod: PaymentMethod,\n ): ApplePayJS.ApplePayPaymentRequest {\n const {\n storeProfile: { storeCountryCode, storeName },\n } = config;\n const {\n currency: { decimalPlaces },\n } = cart;\n const {\n initializationData: { merchantCapabilities, supportedNetworks },\n } = paymentMethod;\n const lineItems: ApplePayJS.ApplePayLineItem[] = [\n {\n label: this._subTotalLabel,\n amount: `${checkout.subtotal.toFixed(decimalPlaces)}`,\n },\n ];\n\n checkout.taxes.forEach((tax) =>\n lineItems.push({\n label: tax.name,\n amount: `${tax.amount.toFixed()}`,\n }),\n );\n\n lineItems.push({\n label: this._shippingLabel,\n amount: `${checkout.shippingCostTotal.toFixed(decimalPlaces)}`,\n });\n\n return {\n countryCode: storeCountryCode,\n currencyCode: cart.currency.code,\n merchantCapabilities,\n supportedNetworks,\n lineItems,\n total: {\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(cart.currency.decimalPlaces)}`,\n type: 'final',\n },\n };\n }\n\n private _handleApplePayEvents(\n applePaySession: ApplePaySession,\n paymentMethod: PaymentMethod,\n promise: ApplePayPromise,\n ) {\n applePaySession.onvalidatemerchant = async (event) => {\n try {\n const { body: merchantSession } = await this._onValidateMerchant(\n paymentMethod,\n event,\n );\n\n applePaySession.completeMerchantValidation(merchantSession);\n } catch (err) {\n throw new Error('Merchant validation failed');\n }\n };\n\n applePaySession.oncancel = async () =>\n promise.reject(new PaymentMethodCancelledError('Continue with applepay'));\n\n applePaySession.onpaymentauthorized = (event: ApplePayJS.ApplePayPaymentAuthorizedEvent) =>\n this._onPaymentAuthorized(event, applePaySession, paymentMethod, promise);\n }\n\n private async _onValidateMerchant(\n paymentData: PaymentMethod,\n event: ApplePayJS.ApplePayValidateMerchantEvent,\n ) {\n const body = [\n `validationUrl=${event.validationURL}`,\n `merchantIdentifier=${paymentData.initializationData.merchantId}`,\n `displayName=${paymentData.initializationData.storeName}`,\n `domainName=${window.location.hostname}`,\n ].join('&');\n\n return this._requestSender.post(\n validationEndpoint(paymentData.initializationData.paymentsUrl),\n {\n credentials: false,\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'X-XSRF-TOKEN': null,\n },\n body,\n },\n );\n }\n\n private async _onPaymentAuthorized(\n event: ApplePayJS.ApplePayPaymentAuthorizedEvent,\n applePaySession: ApplePaySession,\n paymentMethod: PaymentMethod,\n promise: ApplePayPromise,\n ) {\n const { token } = event.payment;\n const payment: Payment = {\n methodId: paymentMethod.id,\n paymentData: {\n formattedPayload: {\n apple_pay_token: {\n payment_data: token.paymentData,\n payment_method: token.paymentMethod,\n transaction_id: token.transactionIdentifier,\n },\n },\n },\n };\n\n try {\n await this._paymentIntegrationService.submitPayment(payment);\n applePaySession.completePayment(ApplePaySession.STATUS_SUCCESS);\n\n return promise.resolve();\n } catch (error) {\n applePaySession.completePayment(ApplePaySession.STATUS_FAILURE);\n\n return promise.reject(\n new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ApplePayPaymentStrategy from './apple-pay-payment-strategy';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst createApplePayPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new ApplePayPaymentStrategy(\n createRequestSender({ host: getHost() }),\n paymentIntegrationService,\n new ApplePaySessionFactory(),\n );\n};\n\nexport default toResolvableModule(createApplePayPaymentStrategy, [{ id: 'applepay' }]);\n","export default function guard(value: T, errorFactory?: () => Error): NonNullable {\n if (value === undefined || value === null) {\n throw errorFactory ? errorFactory() : new Error('An unexpected error has occurred.');\n }\n\n return value as NonNullable;\n}\n","// copied from packages/core/src/hosted-form/hosted-field-type.ts\n\nenum HostedFieldType {\n CardCode = 'cardCode',\n CardCodeVerification = 'cardCodeVerification',\n CardExpiry = 'cardExpiry',\n CardName = 'cardName',\n CardNumber = 'cardNumber',\n CardNumberVerification = 'cardNumberVerification',\n}\n\nexport default HostedFieldType;\n","import {\n HostedCardFieldOptionsMap,\n HostedFieldOptionsMap,\n HostedFieldType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isHostedCardFieldOptionsMap(\n fields: HostedFieldOptionsMap,\n): fields is HostedCardFieldOptionsMap {\n return HostedFieldType.CardNumber in fields;\n}\n","import {\n HostedFieldOptionsMap,\n HostedFieldType,\n HostedStoredCardFieldOptionsMap,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isHostedStoredCardFieldOptionsMap(\n fields: HostedFieldOptionsMap,\n): fields is HostedStoredCardFieldOptionsMap {\n return (\n HostedFieldType.CardCodeVerification in fields ||\n HostedFieldType.CardNumberVerification in fields\n );\n}\n","import { WithCreditCardPaymentInitializeOptions } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n guard,\n InvalidArgumentError,\n isHostedInstrumentLike,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BlueSnapDirectHostedForm from './bluesnap-direct-hosted-form';\nimport isHostedCardFieldOptionsMap from './is-hosted-card-field-options-map';\nimport isHostedStoredCardFieldOptionsMap from './is-hosted-stored-card-field-options-map';\nimport { BlueSnapDirectThreeDSecureData } from './types';\n\nexport default class BlueSnapDirectCreditCardPaymentStrategy implements PaymentStrategy {\n private _paymentFieldsToken?: string;\n private _shouldUseHostedFields?: boolean;\n\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _blueSnapDirectHostedForm: BlueSnapDirectHostedForm,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithCreditCardPaymentInitializeOptions,\n ): Promise {\n const { methodId, gatewayId, creditCard } = options;\n\n if (!gatewayId || !creditCard) {\n throw new InvalidArgumentError();\n }\n\n const state = await this._paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n\n const {\n config: { testMode, is3dsEnabled },\n clientToken,\n } = state.getPaymentMethodOrThrow(methodId, gatewayId);\n\n this._paymentFieldsToken = clientToken;\n this._shouldUseHostedFields =\n isHostedCardFieldOptionsMap(creditCard.form.fields) ||\n (isHostedStoredCardFieldOptionsMap(creditCard.form.fields) &&\n (!!creditCard.form.fields.cardNumberVerification ||\n !!creditCard.form.fields.cardCodeVerification));\n\n if (this._shouldUseHostedFields) {\n await this._blueSnapDirectHostedForm.initialize(testMode, creditCard.form.fields);\n await this._blueSnapDirectHostedForm.attach(\n this._getPaymentFieldsToken(),\n creditCard,\n is3dsEnabled,\n );\n }\n }\n\n async execute(payload: OrderRequestBody): Promise {\n if (!payload.payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { paymentData } = payload.payment;\n\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = isHostedInstrumentLike(\n paymentData,\n )\n ? paymentData\n : { shouldSaveInstrument: false, shouldSetAsDefaultInstrument: false };\n\n const pfToken = this._getPaymentFieldsToken();\n\n const { is3dsEnabled } = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(payload.payment.methodId, payload.payment.gatewayId).config;\n\n const bluesnapSubmitedForm = this._shouldUseHostedFields\n ? await this._blueSnapDirectHostedForm\n .validate()\n .submit(\n is3dsEnabled ? this._getBlueSnapDirectThreeDSecureData() : undefined,\n !(isHostedInstrumentLike(paymentData) && isVaultedInstrument(paymentData)),\n )\n : undefined;\n\n await this._paymentIntegrationService.submitOrder();\n\n if (\n isHostedInstrumentLike(paymentData) &&\n isVaultedInstrument(paymentData) &&\n paymentData.instrumentId\n ) {\n await this._paymentIntegrationService.submitPayment({\n ...payload.payment,\n paymentData: {\n instrumentId: paymentData.instrumentId,\n ...(this._shouldUseHostedFields ? { nonce: pfToken } : {}),\n shouldSetAsDefaultInstrument: !!shouldSetAsDefaultInstrument,\n },\n });\n\n return;\n }\n\n await this._paymentIntegrationService.submitPayment({\n ...payload.payment,\n paymentData: {\n formattedPayload: {\n credit_card_token: {\n token: JSON.stringify({\n pfToken,\n cardHolderName:\n bluesnapSubmitedForm && bluesnapSubmitedForm.cardHolderName,\n }),\n },\n vault_payment_instrument: shouldSaveInstrument,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n },\n },\n });\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n if (this._shouldUseHostedFields) {\n this._blueSnapDirectHostedForm.detach();\n }\n\n return Promise.resolve();\n }\n\n private _getBlueSnapDirectThreeDSecureData(): BlueSnapDirectThreeDSecureData {\n const {\n getBillingAddress,\n getShippingAddress,\n getCustomer,\n getCheckoutOrThrow,\n getCartOrThrow,\n } = this._paymentIntegrationService.getState();\n const billingAddress = getBillingAddress();\n const shippingAddress = getShippingAddress();\n const email = getCustomer()?.email || billingAddress?.email;\n const phone = billingAddress?.phone || shippingAddress?.phone;\n\n return {\n amount: getCheckoutOrThrow().outstandingBalance,\n currency: getCartOrThrow().currency.code,\n ...(email && { email }),\n ...(phone && { phone }),\n ...(billingAddress && {\n billingFirstName: billingAddress.firstName,\n billingLastName: billingAddress.lastName,\n billingCountry: billingAddress.countryCode,\n billingState: billingAddress.stateOrProvinceCode,\n billingCity: billingAddress.city,\n billingAddress: `${billingAddress.address1} ${billingAddress.address2}`.trim(),\n billingZip: billingAddress.postalCode,\n }),\n ...(shippingAddress && {\n shippingFirstName: shippingAddress.firstName,\n shippingLastName: shippingAddress.lastName,\n shippingCountry: shippingAddress.countryCode,\n shippingState: shippingAddress.stateOrProvinceCode,\n shippingCity: shippingAddress.city,\n shippingAddress: `${shippingAddress.address1} ${shippingAddress.address2}`.trim(),\n shippingZip: shippingAddress.postalCode,\n }),\n };\n }\n\n private _getPaymentFieldsToken(): string {\n return guard(\n this._paymentFieldsToken,\n () => new MissingDataError(MissingDataErrorType.MissingPaymentToken),\n );\n }\n}\n","export type BluesnapDirectNocInputAllowedStyle = Pick<\n CSSStyleDeclaration,\n 'color' | 'fontFamily' | 'fontSize' | 'fontWeight'\n>;\n\nexport interface BlueSnapDirectStyleDeclaration {\n [k: string]: string;\n}\n\nexport interface BlueSnapDirectStyle {\n '.invalid'?: BlueSnapDirectStyleDeclaration;\n ':focus'?: BlueSnapDirectStyleDeclaration;\n input?: BlueSnapDirectStyleDeclaration;\n}\n\nexport enum BlueSnapDirectCardType {\n AMEX = 'american-express',\n CHINA_UNION_PAY = 'unionpay',\n DINERS = 'diners-club',\n DISCOVER = 'discover',\n JCB = 'jcb',\n MASTERCARD = 'mastercard',\n UNKNOWN = 'unknown',\n VISA = 'visa',\n}\n\nexport type BlueSnapDirectCardTypeValues = keyof typeof BlueSnapDirectCardType;\n\nexport enum BlueSnapDirectEventOrigin {\n ON_BLUR = 'onBlur',\n ON_SUBMIT = 'onSubmit',\n}\n\nexport enum BlueSnapDirectErrorDescription {\n EMPTY = 'empty',\n INVALID = 'invalid',\n THREE_DS_NOT_ENABLED = '3D Secure is not enabled',\n}\n\nexport type BlueSnapDirectInputValidationErrorDescription = Extract<\n BlueSnapDirectErrorDescription,\n BlueSnapDirectErrorDescription.EMPTY | BlueSnapDirectErrorDescription.INVALID\n>;\n\nexport enum BlueSnapDirectErrorCode {\n CC_NOT_SUPORTED = '22013',\n ERROR_403 = '403',\n ERROR_404 = '404',\n ERROR_500 = '500',\n INVALID_OR_EMPTY = '10',\n SESSION_EXPIRED = '400',\n THREE_DS_AUTH_FAILED = '14101',\n THREE_DS_CLIENT_ERROR = '14103',\n THREE_DS_MISSING_FIELDS = '14102',\n THREE_DS_NOT_ENABLED = '14100',\n TOKEN_EXPIRED = '14040',\n TOKEN_NOT_ASSOCIATED = '14042',\n TOKEN_NOT_FOUND = '14041',\n}\n\nexport enum BlueSnapDirectHostedFieldTagId {\n CardCode = 'cvv',\n CardExpiry = 'exp',\n CardName = 'noc',\n CardNumber = 'ccn',\n}\n\nexport interface BlueSnapDirectHostedPaymentFieldsOptions {\n token: string;\n onFieldEventHandler?: {\n setupComplete?: () => void;\n threeDsChallengeExecuted?: () => void;\n onFocus?: (tagId: BlueSnapDirectHostedFieldTagId) => void;\n onBlur?: (tagId: BlueSnapDirectHostedFieldTagId) => void;\n onError?: (\n tagId: BlueSnapDirectHostedFieldTagId | undefined,\n errorCode: BlueSnapDirectErrorCode,\n errorDescription: BlueSnapDirectErrorDescription | undefined,\n eventOrigin: BlueSnapDirectEventOrigin | undefined,\n ) => void;\n onType?: (\n tagId: BlueSnapDirectHostedFieldTagId,\n cardType: BlueSnapDirectCardTypeValues,\n cardData: BlueSnapDirectCardData | undefined,\n ) => void;\n onEnter?: (tagId: BlueSnapDirectHostedFieldTagId) => void;\n onValid?: (tagId: BlueSnapDirectHostedFieldTagId) => void;\n };\n ccnPlaceHolder?: string;\n cvvPlaceHolder?: string;\n expPlaceHolder?: string;\n style?: BlueSnapDirectStyle;\n '3DS'?: boolean;\n}\n\ninterface BlueSnapDirectCallback {\n statusCode: string;\n transactionFraudInfo: {\n fraudSessionId: string;\n };\n}\n\ninterface BlueSnapDirectCardData {\n binCategory: string;\n cardSubType: string;\n ccBin: string;\n ccType: string;\n isRegulatedCard: string;\n issuingCountry: string;\n last4Digits: string;\n}\n\nexport interface BlueSnapDirectCallbackCardData extends BlueSnapDirectCardData {\n cardCategory: string;\n exp: string;\n}\n\ninterface BlueSnapDirectCallbackData extends BlueSnapDirectCallback {\n cardData: BlueSnapDirectCallbackCardData;\n}\n\nexport interface WithBlueSnapDirectCardHolderName {\n cardHolderName?: string;\n}\n\ninterface BlueSnapDirectSubmitError {\n errorCode: string;\n errorDescription: string;\n eventType: string;\n tagId: string;\n}\n\nexport interface BlueSnapDirectCallbackError extends BlueSnapDirectCallback {\n error: BlueSnapDirectSubmitError[];\n}\n\nexport type BlueSnapDirectCallbackResults =\n | BlueSnapDirectCallbackData\n | BlueSnapDirectCallbackError;\n\nexport interface BlueSnapDirectThreeDSecureData {\n amount: number;\n currency: string;\n billingFirstName?: string;\n billingLastName?: string;\n billingCountry?: string;\n billingState?: string;\n billingCity?: string;\n billingAddress?: string;\n billingZip?: string;\n shippingFirstName?: string;\n shippingLastName?: string;\n shippingCountry?: string;\n shippingState?: string;\n shippingCity?: string;\n shippingAddress?: string;\n shippingZip?: string;\n email?: string;\n phone?: string;\n}\n\nexport interface BlueSnapDirectSdk {\n hostedPaymentFieldsCreate(options: BlueSnapDirectHostedPaymentFieldsOptions): void;\n hostedPaymentFieldsSubmitData(\n callback: (results: BlueSnapDirectCallbackResults) => void,\n threeDSecureData?: BlueSnapDirectThreeDSecureData,\n ): void;\n}\n\nexport interface BlueSnapDirectHostWindow extends Window {\n bluesnap?: BlueSnapDirectSdk;\n}\n\nexport interface BlueSnapDirectStyleProps {\n border?: string;\n height?: string;\n width?: string;\n}\n\nexport interface BlueSnapDirectRedirectResponseProviderData {\n [key: string]: string;\n merchantid: string;\n}\n\nexport interface BlueSnapDirectRedirectResponse {\n body: {\n additional_action_required: {\n type: 'offsite_redirect';\n data: {\n redirect_url: string;\n };\n };\n status: string;\n provider_data: string;\n };\n}\n\n/**\n * A set of options that are required to initialize the BlueSnap V2 payment\n * method.\n *\n * The payment step is done through a web page via an iframe provided by the\n * strategy.\n *\n * ```html\n * \n *
\n *\n * \n * \n * ```\n *\n * ```js\n * service.initializePayment({\n * methodId: 'bluesnapDirect',\n * bluesnapDirect: {\n * onLoad: (iframe) => {\n * document.getElementById('container')\n * .appendChild(iframe);\n *\n * document.getElementById('cancel-button')\n * .addEventListener('click', () => {\n * document.getElementById('container').innerHTML = '';\n * });\n * },\n * },\n * });\n * ```\n */\nexport interface BlueSnapDirectAPMInitializeOptions {\n /**\n * A set of CSS properties to apply to the iframe.\n */\n style?: BlueSnapDirectStyleProps;\n\n /**\n * A callback that gets called when the iframe is ready to be added to the\n * current page. It is responsible for determining where the iframe should\n * be inserted in the DOM.\n *\n * @param iframe - The iframe element containing the payment web page\n * provided by the strategy.\n * @param cancel - A function, when called, will cancel the payment\n * process and remove the iframe.\n */\n onLoad(iframe: HTMLIFrameElement, cancel: () => void): void;\n}\n\nexport interface WithBlueSnapDirectAPMPaymentInitializeOptions {\n /**\n * The options that are required to initialize the Apple Pay payment\n * method. They can be omitted unless you need to support Apple Pay.\n */\n bluesnapdirect?: BlueSnapDirectAPMInitializeOptions;\n}\n","import { HostedFieldType } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BlueSnapDirectHostedFieldTagId as HostedFieldTagId } from './types';\n\nexport const BlueSnapHostedFieldType: {\n [HostedFieldTagId.CardNumber]: HostedFieldType.CardNumber;\n [HostedFieldTagId.CardExpiry]: HostedFieldType.CardExpiry;\n [HostedFieldTagId.CardName]: HostedFieldType.CardName;\n [HostedFieldTagId.CardCode]: HostedFieldType.CardCode;\n} = {\n [HostedFieldTagId.CardNumber]: HostedFieldType.CardNumber,\n [HostedFieldTagId.CardExpiry]: HostedFieldType.CardExpiry,\n [HostedFieldTagId.CardName]: HostedFieldType.CardName,\n [HostedFieldTagId.CardCode]: HostedFieldType.CardCode,\n};\n\nexport const CREDIT_CARD_ERRORS = {\n empty: {\n [HostedFieldType.CardNumber]: {\n fieldType: 'cardNumber',\n message: 'Credit card number is required',\n type: 'required',\n },\n [HostedFieldType.CardNumberVerification]: {\n fieldType: 'cardNumber',\n message: 'Credit card number is required',\n type: 'required',\n },\n [HostedFieldType.CardExpiry]: {\n fieldType: 'cardExpiry',\n message: 'Expiration date is required',\n type: 'required',\n },\n [HostedFieldType.CardCode]: {\n fieldType: 'cardCode',\n message: 'CVV is required',\n type: 'required',\n },\n [HostedFieldType.CardCodeVerification]: {\n fieldType: 'cardCode',\n message: 'CVV is required',\n type: 'required',\n },\n [HostedFieldType.CardName]: {\n fieldType: 'cardName',\n message: 'Full name is required',\n type: 'required',\n },\n },\n invalid: {\n [HostedFieldType.CardNumber]: {\n fieldType: 'cardNumber',\n message: 'Credit card number must be valid',\n type: 'invalid_card_number',\n },\n [HostedFieldType.CardNumberVerification]: {\n fieldType: 'cardNumber',\n message: 'Credit card number must be valid',\n type: 'invalid_card_number',\n },\n [HostedFieldType.CardExpiry]: {\n fieldType: 'cardExpiry',\n message: 'Expiration date must be a valid future date in MM / YY format',\n type: 'invalid_card_expiry',\n },\n [HostedFieldType.CardCode]: {\n fieldType: 'cardCode',\n message: 'CVV must be valid',\n type: 'invalid_card_code',\n },\n [HostedFieldType.CardCodeVerification]: {\n fieldType: 'cardCode',\n message: 'CVV must be valid',\n type: 'invalid_card_code',\n },\n [HostedFieldType.CardName]: {\n fieldType: 'cardName',\n message: 'Full name is required',\n type: 'required',\n },\n },\n};\n","import { kebabCase } from 'lodash';\n\nimport { CreditCardPaymentInitializeOptions } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n guard,\n HostedCardFieldOptionsMap,\n HostedFieldBlurEventData,\n HostedFieldEnterEventData,\n HostedFieldFocusEventData,\n HostedFieldOptionsMap,\n HostedFieldStylesMap,\n HostedFormOptions,\n HostedInputValidateErrorData,\n HostedStoredCardFieldOptionsMap,\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n PaymentMethodFailedError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BlueSnapHostedFieldType } from './bluesnap-direct-constants';\nimport BlueSnapHostedInputValidator from './bluesnap-direct-hosted-input-validator';\nimport BluesnapDirectNameOnCardInput from './bluesnap-direct-name-on-card-input';\nimport BlueSnapDirectScriptLoader from './bluesnap-direct-script-loader';\nimport isValidationErrorDescription from './is-bluesnap-direct-input-validation-error-description';\nimport isHostedCardFieldOptionsMap from './is-hosted-card-field-options-map';\nimport isHostedStoredCardFieldOptionsMap from './is-hosted-stored-card-field-options-map';\nimport {\n BlueSnapDirectSdk,\n BlueSnapDirectStyle,\n BlueSnapDirectCallbackCardData as CallbackCardData,\n BlueSnapDirectCallbackError as CallbackError,\n BlueSnapDirectCallbackResults as CallbackResults,\n WithBlueSnapDirectCardHolderName as CardHolderName,\n BlueSnapDirectCardType as CardType,\n BlueSnapDirectCardTypeValues as CardTypeValues,\n BlueSnapDirectErrorCode as ErrorCode,\n BlueSnapDirectErrorDescription as ErrorDescription,\n BlueSnapDirectEventOrigin as EventOrigin,\n BlueSnapDirectHostedFieldTagId as HostedFieldTagId,\n BlueSnapDirectHostedPaymentFieldsOptions as HostedPaymentFieldsOptions,\n BlueSnapDirectThreeDSecureData as ThreeDSecureData,\n} from './types';\n\nexport default class BlueSnapDirectHostedForm {\n private _blueSnapSdk?: BlueSnapDirectSdk;\n private _onValidate: HostedFormOptions['onValidate'];\n\n constructor(\n private _scriptLoader: BlueSnapDirectScriptLoader,\n private _nameOnCardInput: BluesnapDirectNameOnCardInput,\n private _hostedInputValidator: BlueSnapHostedInputValidator,\n ) {}\n\n async initialize(testMode = false, fields?: HostedFieldOptionsMap): Promise {\n this._blueSnapSdk = await this._scriptLoader.load(testMode);\n\n if (!fields) {\n return;\n }\n\n if (isHostedCardFieldOptionsMap(fields)) {\n this._hostedInputValidator.initialize();\n\n return;\n }\n\n if (\n isHostedStoredCardFieldOptionsMap(fields) &&\n !!fields.cardNumberVerification &&\n !!fields.cardCodeVerification\n ) {\n this._hostedInputValidator.initializeValidationFields();\n\n return;\n }\n\n if (isHostedStoredCardFieldOptionsMap(fields) && !!fields.cardCodeVerification) {\n this._hostedInputValidator.initializeValidationCVVFields();\n }\n }\n\n async attach(\n paymentFieldsToken: string,\n { form: { fields, ...callbacksAndStyles } }: CreditCardPaymentInitializeOptions,\n enable3DS = false,\n ): Promise {\n const blueSnapSdk = this._getBlueSnapSdk();\n\n if (!isHostedCardFieldOptionsMap(fields) && !isHostedStoredCardFieldOptionsMap(fields)) {\n throw new InvalidArgumentError(\n 'Field options must be of type HostedCardFieldOptionsMap',\n );\n }\n\n this._onValidate = callbacksAndStyles.onValidate;\n\n if (isHostedCardFieldOptionsMap(fields)) {\n this._setCustomBlueSnapAttributes(fields);\n }\n\n if (isHostedStoredCardFieldOptionsMap(fields)) {\n this._setCustomStoredCardsBlueSnapAttributes(fields);\n }\n\n return new Promise((resolve) => {\n const options = this._getHostedPaymentFieldsOptions(\n paymentFieldsToken,\n fields,\n callbacksAndStyles,\n resolve,\n enable3DS,\n );\n\n blueSnapSdk.hostedPaymentFieldsCreate(options);\n\n if (isHostedCardFieldOptionsMap(fields)) {\n this._nameOnCardInput.attach(\n options,\n fields.cardName.accessibilityLabel,\n fields.cardName.placeholder,\n );\n }\n });\n }\n\n validate(): this {\n const results = this._hostedInputValidator.validate();\n\n this._onValidate?.(results);\n\n if (!results.isValid) {\n const details = Object.entries(results.errors).reduce(\n (result, [key, value]: [string, HostedInputValidateErrorData[]]) => ({\n ...result,\n [key]: value.map(({ message, type }) => ({ message, type })),\n }),\n {},\n );\n\n throw new PaymentInvalidFormError(details);\n }\n\n return this;\n }\n\n submit(\n threeDSecureData?: ThreeDSecureData,\n shouldSendName = false,\n ): Promise {\n return new Promise((resolve, reject) =>\n this._getBlueSnapSdk().hostedPaymentFieldsSubmitData(\n (data: CallbackResults) =>\n this._isBlueSnapDirectCallbackError(data)\n ? reject(\n new PaymentMethodFailedError(\n data.statusCode === ErrorCode.THREE_DS_AUTH_FAILED\n ? data.error[0].errorDescription\n : `Submission failed with status: ${\n data.statusCode\n } and errors: ${JSON.stringify(data.error)}`,\n ),\n )\n : resolve({\n ...data.cardData,\n ...(shouldSendName\n ? { cardHolderName: this._nameOnCardInput.getValue() }\n : {}),\n }),\n threeDSecureData,\n ),\n );\n }\n\n detach(): void {\n this._nameOnCardInput.detach();\n }\n\n private _isBlueSnapDirectCallbackError(data: CallbackResults): data is CallbackError {\n return 'error' in data;\n }\n\n private _getHostedPaymentFieldsOptions(\n token: string,\n fields: HostedCardFieldOptionsMap | HostedStoredCardFieldOptionsMap,\n {\n onFocus,\n onBlur,\n onValidate,\n onCardTypeChange,\n onEnter,\n styles,\n }: Omit,\n resolve: () => void,\n enable3DS: boolean,\n ): HostedPaymentFieldsOptions {\n return {\n token,\n onFieldEventHandler: {\n setupComplete: () => resolve(),\n onFocus: this._usetUiEventCallback(onFocus),\n onBlur: this._usetUiEventCallback(onBlur),\n onError: this._handleError(onValidate),\n onType: (_tagId: HostedFieldTagId, cardType: CardTypeValues) =>\n onCardTypeChange?.({ cardType: CardType[cardType] }),\n onEnter: this._usetUiEventCallback(onEnter),\n onValid: (tagId: HostedFieldTagId) =>\n onValidate?.(this._hostedInputValidator.validate({ tagId })),\n },\n ...(isHostedCardFieldOptionsMap(fields) && {\n ccnPlaceHolder: fields.cardNumber.placeholder || '',\n cvvPlaceHolder: fields.cardCode?.placeholder || '',\n expPlaceHolder: fields.cardExpiry.placeholder || 'MM / YY',\n }),\n ...(styles && { style: this._mapStyles(styles) }),\n '3DS': enable3DS,\n };\n }\n\n private _mapStyles({\n default: input,\n error,\n focus,\n }: HostedFieldStylesMap): BlueSnapDirectStyle {\n return Object.entries({\n ...(input && { input }),\n ...(error && { '.invalid': error }),\n ...(focus && { ':focus': focus }),\n }).reduce((result, [selector, declaration]) => {\n return {\n ...result,\n [selector]: Object.entries(declaration).reduce(\n (declarationBlock, [property, value]) => ({\n ...declarationBlock,\n [kebabCase(property)]: value,\n }),\n {},\n ),\n };\n }, {});\n }\n\n private _handleError(\n onValidate: HostedFormOptions['onValidate'],\n ): (\n tagId: HostedFieldTagId | undefined,\n errorCode: ErrorCode,\n errorDescription: ErrorDescription | undefined,\n eventOrigin: EventOrigin | undefined,\n ) => void {\n return (tagId, errorCode, errorDescription, eventOrigin) => {\n if (errorCode === ErrorCode.INVALID_OR_EMPTY) {\n if (tagId && isValidationErrorDescription(errorDescription)) {\n return onValidate?.(\n this._hostedInputValidator.validate({ tagId, errorDescription }),\n );\n }\n }\n\n throw new PaymentMethodFailedError(\n `An unexpected error has occurred: ${JSON.stringify({\n tagId,\n errorCode,\n errorDescription,\n eventOrigin,\n })}`,\n );\n };\n }\n\n private _usetUiEventCallback(\n callback?: (\n data: HostedFieldBlurEventData | HostedFieldEnterEventData | HostedFieldFocusEventData,\n ) => void,\n ): (tagId: HostedFieldTagId) => void {\n return (tagId) => {\n if (callback) {\n callback({ fieldType: BlueSnapHostedFieldType[tagId] });\n }\n };\n }\n\n private _getBlueSnapSdk(): BlueSnapDirectSdk {\n return guard(\n this._blueSnapSdk,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n private _setCustomBlueSnapAttributes(fields: HostedCardFieldOptionsMap): void {\n const { cardNumber, cardExpiry, cardCode, cardName } = fields;\n\n const cardNumberContainer = document.getElementById(cardNumber.containerId);\n const cardExpiryContainer = document.getElementById(cardExpiry.containerId);\n const cardCodeContainer = cardCode && document.getElementById(cardCode.containerId);\n const cardNameContainer = document.getElementById(cardName.containerId);\n\n if (\n !cardNumberContainer ||\n !cardExpiryContainer ||\n !cardCodeContainer ||\n !cardNameContainer\n ) {\n throw new InvalidArgumentError(\n 'Unable to create hosted payment fields to invalid HTML container elements.',\n );\n }\n\n cardNumberContainer.dataset.bluesnap = HostedFieldTagId.CardNumber;\n cardExpiryContainer.dataset.bluesnap = HostedFieldTagId.CardExpiry;\n cardCodeContainer.dataset.bluesnap = HostedFieldTagId.CardCode;\n cardNameContainer.dataset.bluesnap = HostedFieldTagId.CardName;\n }\n\n private _setCustomStoredCardsBlueSnapAttributes(fields: HostedStoredCardFieldOptionsMap): void {\n const { cardNumberVerification, cardCodeVerification } = fields;\n\n const cardNumberContainer =\n cardNumberVerification && document.getElementById(cardNumberVerification.containerId);\n const cardCodeContainer =\n cardCodeVerification && document.getElementById(cardCodeVerification.containerId);\n\n if (!cardNumberContainer && !cardCodeContainer) {\n return;\n }\n\n if (cardNumberContainer) {\n cardNumberContainer.dataset.bluesnap = HostedFieldTagId.CardNumber;\n }\n\n if (cardCodeContainer) {\n cardCodeContainer.dataset.bluesnap = HostedFieldTagId.CardCode;\n }\n }\n}\n","import {\n BlueSnapDirectErrorDescription,\n BlueSnapDirectInputValidationErrorDescription,\n} from './types';\n\nexport default function isBlueSnapDirectInputValidationErrorDescription(\n errorDescription?: BlueSnapDirectErrorDescription,\n): errorDescription is BlueSnapDirectInputValidationErrorDescription {\n if (errorDescription === undefined) {\n return false;\n }\n\n return [BlueSnapDirectErrorDescription.EMPTY, BlueSnapDirectErrorDescription.INVALID].includes(\n errorDescription,\n );\n}\n","import {\n HostedInputValidateErrorData,\n HostedInputValidateErrorDataMap,\n HostedInputValidateResults,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BlueSnapHostedFieldType, CREDIT_CARD_ERRORS } from './bluesnap-direct-constants';\nimport {\n BlueSnapDirectInputValidationErrorDescription as ErrorDescription,\n BlueSnapDirectHostedFieldTagId as HostedFieldTagId,\n} from './types';\n\nexport default class BlueSnapHostedInputValidator {\n private _errors: HostedInputValidateErrorDataMap = {};\n\n initialize(): void {\n this._errors = {\n cardNumber: [CREDIT_CARD_ERRORS.empty.cardNumber],\n cardExpiry: [CREDIT_CARD_ERRORS.empty.cardExpiry],\n cardCode: [CREDIT_CARD_ERRORS.empty.cardCode],\n cardName: [CREDIT_CARD_ERRORS.empty.cardName],\n };\n }\n\n initializeValidationFields(): void {\n this._errors = {\n cardNumber: [CREDIT_CARD_ERRORS.empty.cardNumber],\n cardCode: [CREDIT_CARD_ERRORS.empty.cardCode],\n };\n }\n\n initializeValidationCVVFields(): void {\n this._errors = {\n cardCode: [CREDIT_CARD_ERRORS.empty.cardCode],\n };\n }\n\n validate(error?: {\n tagId: HostedFieldTagId;\n errorDescription?: ErrorDescription;\n }): HostedInputValidateResults {\n if (error) {\n this._updateErrors(error.tagId, error.errorDescription);\n }\n\n return {\n isValid: Object.values(this._errors).every(\n (errorData: HostedInputValidateErrorData[]) => errorData.length === 0,\n ),\n errors: this._errors,\n };\n }\n\n private _updateErrors(tagId: HostedFieldTagId, errorDescription?: ErrorDescription): void {\n const fieldType = BlueSnapHostedFieldType[tagId];\n\n this._errors[fieldType] = errorDescription\n ? [CREDIT_CARD_ERRORS[errorDescription][fieldType]]\n : [];\n }\n}\n","import {\n guard,\n NotInitializedError,\n NotInitializedErrorType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport isArrayOfAllowedProps from './is-array-of-allowed-props';\nimport {\n BluesnapDirectNocInputAllowedStyle as AllowedStyle,\n BlueSnapDirectStyle,\n BlueSnapDirectErrorCode as ErrorCode,\n BlueSnapDirectErrorDescription as ErrorDescription,\n BlueSnapDirectEventOrigin as EventOrigin,\n BlueSnapDirectHostedFieldTagId as HostedFieldTagId,\n BlueSnapDirectHostedPaymentFieldsOptions as HostedPaymentFieldsOptions,\n BlueSnapDirectStyleDeclaration as StyleDeclaration,\n} from './types';\n\nexport default class BluesnapDirectNameOnCardInput {\n private _input?: HTMLInputElement;\n private _style?: BlueSnapDirectStyle;\n\n attach(\n {\n style,\n onFieldEventHandler: { onFocus, onBlur, onValid, onError, onEnter } = {},\n }: HostedPaymentFieldsOptions,\n accessibilityLabel?: string,\n placeholder?: string,\n ): void {\n this._style = style;\n\n this._create();\n\n this._getInput().addEventListener('focus', this._handleFocus(onFocus));\n this._getInput().addEventListener('blur', this._handleBlur(onBlur, onValid, onError));\n this._getInput().addEventListener('enter', this._handleEnter(onEnter));\n\n if (accessibilityLabel) {\n this._getInput().setAttribute('aria-label', accessibilityLabel);\n }\n\n if (placeholder) {\n this._getInput().placeholder = placeholder;\n }\n\n document.querySelector('[data-bluesnap=\"noc\"]')?.appendChild(this._getInput());\n }\n\n getValue(): string {\n return this._getInput().value;\n }\n\n detach(): void {\n if (this._input) {\n this._input.remove();\n this._input = undefined;\n }\n }\n\n private _handleFocus(\n onFocus: Required['onFieldEventHandler']['onFocus'],\n ): (event: Event) => void {\n return () => {\n this._applyStyles(this._style?.[':focus']);\n\n onFocus?.(HostedFieldTagId.CardName);\n };\n }\n\n private _handleBlur(\n onBlur: Required['onFieldEventHandler']['onBlur'],\n onValid: Required['onFieldEventHandler']['onValid'],\n onError: Required['onFieldEventHandler']['onError'],\n ): (event: Event) => void {\n return ({ target }) => {\n onBlur?.(HostedFieldTagId.CardName);\n\n if (target instanceof HTMLInputElement) {\n if (/\\w{1,200}/.test(target.value)) {\n this._applyStyles(this._style?.input);\n\n onValid?.(HostedFieldTagId.CardName);\n } else {\n this._applyStyles(this._style?.['.invalid']);\n\n onError?.(\n HostedFieldTagId.CardName,\n ErrorCode.INVALID_OR_EMPTY,\n ErrorDescription.EMPTY,\n EventOrigin.ON_BLUR,\n );\n }\n }\n };\n }\n\n private _handleEnter(\n onEnter: Required['onFieldEventHandler']['onEnter'],\n ): (event: Event) => void {\n return () => onEnter?.(HostedFieldTagId.CardName);\n }\n\n private _applyStyles(styles: StyleDeclaration = {}): void {\n const allowedStyle: AllowedStyle = {\n color: styles.color,\n fontFamily: styles['font-family'],\n fontSize: styles['font-size'],\n fontWeight: styles['font-weight'],\n };\n const styleKeys = Object.keys(allowedStyle);\n\n if (isArrayOfAllowedProps(styleKeys)) {\n styleKeys.forEach((key) => {\n if (!allowedStyle[key]) {\n return;\n }\n\n this._getInput().style[key] = allowedStyle[key] || '';\n });\n }\n }\n\n private _configureInput(): void {\n this._getInput().autocomplete = 'cc-name';\n this._getInput().id = HostedFieldTagId.CardName;\n this._getInput().inputMode = 'text';\n this._getInput().maxLength = 200;\n this._getInput().style.backgroundColor = 'transparent';\n this._getInput().style.border = '0';\n this._getInput().style.height = '100%';\n this._getInput().style.margin = '0';\n this._getInput().style.outline = 'none';\n this._getInput().style.padding = '0';\n this._getInput().style.width = '100%';\n this._getInput().type = 'text';\n }\n\n private _getInput(): HTMLInputElement {\n return guard(\n this._input,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n private _create(): void {\n this._input = document.createElement('input');\n this._configureInput();\n this._applyStyles(this._style?.input);\n }\n}\n","import { BluesnapDirectNocInputAllowedStyle } from './types';\n\nexport default function isArrayOfAllowedProps(\n fields: string[],\n): fields is Array {\n return fields.every((field) =>\n ['color', 'fontFamily', 'fontSize', 'fontWeight'].includes(field),\n );\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BlueSnapDirectHostWindow, BlueSnapDirectSdk } from './types';\n\nexport enum BlueSnapDirectSdkEnv {\n PRODUCTION = 'https://pay.bluesnap.com/web-sdk/5/bluesnap.js',\n SANDBOX = 'https://sandpay.bluesnap.com/web-sdk/5/bluesnap.js',\n}\n\nexport default class BlueSnapDirectScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _window: BlueSnapDirectHostWindow = window,\n ) {}\n\n async load(testMode = false): Promise {\n await this._scriptLoader.loadScript(\n testMode ? BlueSnapDirectSdkEnv.SANDBOX : BlueSnapDirectSdkEnv.PRODUCTION,\n );\n\n if (!this._window.bluesnap) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.bluesnap;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BlueSnapDirectCreditCardPaymentStrategy from './bluesnap-direct-credit-card-payment-strategy';\nimport BlueSnapDirectHostedForm from './bluesnap-direct-hosted-form';\nimport BlueSnapHostedInputValidator from './bluesnap-direct-hosted-input-validator';\nimport BluesnapDirectNameOnCardInput from './bluesnap-direct-name-on-card-input';\nimport BlueSnapDirectScriptLoader from './bluesnap-direct-script-loader';\n\nconst createBlueSnapDirectCreditCardPaymentStrategy: PaymentStrategyFactory<\n BlueSnapDirectCreditCardPaymentStrategy\n> = (paymentIntegrationService) =>\n new BlueSnapDirectCreditCardPaymentStrategy(\n paymentIntegrationService,\n new BlueSnapDirectHostedForm(\n new BlueSnapDirectScriptLoader(getScriptLoader()),\n new BluesnapDirectNameOnCardInput(),\n new BlueSnapHostedInputValidator(),\n ),\n );\n\nexport default toResolvableModule(createBlueSnapDirectCreditCardPaymentStrategy, [\n { id: 'credit_card', gateway: 'bluesnapdirect' },\n]);\n","import {\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentIntegrationService,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport assertBlueSnapDirectEcpInstrument from './is-bluesnap-direct-ecp-instrument';\n\nexport default class BlueSnapDirectEcpPaymentStrategy implements PaymentStrategy {\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n async execute({ payment }: OrderRequestBody): Promise {\n assertBlueSnapDirectEcpInstrument(payment?.paymentData);\n\n await this._paymentIntegrationService.submitOrder();\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n formattedPayload: {\n ecp: {\n account_number: payment.paymentData.accountNumber,\n account_type: payment.paymentData.accountType,\n shopper_permission: payment.paymentData.shopperPermission,\n routing_number: payment.paymentData.routingNumber,\n },\n },\n },\n });\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n}\n","import {\n BlueSnapDirectEcpInstrument,\n OrderPaymentRequestBody,\n PaymentArgumentInvalidError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nfunction isBlueSnapDirectEcpInstrument(\n data: OrderPaymentRequestBody['paymentData'],\n): data is BlueSnapDirectEcpInstrument {\n if (data === undefined) {\n return false;\n }\n\n return (\n 'accountNumber' in data &&\n 'accountType' in data &&\n 'shopperPermission' in data &&\n 'routingNumber' in data\n );\n}\n\nexport default function assertBlueSnapDirectEcpInstrument(\n data: OrderPaymentRequestBody['paymentData'],\n): asserts data is BlueSnapDirectEcpInstrument {\n if (!isBlueSnapDirectEcpInstrument(data)) {\n throw new PaymentArgumentInvalidError();\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BlueSnapDirectEcpPaymentStrategy from './bluesnap-direct-ecp-payment-strategy';\n\nconst createBlueSnapDirectEcpPaymentStrategy: PaymentStrategyFactory<\n BlueSnapDirectEcpPaymentStrategy\n> = (paymentIntegrationService) => new BlueSnapDirectEcpPaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createBlueSnapDirectEcpPaymentStrategy, [\n { id: 'ecp', gateway: 'bluesnapdirect' },\n]);\n","import {\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { createIframe } from './bluesnap-direct-iframe-creator';\nimport isBlueSnapDirectRedirectResponseProviderData from './is-bluesnap-direct-provider-data';\nimport {\n BlueSnapDirectAPMInitializeOptions,\n BlueSnapDirectRedirectResponse,\n WithBlueSnapDirectAPMPaymentInitializeOptions,\n} from './types';\n\nconst IFRAME_NAME = 'bluesnap_direct_hosted_payment_page';\n\nexport default class BlueSnapDirectAPMPaymentStrategy implements PaymentStrategy {\n private _initializeOptions?: BlueSnapDirectAPMInitializeOptions;\n\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBlueSnapDirectAPMPaymentInitializeOptions,\n ): Promise {\n const { bluesnapdirect } = options;\n\n if (!bluesnapdirect) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bluesnapdirect\" argument is not provided.',\n );\n }\n\n this._initializeOptions = bluesnapdirect;\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentInitializeOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!this._initializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n try {\n await this._paymentIntegrationService.submitPayment({\n methodId: payment.methodId,\n });\n } catch (error) {\n if (this._isBlueSnapDirectRedirectResponse(error)) {\n const providerData: unknown = JSON.parse(error.body.provider_data);\n\n if (isBlueSnapDirectRedirectResponseProviderData(providerData)) {\n const providerDataQuery = new URLSearchParams(providerData).toString();\n\n await this._mountAPMFrame(\n `${error.body.additional_action_required.data.redirect_url}&${providerDataQuery}`,\n );\n }\n }\n\n return Promise.reject(error);\n }\n }\n\n async finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private _mountAPMFrame(url: string): Promise {\n return new Promise((_, reject) => {\n if (!this._initializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { onLoad, style } = this._initializeOptions;\n const frame = createIframe(IFRAME_NAME, url, style);\n\n onLoad(frame, () => {\n reject(new PaymentMethodCancelledError());\n });\n });\n }\n\n private _isBlueSnapDirectRedirectResponse(\n response: unknown,\n ): response is BlueSnapDirectRedirectResponse {\n if (typeof response !== 'object' || response === null) {\n return false;\n }\n\n const partialResponse: Partial = response;\n\n if (!partialResponse.body) {\n return false;\n }\n\n const partialBody: Partial = partialResponse.body;\n\n return (\n partialBody.status === 'additional_action_required' &&\n !!partialBody.additional_action_required?.data.redirect_url &&\n typeof partialBody.provider_data === 'string'\n );\n }\n}\n","import { BlueSnapDirectRedirectResponseProviderData } from './types';\n\nexport default function isBlueSnapDirectRedirectResponseProviderData(\n value: unknown,\n): value is BlueSnapDirectRedirectResponseProviderData {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n\n const partialValue: Partial = value;\n\n if (!partialValue.merchantid) {\n return false;\n }\n\n return typeof partialValue.merchantid === 'string';\n}\n","import { BlueSnapDirectStyleProps } from './types';\n\nexport const createIframe = (\n name: string,\n src: string,\n style?: BlueSnapDirectStyleProps,\n): HTMLIFrameElement => {\n const iframe = document.createElement('iframe');\n\n iframe.setAttribute(\n 'sandbox',\n 'allow-top-navigation allow-scripts allow-forms allow-same-origin',\n );\n\n iframe.src = src;\n\n iframe.name = name;\n\n if (style) {\n const { border, height, width } = style;\n\n iframe.style.border = border || '';\n iframe.style.height = height || '';\n iframe.style.width = width || '';\n }\n\n return iframe;\n};\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BlueSnapDirectAPMPaymentStrategy from './bluesnap-direct-apm-payment-strategy';\n\nconst createBlueSnapDirectAPMPaymentStrategy: PaymentStrategyFactory<\n BlueSnapDirectAPMPaymentStrategy\n> = (paymentIntegrationService) => new BlueSnapDirectAPMPaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createBlueSnapDirectAPMPaymentStrategy, [\n { gateway: 'bluesnapdirect' },\n]);\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"local-storage-fallback\");","import { isObject } from 'lodash';\n\nimport { LineItemMap } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ExtraItemsData } from './extra-items-data';\n\ntype StorageFallback = Pick;\n\nconst ORDER_ITEMS_STORAGE_KEY = 'ORDER_ITEMS';\n\nfunction isExtraItemsData(itemsData: unknown): itemsData is ExtraItemsData {\n if (!isObject(itemsData)) {\n return false;\n }\n\n const hasNotExtraItems = Object.values(itemsData).some(\n (item) => !isObject(item) || !('brand' in item) || !('category' in item),\n );\n\n return Boolean(!hasNotExtraItems);\n}\n\nexport default class AnalyticsExtraItemsManager {\n constructor(private storage: StorageFallback) {}\n\n saveExtraItemsData(id: string, lineItems: LineItemMap): ExtraItemsData {\n const data = [...lineItems.physicalItems, ...lineItems.digitalItems].reduce(\n (result, item) => {\n result[item.productId] = {\n brand: item.brand ? item.brand : '',\n category: item.categoryNames ? item.categoryNames.join(', ') : '',\n };\n\n return result;\n },\n {},\n );\n\n try {\n this.storage.setItem(this.getStorageKey(id), JSON.stringify(data));\n\n return data;\n } catch (err) {\n return {};\n }\n }\n\n readExtraItemsData(id: string): ExtraItemsData | null {\n try {\n const item = this.storage.getItem(this.getStorageKey(id));\n\n if (!item) {\n return null;\n }\n\n const data: unknown = JSON.parse(item);\n\n return isExtraItemsData(data) ? data : null;\n } catch (err) {\n return null;\n }\n }\n\n clearExtraItemData(id: string): void {\n try {\n this.storage.removeItem(this.getStorageKey(id));\n } catch (err) {\n // silently ignore the failure\n }\n }\n\n private getStorageKey(id: string): string {\n return id ? `${ORDER_ITEMS_STORAGE_KEY}_${id}` : '';\n }\n}\n","import AnalyticsTrackerWindow from './analytics-tracker-window';\n\nexport function isAnalyticsTrackerWindow(window: Window): window is AnalyticsTrackerWindow {\n return Boolean(window.hasOwnProperty('analytics'));\n}\n","import { WithAccountCreation } from './payment';\n\nexport default function isWithAccountCreation(\n paymentData: unknown,\n): paymentData is WithAccountCreation {\n return (\n typeof paymentData === 'object' &&\n paymentData !== null &&\n 'shouldCreateAccount' in paymentData\n );\n}\n","import { PaymentErrorData, StandardError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class BoltError extends StandardError {\n body: { errors: PaymentErrorData[] };\n\n constructor(public errorCode: string) {\n super();\n\n this.name = 'BoltPaymentsFieldError';\n this.type = 'bolt_payments_field_error';\n this.body = { errors: [BoltError.getError(errorCode)] };\n }\n\n private static getError(errorCode: string): PaymentErrorData {\n switch (errorCode) {\n case '1000':\n case '2000':\n case '3000':\n return { code: 'invalid_number' };\n\n case '1001':\n case '2001':\n case '3001':\n return { code: 'invalid_expiry_date' };\n\n case '1002':\n case '2002':\n return { code: 'invalid_cvc' };\n\n case '1003':\n return { code: 'invalid_zip' };\n\n case '2003':\n return { code: 'incorrect_zip' };\n\n default:\n return { code: 'general_error' };\n }\n }\n}\n","import {\n AnalyticsExtraItemsManager,\n isAnalyticsTrackerWindow,\n} from '@bigcommerce/checkout-sdk/analytics';\nimport {\n InvalidArgumentError,\n isWithAccountCreation,\n MissingDataError,\n MissingDataErrorType,\n NonceInstrument,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n WithAccountCreation,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n BoltCheckout,\n BoltEmbedded,\n BoltEmbeddedTokenize,\n BoltEmbededField,\n BoltPaymentMethod,\n BoltTransaction,\n} from './bolt';\nimport BoltError from './bolt-error';\nimport { WithBoltPaymentInitializeOptions } from './bolt-payment-initialize-options';\nimport BoltScriptLoader from './bolt-script-loader';\nimport { isBoltPaymentData } from './is-bolt-payment-data';\n\nexport default class BoltPaymentStrategy implements PaymentStrategy {\n private boltClient?: BoltCheckout;\n private boltEmbedded?: BoltEmbedded;\n private embeddedField?: BoltEmbededField;\n private useBoltClient = false;\n private useBoltEmbedded = false;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private boltScriptLoader: BoltScriptLoader,\n private analyticsExtraItemsManager: AnalyticsExtraItemsManager,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBoltPaymentInitializeOptions,\n ): Promise {\n const { bolt, methodId } = options;\n const { containerId, onPaymentSelect, useBigCommerceCheckout } = bolt || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!useBigCommerceCheckout) {\n // info: calling loadBoltClient method without providing any params is necessary for Bolt Full Checkout and Fraud Protection\n this.boltClient = await this.boltScriptLoader.loadBoltClient();\n\n return;\n }\n\n const paymentMethod: BoltPaymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(options.methodId);\n\n const { initializationData, config } = paymentMethod;\n const { publishableKey, developerConfig, embeddedOneClickEnabled } =\n initializationData || {};\n const { testMode } = config;\n\n if (!publishableKey) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.boltClient = await this.boltScriptLoader.loadBoltClient(\n publishableKey,\n testMode,\n developerConfig,\n );\n\n this.useBoltClient = !embeddedOneClickEnabled;\n this.useBoltEmbedded = !!embeddedOneClickEnabled;\n\n if (this.useBoltEmbedded) {\n if (!containerId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bolt.containerId\" argument is not provided.',\n );\n }\n\n if (!onPaymentSelect) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bolt.onPaymentSelect\" argument is not provided.',\n );\n }\n\n this.boltEmbedded = await this.boltScriptLoader.loadBoltEmbedded(\n publishableKey,\n testMode,\n developerConfig,\n );\n\n this.mountBoltEmbeddedField(containerId);\n onPaymentSelect(await this.hasBoltAccount());\n }\n }\n\n deinitialize(): Promise {\n this.embeddedField?.unmount();\n\n this.boltClient = undefined;\n this.boltEmbedded = undefined;\n\n return Promise.resolve();\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n this.setExtraItemsForAnalytics();\n\n const { payment, ...order } = payload;\n const { methodId, paymentData } = payment || {};\n let paymentPayload;\n\n if (!payload.payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!methodId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (!paymentData || !isBoltPaymentData(paymentData)) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n if (this.useBoltClient) {\n paymentPayload = await this.getBoltClientPaymentPayload(methodId, paymentData, options);\n } else if (this.useBoltEmbedded) {\n paymentPayload = await this.getBoltEmbeddedPaymentPayload(methodId, paymentData);\n } else {\n paymentPayload = await this.getBoltFullCheckoutPaymentPayload(methodId, paymentData);\n }\n\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n }\n\n private async getBoltClientPaymentPayload(\n methodId: string,\n paymentData: NonceInstrument,\n options?: PaymentRequestOptions,\n ): Promise {\n await this.paymentIntegrationService.loadPaymentMethod(methodId, options);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const orderToken = paymentMethod.clientToken;\n const { isStoreCreditApplied } = state.getCheckoutOrThrow();\n const { shouldSaveInstrument } = paymentData;\n const boltClient = this.getBoltClientOrThrow();\n\n await this.paymentIntegrationService.applyStoreCredit(isStoreCreditApplied);\n\n if (!orderToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const boltTransaction: BoltTransaction = await new Promise((resolve, reject) => {\n const onSuccess = (transaction: BoltTransaction, callback: () => void) => {\n if (!transaction.reference) {\n reject(\n new PaymentMethodFailedError(\n 'Unable to proceed because transaction reference is unavailable. Please try again later.',\n ),\n );\n } else {\n resolve(transaction);\n }\n\n callback();\n };\n\n const onClose = () => {\n reject(new PaymentMethodCancelledError());\n };\n\n const callbacks = {\n success: onSuccess,\n close: onClose,\n };\n\n boltClient.configure({ orderToken }, {}, callbacks).open();\n });\n\n return {\n methodId,\n paymentData: {\n nonce: boltTransaction.reference,\n shouldSaveInstrument,\n },\n };\n }\n\n private async getBoltEmbeddedPaymentPayload(\n methodId: string,\n paymentData: WithAccountCreation,\n ): Promise {\n if (!isWithAccountCreation(paymentData)) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n const tokenizeResult = this.validateTokenizeResultOrThrow(\n await this.embeddedField?.tokenize(),\n );\n\n return {\n methodId,\n paymentData: {\n formattedPayload: {\n credit_card_token: {\n token: tokenizeResult.token,\n last_four_digits: tokenizeResult.last4,\n iin: tokenizeResult.bin,\n expiration_month: +tokenizeResult.expiration.split('-')[1],\n expiration_year: +tokenizeResult.expiration.split('-')[0],\n },\n provider_data: {\n create_account: !!paymentData.shouldCreateAccount,\n embedded_checkout: true,\n },\n },\n },\n };\n }\n\n private async getBoltFullCheckoutPaymentPayload(\n methodId: string,\n paymentData: NonceInstrument,\n ): Promise {\n await this.setBoltOrderId();\n\n const boltClient = this.getBoltClientOrThrow();\n const transactionReference = await boltClient.getTransactionReference();\n\n if (!transactionReference) {\n throw new PaymentMethodInvalidError();\n }\n\n return {\n methodId,\n paymentData: {\n ...paymentData,\n nonce: transactionReference,\n },\n };\n }\n\n private getBoltClientOrThrow(): BoltCheckout {\n if (!this.boltClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.boltClient;\n }\n\n private getBoltEmbeddedOrThrow() {\n if (!this.boltEmbedded) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.boltEmbedded;\n }\n\n private async hasBoltAccount(): Promise {\n const state = this.paymentIntegrationService.getState();\n const customer = state.getCustomer();\n const billingAddress = state.getBillingAddress();\n const email = customer?.email || billingAddress?.email || '';\n const boltClient = this.getBoltClientOrThrow();\n\n try {\n return await boltClient.hasBoltAccount(email);\n } catch {\n throw new PaymentMethodInvalidError();\n }\n }\n\n private async setBoltOrderId() {\n const order = this.paymentIntegrationService.getState().getOrderOrThrow();\n const boltClient = this.getBoltClientOrThrow();\n\n try {\n await boltClient.setOrderId(order.orderId);\n } catch {\n throw new PaymentMethodInvalidError();\n }\n }\n\n private mountBoltEmbeddedField(containerId: string) {\n const boltEmbedded = this.getBoltEmbeddedOrThrow();\n const styles = { backgroundColor: '#fff' };\n const embeddedField = boltEmbedded.create('payment_field', {\n styles,\n renderSeparateFields: true,\n });\n\n embeddedField.mount(`#${containerId}`);\n\n this.embeddedField = embeddedField;\n }\n\n private validateTokenizeResultOrThrow(\n tokenizeResult?: BoltEmbeddedTokenize | Error,\n ): BoltEmbeddedTokenize {\n if (!tokenizeResult) {\n throw new PaymentMethodInvalidError();\n }\n\n if (tokenizeResult instanceof Error) {\n throw new BoltError(tokenizeResult.message);\n }\n\n const { token, last4, bin, expiration } = tokenizeResult;\n const lastFourDigits = +last4;\n const iin = +bin;\n const expirationMonth = +`${expiration}`.split('-')[1];\n const expirationYear = +`${expiration}`.split('-')[0];\n\n if (\n !token ||\n Number.isNaN(lastFourDigits) ||\n Number.isNaN(iin) ||\n Number.isNaN(expirationMonth) ||\n Number.isNaN(expirationYear)\n ) {\n throw new PaymentArgumentInvalidError();\n }\n\n return tokenizeResult;\n }\n\n private setExtraItemsForAnalytics() {\n const state = this.paymentIntegrationService.getState();\n const storeConfig = state.getStoreConfigOrThrow();\n const cart = state.getCartOrThrow();\n\n if (storeConfig.checkoutSettings.isAnalyticsEnabled && isAnalyticsTrackerWindow(window)) {\n const { id, lineItems } = cart;\n\n this.analyticsExtraItemsManager.saveExtraItemsData(id, lineItems);\n }\n }\n}\n","import { isObject } from 'lodash';\n\nimport { isWithAccountCreation } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BoltPaymentData } from './bolt';\n\nexport function isBoltPaymentData(paymentData: unknown): paymentData is BoltPaymentData {\n return Boolean(\n isObject(paymentData) &&\n ('shouldSaveInstrument' in paymentData ||\n 'nonce' in paymentData ||\n isWithAccountCreation(paymentData)),\n );\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\nimport localStorageFallback from 'local-storage-fallback';\n\nimport { AnalyticsExtraItemsManager } from '@bigcommerce/checkout-sdk/analytics';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BoltPaymentStrategy from './bolt-payment-strategy';\nimport BoltScriptLoader from './bolt-script-loader';\n\nconst createBoltPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new BoltPaymentStrategy(\n paymentIntegrationService,\n new BoltScriptLoader(getScriptLoader()),\n new AnalyticsExtraItemsManager(localStorageFallback),\n );\n};\n\nexport default toResolvableModule(createBoltPaymentStrategy, [{ id: 'bolt' }]);\n","import {\n PaymentInstrument,\n WithBankAccountInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isUsBankAccountInstrumentLike(\n instrument?: PaymentInstrument,\n): instrument is WithBankAccountInstrument {\n if (!instrument) {\n return false;\n }\n\n return (\n 'accountNumber' in instrument &&\n 'routingNumber' in instrument &&\n 'ownershipType' in instrument &&\n 'accountType' in instrument\n );\n}\n","import {\n InvalidArgumentError,\n isHostedInstrumentLike,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStrategy,\n WithBankAccountInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BankAccountSuccessPayload, BraintreeBankAccount } from '../braintree';\nimport BraintreeIntegrationService from '../braintree-integration-service';\nimport isBraintreeError from '../is-braintree-error';\nimport isUsBankAccountInstrumentLike from '../is-us-bank-account-instrument-like';\n\nimport { WithBraintreePaypalAchPaymentInitializeOptions } from './braintree-paypal-ach-initialize-options';\n\nexport default class BraintreePaypalAchPaymentStrategy implements PaymentStrategy {\n private usBankAccount?: BraintreeBankAccount;\n private getMandateText?: () => string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeIntegrationService: BraintreeIntegrationService,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreePaypalAchPaymentInitializeOptions,\n ): Promise {\n const { getMandateText } = options.braintreeach || {};\n\n if (!options.methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n this.getMandateText = getMandateText;\n\n await this.paymentIntegrationService.loadPaymentMethod(options.methodId);\n\n const state = this.paymentIntegrationService.getState();\n\n const paymentMethod = state.getPaymentMethodOrThrow(options.methodId);\n\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n try {\n this.braintreeIntegrationService.initialize(paymentMethod.clientToken);\n this.usBankAccount = await this.braintreeIntegrationService.getUsBankAccount();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n async execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const isSubmittingWithVaultingInstrument = isVaultedInstrument(payment.paymentData || {});\n\n const nonce = isSubmittingWithVaultingInstrument\n ? await this.tokenizePaymentForVaultedInstrument(payment)\n : await this.tokenizePayment(payment);\n\n const submitPaymentPayload = isSubmittingWithVaultingInstrument\n ? await this.preparePaymentDataForVaultedInstrument(nonce, payment)\n : await this.preparePaymentData(nonce, payment);\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paymentIntegrationService.submitPayment(submitPaymentPayload);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n this.getMandateText = undefined;\n\n return Promise.resolve();\n }\n\n private async preparePaymentData(\n nonce: string | null,\n payment: OrderPaymentRequestBody,\n ): Promise {\n const { paymentData = {} } = payment;\n\n if (!isUsBankAccountInstrumentLike(paymentData)) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const sessionId = await this.braintreeIntegrationService.getSessionId();\n\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument, routingNumber, accountNumber } =\n paymentData;\n\n const paymentPayload = {\n formattedPayload: {\n vault_payment_instrument: shouldSaveInstrument || null,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n device_info: sessionId || null,\n tokenized_bank_account: {\n issuer: routingNumber,\n masked_account_number: accountNumber.substr(-4),\n token: nonce,\n },\n },\n };\n\n return {\n methodId: payment.methodId,\n paymentData: paymentPayload,\n };\n }\n\n private async preparePaymentDataForVaultedInstrument(\n nonce: string | null,\n payment: OrderPaymentRequestBody,\n ): Promise {\n const { paymentData = {} } = payment;\n\n if (!isVaultedInstrument(paymentData) || !isHostedInstrumentLike(paymentData)) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const sessionId = await this.braintreeIntegrationService.getSessionId();\n\n return {\n methodId: payment.methodId,\n paymentData: {\n deviceSessionId: sessionId,\n instrumentId: paymentData.instrumentId,\n shouldSetAsDefaultInstrument: paymentData.shouldSetAsDefaultInstrument,\n ...(nonce && { nonce }),\n },\n };\n }\n\n private async tokenizePayment({ paymentData }: OrderPaymentRequestBody): Promise {\n const usBankAccount = this.getUsBankAccountOrThrow();\n\n if (!isUsBankAccountInstrumentLike(paymentData)) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const mandateText = isVaultedInstrument(paymentData)\n ? 'The data are used for stored instrument verification'\n : typeof this.getMandateText === 'function' && this.getMandateText();\n\n if (!mandateText) {\n throw new InvalidArgumentError(\n 'Unable to proceed because getMandateText is not provided or returned undefined value.',\n );\n }\n\n try {\n const { nonce } = await usBankAccount.tokenize({\n bankDetails: this.getBankDetails(paymentData),\n mandateText,\n });\n\n return nonce;\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async tokenizePaymentForVaultedInstrument(\n payment: OrderPaymentRequestBody,\n ): Promise {\n const { methodId, paymentData = {} } = payment;\n\n const state = this.paymentIntegrationService.getState();\n const { config } = state.getPaymentMethodOrThrow(methodId);\n\n if (!config.isVaultingEnabled) {\n throw new InvalidArgumentError(\n 'Vaulting is disabled but a vaulted instrument was being used for this transaction',\n );\n }\n\n const shouldVerifyVaultingInstrument = isUsBankAccountInstrumentLike(paymentData);\n\n return shouldVerifyVaultingInstrument ? this.tokenizePayment(payment) : null;\n }\n\n private getBankDetails(paymentData: WithBankAccountInstrument): BankAccountSuccessPayload {\n const state = this.paymentIntegrationService.getState();\n const billingAddress = state.getBillingAddressOrThrow();\n\n const ownershipType = paymentData.ownershipType.toLowerCase();\n const accountType = paymentData.accountType.toLowerCase();\n\n return {\n accountNumber: paymentData.accountNumber,\n routingNumber: paymentData.routingNumber,\n ownershipType,\n ...(ownershipType === 'personal'\n ? {\n firstName: paymentData.firstName,\n lastName: paymentData.lastName,\n }\n : {\n businessName: paymentData.businessName,\n }),\n accountType,\n billingAddress: {\n streetAddress: billingAddress.address1,\n extendedAddress: billingAddress.address2,\n locality: billingAddress.city,\n region: billingAddress.stateOrProvinceCode,\n postalCode: billingAddress.postalCode,\n },\n };\n }\n\n private getUsBankAccountOrThrow(): BraintreeBankAccount {\n if (!this.usBankAccount) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.usBankAccount;\n }\n\n private handleError(error: unknown): never {\n if (!isBraintreeError(error)) {\n throw error;\n }\n\n throw new PaymentMethodFailedError(error.message);\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BraintreeHostWindow } from '../braintree';\nimport BraintreeIntegrationService from '../braintree-integration-service';\nimport BraintreeScriptLoader from '../braintree-script-loader';\n\nimport BraintreeAchPaymentStrategy from './braintree-paypal-ach-payment-strategy';\n\nconst createBraintreePaypalAchPaymentStrategy: PaymentStrategyFactory<\n BraintreeAchPaymentStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n braintreeHostWindow,\n );\n\n return new BraintreeAchPaymentStrategy(paymentIntegrationService, braintreeIntegrationService);\n};\n\nexport default toResolvableModule(createBraintreePaypalAchPaymentStrategy, [\n { id: 'braintreeach' },\n]);\n","import {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport BraintreeIntegrationService from '../braintree-integration-service';\nimport {\n BraintreeLocalMethods,\n LocalPaymentInstance,\n LocalPaymentsPayload,\n onPaymentStartData,\n StartPaymentError,\n WithBraintreeLocalMethodsPaymentInitializeOptions,\n} from './braintree-local-methods-options';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nexport default class BraintreeLocalMethodsPaymentStrategy implements PaymentStrategy {\n private orderId?: string;\n private localPaymentInstance?: LocalPaymentInstance;\n private braintreeLocalMethods?: BraintreeLocalMethods;\n private loadingIndicatorContainer?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeIntegrationService: BraintreeIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreeLocalMethodsPaymentInitializeOptions,\n ): Promise {\n const { gatewayId, methodId, braintreelocalmethods } = options;\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.gatewayId\" argument is not provided.',\n );\n }\n\n if (!braintreelocalmethods) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreelocalmethods\" argument is not provided.`,\n );\n }\n\n this.braintreeLocalMethods = braintreelocalmethods;\n\n this.loadingIndicatorContainer = braintreelocalmethods.container.split('#')[1];\n\n await this.paymentIntegrationService.loadPaymentMethod(gatewayId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(gatewayId);\n const { merchantId } = paymentMethod.config;\n\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n try {\n this.braintreeIntegrationService.initialize(paymentMethod.clientToken);\n await this.braintreeIntegrationService.loadBraintreeLocalMethods(\n this.getLocalPaymentInstance.bind(this),\n merchantId || '',\n );\n } catch (error: unknown) {\n this.handleError(error);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n this.orderId = undefined;\n this.toggleLoadingIndicator(false);\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const sessionId = await this.braintreeIntegrationService.getSessionId();\n const billing = state.getBillingAddressOrThrow();\n const { firstName, lastName, countryCode } = billing;\n const { baseAmount, currency, email, lineItems } = cart;\n const isShippingRequired = lineItems.physicalItems.length > 0;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n this.toggleLoadingIndicator(true);\n\n if (!this.localPaymentInstance) {\n throw new PaymentMethodInvalidError();\n }\n\n return new Promise((resolve, reject) => {\n this.localPaymentInstance?.startPayment(\n {\n paymentType: payment.methodId,\n amount: baseAmount,\n fallback: {\n url: 'url-placeholder',\n buttonText: 'button placeholder',\n },\n currencyCode: currency.code,\n shippingAddressRequired: isShippingRequired,\n email,\n givenName: firstName,\n surname: lastName,\n address: {\n countryCode,\n },\n onPaymentStart: (data: onPaymentStartData, start: () => void) => {\n // Call start to initiate the popup\n this.orderId = data.paymentId;\n start();\n },\n },\n async (\n startPaymentError: StartPaymentError | null,\n payloadData: LocalPaymentsPayload,\n ) => {\n if (startPaymentError) {\n if (startPaymentError.code !== 'LOCAL_PAYMENT_WINDOW_CLOSED') {\n reject(() => this.handleError(startPaymentError));\n }\n this.toggleLoadingIndicator(false);\n reject();\n } else {\n if (!this.orderId) {\n throw PaymentMethodInvalidError;\n }\n\n const paymentData = {\n formattedPayload: {\n device_info: sessionId || null,\n method: payment.methodId,\n [`${payment.methodId}_account`]: {\n email: cart.email,\n token: payloadData.nonce,\n order_id: this.orderId,\n },\n vault_payment_instrument: null,\n set_as_default_stored_instrument: null,\n },\n };\n\n try {\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paymentIntegrationService.submitPayment({\n methodId: payment.methodId,\n paymentData,\n });\n resolve();\n } catch (error: unknown) {\n reject(() => this.handleError(error));\n }\n }\n },\n );\n });\n }\n\n private getLocalPaymentInstance(localPaymentInstance: LocalPaymentInstance) {\n if (!this.localPaymentInstance) {\n this.localPaymentInstance = localPaymentInstance;\n }\n }\n\n /**\n *\n * Loading Indicator methods\n *\n * */\n private toggleLoadingIndicator(isLoading: boolean): void {\n if (isLoading && this.loadingIndicatorContainer) {\n this.loadingIndicator.show(this.loadingIndicatorContainer);\n } else {\n this.loadingIndicator.hide();\n }\n }\n\n private handleError(error: unknown) {\n const { onError } = this.braintreeLocalMethods || {};\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n}\n","import { LoadingIndicatorStyles } from './loading-indicator-styles';\n\nconst DEFAULT_STYLES: LoadingIndicatorStyles = {\n size: 70,\n color: '#d9d9d9',\n backgroundColor: '#ffffff',\n};\n\nconst ROTATION_ANIMATION = 'embedded-checkout-loading-indicator-rotation';\n\nexport default class LoadingIndicator {\n private container: HTMLElement;\n private indicator: HTMLElement;\n private styles: LoadingIndicatorStyles;\n\n constructor(options?: { styles?: LoadingIndicatorStyles }) {\n this.styles = { ...DEFAULT_STYLES, ...(options && options.styles) };\n\n this.defineAnimation();\n\n this.container = this.buildContainer();\n this.indicator = this.buildIndicator();\n\n this.container.appendChild(this.indicator);\n }\n\n show(parentId?: string): void {\n if (parentId) {\n const parent = document.getElementById(parentId);\n\n if (!parent) {\n throw new Error(\n 'Unable to attach the loading indicator because the parent ID is not valid.',\n );\n }\n\n parent.appendChild(this.container);\n }\n\n this.container.style.visibility = 'visible';\n this.container.style.opacity = '1';\n }\n\n hide(): void {\n const handleTransitionEnd = () => {\n this.container.style.visibility = 'hidden';\n\n this.container.removeEventListener('transitionend', handleTransitionEnd);\n };\n\n this.container.addEventListener('transitionend', handleTransitionEnd);\n\n this.container.style.opacity = '0';\n }\n\n private buildContainer(): HTMLElement {\n const container = document.createElement('div');\n\n container.style.display = 'block';\n container.style.bottom = '0';\n container.style.left = '0';\n container.style.height = '100%';\n container.style.width = '100%';\n container.style.position = 'absolute';\n container.style.right = '0';\n container.style.top = '0';\n container.style.transition = 'all 250ms ease-out';\n container.style.opacity = '0';\n\n return container;\n }\n\n private buildIndicator(): HTMLElement {\n const indicator = document.createElement('div');\n\n indicator.style.display = 'block';\n indicator.style.width = `${this.styles.size}px`;\n indicator.style.height = `${this.styles.size}px`;\n indicator.style.borderRadius = `${this.styles.size}px`;\n indicator.style.border = 'solid 1px';\n indicator.style.borderColor = `${this.styles.backgroundColor} ${this.styles.backgroundColor} ${this.styles.color} ${this.styles.color}`;\n indicator.style.margin = '0 auto';\n indicator.style.position = 'absolute';\n indicator.style.left = '0';\n indicator.style.right = '0';\n indicator.style.top = '50%';\n indicator.style.transform = 'translateY(-50%) rotate(0deg)';\n indicator.style.transformStyle = 'preserve-3d';\n indicator.style.animation = `${ROTATION_ANIMATION} 500ms infinite cubic-bezier(0.69, 0.31, 0.56, 0.83)`;\n\n return indicator;\n }\n\n private defineAnimation(): void {\n // In order to define CSS animation, we need to insert a stylesheet into the host frame.\n // We only have to do it once.\n if (document.getElementById(ROTATION_ANIMATION)) {\n return;\n }\n\n const style = document.createElement('style');\n\n style.id = ROTATION_ANIMATION;\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n document.head?.appendChild(style);\n\n if (style.sheet instanceof CSSStyleSheet) {\n // We need to provide the 2nd parameter for IE11, even though it is\n // 0 by default for all other browsers.\n style.sheet.insertRule(\n `\n @keyframes ${ROTATION_ANIMATION} {\n 0% { transform: translateY(-50%) rotate(0deg); }\n 100% { transform: translateY(-50%) rotate(360deg); }\n }\n `,\n 0,\n );\n }\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeLocalMethodsPaymentStrategy from './braintree-local-methods-payment-strategy';\nimport { BraintreeHostWindow } from '../braintree';\nimport BraintreeIntegrationService from '../braintree-integration-service';\nimport BraintreeScriptLoader from '../braintree-script-loader';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nconst createBraintreeLocalMethodsPaymentStrategy: PaymentStrategyFactory<\n BraintreeLocalMethodsPaymentStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n braintreeHostWindow,\n );\n\n return new BraintreeLocalMethodsPaymentStrategy(\n paymentIntegrationService,\n braintreeIntegrationService,\n new LoadingIndicator({ styles: { backgroundColor: 'black' } }),\n );\n};\n\nexport default toResolvableModule(createBraintreeLocalMethodsPaymentStrategy, [\n { gateway: 'braintreelocalmethods' },\n]);\n","import { isNil, values } from 'lodash';\n\nimport {\n HostedForm,\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithCreditCardPaymentInitializeOptions } from './credit-card-payment-initialize-options';\n\nexport default class CreditCardPaymentStrategy implements PaymentStrategy {\n protected _hostedForm?: HostedForm;\n protected _shouldRenderHostedForm?: boolean;\n\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n return this._isHostedPaymentFormEnabled(\n payload.payment?.methodId,\n payload.payment?.gatewayId,\n ) && this._shouldRenderHostedForm\n ? this._executeWithHostedForm(payload, options)\n : this._executeWithoutHostedForm(payload, options);\n }\n\n initialize(\n options?: PaymentInitializeOptions & WithCreditCardPaymentInitializeOptions,\n ): Promise {\n if (\n !this._isHostedPaymentFormEnabled(options?.methodId, options?.gatewayId) ||\n !this._isHostedFieldAvailable(options)\n ) {\n this._shouldRenderHostedForm = false;\n\n return Promise.resolve();\n }\n\n const formOptions = options && options.creditCard && options.creditCard.form;\n const state = this._paymentIntegrationService.getState();\n const { paymentSettings: { bigpayBaseUrl: host = '' } = {} } =\n state.getStoreConfigOrThrow();\n\n if (!formOptions) {\n throw new InvalidArgumentError();\n }\n\n const form = this._paymentIntegrationService.createHostedForm(host, formOptions);\n\n return form.attach().then(() => {\n this._shouldRenderHostedForm = true;\n this._hostedForm = form;\n\n return Promise.resolve();\n });\n }\n\n deinitialize(): Promise {\n if (this._hostedForm) {\n this._hostedForm.detach();\n }\n\n return Promise.resolve();\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n protected async _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment && payment.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n await this._paymentIntegrationService.submitPayment({ ...payment, paymentData });\n }\n\n protected async _executeWithHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!payment || !payment.methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n await form.validate().then(() => form.submit(payment));\n }\n\n protected _isHostedPaymentFormEnabled(methodId?: string, gatewayId?: string): boolean {\n if (!methodId) {\n return false;\n }\n\n const state = this._paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId, gatewayId);\n\n return paymentMethod.config.isHostedFormEnabled === true;\n }\n\n private _isHostedFieldAvailable(\n options?: PaymentInitializeOptions & WithCreditCardPaymentInitializeOptions,\n ): boolean {\n return !values(options && options.creditCard && options.creditCard.form.fields).every(\n isNil,\n );\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CreditCardPaymentStrategy from './credit-card-payment-strategy';\n\nconst createCreditCardPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new CreditCardPaymentStrategy(paymentIntegrationService);\n};\n\nexport default toResolvableModule(createCreditCardPaymentStrategy, [{ default: true }]);\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n isRequestError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { AdditionalActionRequired, isAdditionalActionRequired } from './is-additional-action';\n\nexport default class ExternalPaymentStrategy implements PaymentStrategy {\n constructor(\n private _formPoster: FormPoster,\n private _paymentIntegrationService: PaymentIntegrationService,\n ) {}\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment && payment.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n try {\n await this._paymentIntegrationService.submitPayment({ ...payment, paymentData });\n } catch (error) {\n if (\n !isRequestError(error) ||\n !isAdditionalActionRequired(error.body) ||\n !this._isAdditionalActionRequired(error.body)\n ) {\n return Promise.reject(error);\n }\n\n const {\n body: {\n additional_action_required: {\n data: { redirect_url },\n },\n },\n } = error;\n\n return new Promise(() => this.redirectUrl(redirect_url));\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n protected redirectUrl(redirect_url: string): void {\n return this._formPoster.postForm(redirect_url, {});\n }\n\n private _isAdditionalActionRequired(body: AdditionalActionRequired): boolean {\n const { additional_action_required, status } = body;\n\n return (\n status === 'additional_action_required' &&\n additional_action_required &&\n additional_action_required.type === 'offsite_redirect'\n );\n }\n}\n","export interface AdditionalActionRequired {\n additional_action_required: {\n data: {\n redirect_url: string;\n };\n type: string;\n };\n status: string;\n}\n\nexport function isAdditionalActionRequired(value: unknown): value is AdditionalActionRequired {\n return typeof value === 'object' && value !== null && 'additional_action_required' in value;\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ExternalPaymentStrategy from './external-payment-strategy';\n\nconst createExternalPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => new ExternalPaymentStrategy(createFormPoster(), paymentIntegrationService);\n\nexport default toResolvableModule(createExternalPaymentStrategy, [{ id: 'laybuy' }]);\n","import {\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class LegacyPaymentStrategy implements PaymentStrategy {\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n await this._paymentIntegrationService.submitOrder(payload, options);\n\n return Promise.resolve();\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport LegacyPaymentStrategy from './legacy-payment-strategy';\n\nconst createLegacyPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => new LegacyPaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createLegacyPaymentStrategy, [{ id: 'testgateway' }]);\n","import { omit } from 'lodash';\n\nimport {\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class NoPaymentDataRequiredPaymentStrategy implements PaymentStrategy {\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n await this._paymentIntegrationService.submitOrder(omit(payload, 'payment'), options);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport NoPaymentDataRequiredPaymentStrategy from './no-payment-data-required-strategy';\n\nconst createNoPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => new NoPaymentDataRequiredPaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createNoPaymentStrategy, [{ id: 'nopaymentdatarequired' }]);\n","import {\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class OfflinePaymentStrategy implements PaymentStrategy {\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n await this._paymentIntegrationService.submitOrder(\n {\n ...payload,\n payment: payload.payment ? { methodId: payload.payment.methodId } : undefined,\n },\n options,\n );\n\n return Promise.resolve();\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport OfflinePaymentStrategy from './offline-payment-strategy';\n\nconst createOfflinePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => new OfflinePaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createOfflinePaymentStrategy, [{ type: 'PAYMENT_TYPE_OFFLINE' }]);\n","enum PaymentStatusTypes {\n ACKNOWLEDGE = 'ACKNOWLEDGE',\n FINALIZE = 'FINALIZE',\n INITIALIZE = 'INITIALIZE',\n}\n\nexport default PaymentStatusTypes;\n","import {\n isHostedInstrumentLike,\n isVaultedInstrument,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStatusTypes,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class OffsitePaymentStrategy implements PaymentStrategy {\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const orderPayload = this._shouldSubmitFullPayload(payment) ? payload : order;\n const paymentData = payment && payment.paymentData;\n const instrumentId =\n (paymentData && isVaultedInstrument(paymentData) && paymentData.instrumentId) ||\n undefined;\n const shouldSaveInstrument =\n (paymentData &&\n isHostedInstrumentLike(paymentData) &&\n paymentData.shouldSaveInstrument) ||\n undefined;\n const shouldSetAsDefaultInstrument =\n (paymentData &&\n isHostedInstrumentLike(paymentData) &&\n paymentData.shouldSetAsDefaultInstrument) ||\n undefined;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId, gatewayId } = payment;\n\n await this._paymentIntegrationService.submitOrder(orderPayload, options);\n await this._paymentIntegrationService.initializeOffsitePayment({\n methodId,\n gatewayId,\n instrumentId,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n });\n }\n\n async finalize(options?: PaymentRequestOptions): Promise {\n const state = this._paymentIntegrationService.getState();\n const order = state.getOrder();\n const status = state.getPaymentStatus();\n\n if (\n order &&\n (status === PaymentStatusTypes.ACKNOWLEDGE || status === PaymentStatusTypes.FINALIZE)\n ) {\n await this._paymentIntegrationService.finalizeOrder(options);\n\n return;\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private _shouldSubmitFullPayload(payment?: OrderPaymentRequestBody): boolean {\n // FIXME: A temporary workaround to support offsite payment methods\n // where their return URL needs to be provided by the core app.\n if (!payment) {\n return false;\n }\n\n return (\n payment.gatewayId === 'adyen' ||\n payment.gatewayId === 'barclaycard' ||\n payment.methodId === 'ccavenuemars'\n );\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport OffsitePaymentStrategy from './offsite-payment-strategy';\n\nconst createOffsitePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => new OffsitePaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createOffsitePaymentStrategy, [{ type: 'PAYMENT_TYPE_HOSTED' }]);\n","import {\n InvalidArgumentError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n ClickCallbackActions,\n PayPalCommerceButtons,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n} from '../paypal-commerce-types';\n\nimport PayPalCommercePaymentInitializeOptions, {\n WithPayPalCommercePaymentInitializeOptions,\n} from './paypal-commerce-payment-initialize-options';\n\nexport default class PayPalCommercePaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: PayPalCommerceButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithPayPalCommercePaymentInitializeOptions,\n ): Promise {\n const { methodId, paypalcommerce } = options || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!paypalcommerce) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerce\" argument is not provided.`,\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n // Info:\n // The PayPal button and fields should not be rendered when shopper was redirected to Checkout page\n // after using smart payment button on PDP or Cart page. In this case backend returns order id if\n // it is available in checkout session. Therefore, it is not necessary to render PayPal button.\n if (paymentMethod.initializationData?.orderId) {\n this.orderId = paymentMethod.initializationData?.orderId;\n\n return;\n }\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.loadingIndicatorContainer = paypalcommerce.container.split('#')[1];\n\n this.renderButton(methodId, paypalcommerce);\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!this.orderId) {\n throw new PaymentMethodInvalidError();\n }\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paypalCommerceIntegrationService.submitPayment(payment.methodId, this.orderId);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.orderId = undefined;\n\n this.paypalButton?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Button methods/callbacks\n *\n * */\n private renderButton(\n methodId: string,\n paypalcommerce: PayPalCommercePaymentInitializeOptions,\n ): void {\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { buttonStyle } = paymentMethod.initializationData || {};\n\n const { container, onError, onRenderButton, onValidate, submitForm } = paypalcommerce;\n\n const buttonOptions: PayPalCommerceButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(buttonStyle),\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder('paypalcommercecheckout'),\n onClick: (_, actions) => this.handleClick(actions, onValidate),\n onApprove: (data) => this.handleApprove(data, submitForm),\n onCancel: () => this.toggleLoadingIndicator(false),\n onError: (error) => this.handleError(error, onError),\n };\n\n this.paypalButton = paypalSdk.Buttons(buttonOptions);\n\n if (!this.paypalButton.isEligible()) {\n return;\n }\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n this.paypalButton.render(container);\n }\n\n private async handleClick(\n actions: ClickCallbackActions,\n onValidate: PayPalCommercePaymentInitializeOptions['onValidate'],\n ): Promise {\n const { resolve, reject } = actions;\n\n const onValidationPassed = () => {\n this.toggleLoadingIndicator(true);\n\n return resolve();\n };\n\n await onValidate(onValidationPassed, reject);\n }\n\n private handleApprove(\n { orderID }: ApproveCallbackPayload,\n submitForm: PayPalCommercePaymentInitializeOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n submitForm();\n this.toggleLoadingIndicator(false);\n }\n\n private handleError(\n error: Error,\n onError: PayPalCommercePaymentInitializeOptions['onError'],\n ): void {\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n\n /**\n *\n * Loading Indicator methods\n *\n * */\n private toggleLoadingIndicator(isLoading: boolean): void {\n if (isLoading && this.loadingIndicatorContainer) {\n this.loadingIndicator.show(this.loadingIndicatorContainer);\n } else {\n this.loadingIndicator.hide();\n }\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommercePaymentStrategy from './paypal-commerce-payment-strategy';\n\nconst createPayPalCommercePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) =>\n new PayPalCommercePaymentStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n new LoadingIndicator({ styles: { backgroundColor: 'black' } }),\n );\n\nexport default toResolvableModule(createPayPalCommercePaymentStrategy, [{ id: 'paypalcommerce' }]);\n","import {\n InvalidArgumentError,\n NotImplementedError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n ClickCallbackActions,\n PayPalCommerceButtons,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceCreditPaymentInitializeOptions, {\n WithPayPalCommerceCreditPaymentInitializeOptions,\n} from './paypal-commerce-credit-payment-initialize-options';\n\nexport default class PayPalCommerceCreditPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: PayPalCommerceButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithPayPalCommerceCreditPaymentInitializeOptions,\n ): Promise {\n const { methodId, paypalcommerce, paypalcommercecredit } = options || {};\n\n const paypalOptions = paypalcommercecredit || paypalcommerce;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (paypalcommerce) {\n console.warn(\n 'The \"options.paypalcommerce\" option is deprecated for this strategy, please use \"options.paypalcommercevenmo\" instead',\n );\n }\n\n if (!paypalOptions) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerce\" argument is not provided.`,\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n // Info:\n // The PayPal button and fields should not be rendered when shopper was redirected to Checkout page\n // after using smart payment button on PDP or Cart page. In this case backend returns order id if\n // it is available in checkout session. Therefore, it is not necessary to render PayPal button.\n if (paymentMethod.initializationData?.orderId) {\n this.orderId = paymentMethod.initializationData?.orderId;\n\n return;\n }\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.loadingIndicatorContainer = paypalOptions.container.split('#')[1];\n\n this.renderButton(methodId, paypalOptions);\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!this.orderId) {\n throw new PaymentMethodInvalidError();\n }\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paypalCommerceIntegrationService.submitPayment(payment.methodId, this.orderId);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.orderId = undefined;\n\n this.paypalButton?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Button methods/callbacks\n *\n * */\n private renderButton(\n methodId: string,\n paypalOptions: PayPalCommerceCreditPaymentInitializeOptions,\n ): void {\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { buttonStyle } = paymentMethod.initializationData || {};\n\n const { container, onError, onRenderButton, onValidate, submitForm } = paypalOptions;\n\n const fundingSources = [paypalSdk.FUNDING.PAYLATER, paypalSdk.FUNDING.CREDIT];\n let hasRenderedSmartButton = false;\n\n fundingSources.forEach((fundingSource) => {\n if (hasRenderedSmartButton) {\n return;\n }\n\n const buttonOptions: PayPalCommerceButtonsOptions = {\n fundingSource,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(buttonStyle),\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder(\n 'paypalcommercecreditcheckout',\n ),\n onClick: (_, actions) => this.handleClick(actions, onValidate),\n onApprove: (data) => this.handleApprove(data, submitForm),\n onCancel: () => this.toggleLoadingIndicator(false),\n onError: (error) => this.handleError(error, onError),\n };\n\n this.paypalButton = paypalSdk.Buttons(buttonOptions);\n\n if (!this.paypalButton.isEligible() && fundingSource === paypalSdk.FUNDING.PAYLATER) {\n return;\n }\n\n if (!this.paypalButton.isEligible() && fundingSource === paypalSdk.FUNDING.CREDIT) {\n throw new NotImplementedError(\n `PayPal ${fundingSource} is not available for your region. Please use PayPal Checkout instead.`,\n );\n }\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n this.paypalButton.render(container);\n hasRenderedSmartButton = true;\n });\n }\n\n private async handleClick(\n actions: ClickCallbackActions,\n onValidate: PayPalCommerceCreditPaymentInitializeOptions['onValidate'],\n ): Promise {\n const { resolve, reject } = actions;\n\n const onValidationPassed = () => {\n this.toggleLoadingIndicator(true);\n\n return resolve();\n };\n\n await onValidate(onValidationPassed, reject);\n }\n\n private handleApprove(\n { orderID }: ApproveCallbackPayload,\n submitForm: PayPalCommerceCreditPaymentInitializeOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n submitForm();\n this.toggleLoadingIndicator(false);\n }\n\n private handleError(\n error: Error,\n onError: PayPalCommerceCreditPaymentInitializeOptions['onError'],\n ): void {\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n\n /**\n *\n * Loading Indicator methods\n *\n * */\n private toggleLoadingIndicator(isLoading: boolean): void {\n if (isLoading && this.loadingIndicatorContainer) {\n this.loadingIndicator.show(this.loadingIndicatorContainer);\n } else {\n this.loadingIndicator.hide();\n }\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceCreditPaymentStrategy from './paypal-commerce-credit-payment-strategy';\n\nconst createPayPalCommerceCreditPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceCreditPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditPaymentStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n new LoadingIndicator({ styles: { backgroundColor: 'black' } }),\n );\n\nexport default toResolvableModule(createPayPalCommerceCreditPaymentStrategy, [\n { id: 'paypalcommercecredit' },\n]);\n","import {\n InvalidArgumentError,\n NotImplementedError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n ClickCallbackActions,\n PayPalCommerceButtons,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceVenmoPaymentInitializeOptions, {\n WithPayPalCommerceVenmoPaymentInitializeOptions,\n} from './paypal-commerce-venmo-payment-initialize-options';\n\nexport default class PayPalCommerceVenmoPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: PayPalCommerceButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithPayPalCommerceVenmoPaymentInitializeOptions,\n ): Promise {\n const { methodId, paypalcommerce, paypalcommercevenmo } = options || {};\n\n const paypalOptions = paypalcommercevenmo || paypalcommerce;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (paypalcommerce) {\n console.warn(\n 'The \"options.paypalcommerce\" option is deprecated for this strategy, please use \"options.paypalcommercevenmo\" instead',\n );\n }\n\n if (!paypalOptions) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercevenmo\" argument is not provided.`,\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n // Info:\n // The PayPal button and fields should not be rendered when shopper was redirected to Checkout page\n // after using smart payment button on PDP or Cart page. In this case backend returns order id if\n // it is available in checkout session. Therefore, it is not necessary to render PayPal button.\n if (paymentMethod.initializationData?.orderId) {\n this.orderId = paymentMethod.initializationData?.orderId;\n\n return;\n }\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.loadingIndicatorContainer = paypalOptions.container.split('#')[1];\n\n this.renderButton(methodId, paypalOptions);\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!this.orderId) {\n throw new PaymentMethodInvalidError();\n }\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paypalCommerceIntegrationService.submitPayment(payment.methodId, this.orderId);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.orderId = undefined;\n\n this.paypalButton?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Button methods/callbacks\n *\n * */\n private renderButton(\n methodId: string,\n paypalcommercevenmo: PayPalCommerceVenmoPaymentInitializeOptions,\n ): void {\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { buttonStyle } = paymentMethod.initializationData || {};\n\n const { container, onError, onRenderButton, onValidate, submitForm } = paypalcommercevenmo;\n\n const buttonOptions: PayPalCommerceButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.VENMO,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(buttonStyle),\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder('paypalcommercevenmocheckout'),\n onClick: (_, actions) => this.handleClick(actions, onValidate),\n onApprove: (data) => this.handleApprove(data, submitForm),\n onCancel: () => this.toggleLoadingIndicator(false),\n onError: (error) => this.handleError(error, onError),\n };\n\n this.paypalButton = paypalSdk.Buttons(buttonOptions);\n\n if (!this.paypalButton.isEligible()) {\n throw new NotImplementedError(\n `PayPal Venmo is not available for your region. Please use PayPal Checkout instead.`,\n );\n }\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n this.paypalButton.render(container);\n }\n\n private async handleClick(\n actions: ClickCallbackActions,\n onValidate: PayPalCommerceVenmoPaymentInitializeOptions['onValidate'],\n ): Promise {\n const { resolve, reject } = actions;\n\n const onValidationPassed = () => {\n this.toggleLoadingIndicator(true);\n\n return resolve();\n };\n\n await onValidate(onValidationPassed, reject);\n }\n\n private handleApprove(\n { orderID }: ApproveCallbackPayload,\n submitForm: PayPalCommerceVenmoPaymentInitializeOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n submitForm();\n this.toggleLoadingIndicator(false);\n }\n\n private handleError(\n error: Error,\n onError: PayPalCommerceVenmoPaymentInitializeOptions['onError'],\n ): void {\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n\n /**\n *\n * Loading Indicator methods\n *\n * */\n private toggleLoadingIndicator(isLoading: boolean): void {\n if (isLoading && this.loadingIndicatorContainer) {\n this.loadingIndicator.show(this.loadingIndicatorContainer);\n } else {\n this.loadingIndicator.hide();\n }\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceVenmoPaymentStrategy from './paypal-commerce-venmo-payment-strategy';\n\nconst createPayPalCommerceVenmoPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceVenmoPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceVenmoPaymentStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n new LoadingIndicator({ styles: { backgroundColor: 'black' } }),\n );\n\nexport default toResolvableModule(createPayPalCommerceVenmoPaymentStrategy, [\n { id: 'paypalcommercevenmo' },\n]);\n","import { Response } from '@bigcommerce/request-sender';\n\nimport RequestError from './request-error';\n\n/**\n * Throw this error if a request fails to complete within its required timeframe\n * because of a network issue.\n */\nexport default class TimeoutError extends RequestError {\n constructor(response?: Response) {\n super(response, {\n message: 'The request has timed out or aborted.',\n });\n\n this.name = 'TimeoutError';\n this.type = 'timeout';\n }\n}\n","import { noop } from 'lodash';\n\nimport {\n InvalidArgumentError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n TimeoutError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n ClickCallbackActions,\n NonInstantAlternativePaymentMethods,\n PayPalCommerceButtons,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n PayPalOrderStatus,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceAlternativeMethodsPaymentOptions, {\n WithPayPalCommerceAlternativeMethodsPaymentInitializeOptions,\n} from './paypal-commerce-alternative-methods-payment-initialize-options';\n\nexport default class PayPalCommerceAlternativeMethodsPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: PayPalCommerceButtons;\n private pollingTimer = 0;\n private stopPolling = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n private loadingIndicator: LoadingIndicator,\n private pollingInterval = 3000,\n private maxPollingTime = 600000,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions &\n WithPayPalCommerceAlternativeMethodsPaymentInitializeOptions,\n ): Promise {\n const {\n gatewayId,\n methodId,\n paypalcommerce, // FIXME: this option is deprecated\n paypalcommercealternativemethods,\n } = options;\n const paypalOptions = paypalcommercealternativemethods || paypalcommerce;\n\n if (paypalcommerce) {\n console.warn(\n 'The \"options.paypalcommerce\" option is deprecated for this strategy, please use \"options.paypalcommercealternativemethods\" instead',\n );\n }\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.gatewayId\" argument is not provided.',\n );\n }\n\n if (!paypalOptions) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercealternativemethods\" argument is not provided.`,\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(\n methodId,\n gatewayId,\n );\n const { orderId, shouldRenderFields } = paymentMethod.initializationData || {};\n\n // Info:\n // The PayPal button and fields should not be rendered when shopper was redirected to Checkout page\n // after using smart payment button on PDP or Cart page. In this case backend returns order id if\n // it is available in checkout session. Therefore, it is not necessary to render PayPal button.\n if (orderId) {\n this.orderId = orderId;\n\n return;\n }\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.loadingIndicatorContainer = paypalOptions.container.split('#')[1];\n\n this.renderButton(methodId, gatewayId, paypalOptions);\n\n if (shouldRenderFields) {\n this.renderFields(methodId, paypalOptions);\n }\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!this.orderId) {\n throw new PaymentMethodInvalidError();\n }\n\n if (!this.isNonInstantPaymentMethod(payment.methodId)) {\n await this.paymentIntegrationService.submitOrder(order, options);\n }\n\n await this.paypalCommerceIntegrationService.submitPayment(payment.methodId, this.orderId);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.deinitializePollingMechanism();\n\n this.orderId = undefined;\n\n this.paypalButton?.close();\n\n return Promise.resolve();\n }\n\n private async reinitializeStrategy(\n options: PaymentInitializeOptions &\n WithPayPalCommerceAlternativeMethodsPaymentInitializeOptions,\n ): Promise {\n await this.deinitialize();\n await this.initialize(options);\n }\n\n /**\n *\n * Button methods/callbacks\n *\n * */\n private renderButton(\n methodId: string,\n gatewayId: string,\n paypalOptions: PayPalCommerceAlternativeMethodsPaymentOptions,\n ): void {\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(\n methodId,\n gatewayId,\n );\n const { buttonStyle } = paymentMethod.initializationData || {};\n\n const { container, onError, onRenderButton, submitForm } = paypalOptions;\n\n const buttonOptions: PayPalCommerceButtonsOptions = {\n fundingSource: methodId,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(buttonStyle),\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder(\n 'paypalcommercealternativemethodscheckout',\n ),\n onClick: (_, actions) => this.handleClick(methodId, gatewayId, paypalOptions, actions),\n onApprove: (data) => this.handleApprove(data, submitForm),\n onCancel: () => this.resetPollingMechanism(),\n onError: (error) => this.handleError(error, onError),\n };\n\n this.paypalButton = paypalSdk.Buttons(buttonOptions);\n\n if (!this.paypalButton.isEligible()) {\n return;\n }\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n this.paypalButton.render(container);\n }\n\n private async handleClick(\n methodId: string,\n gatewayId: string,\n paypalOptions: PayPalCommerceAlternativeMethodsPaymentOptions,\n actions: ClickCallbackActions,\n ): Promise {\n const { onValidate } = paypalOptions;\n const { resolve, reject } = actions;\n\n if (!this.isNonInstantPaymentMethod(methodId)) {\n await this.initializePollingMechanism(methodId, gatewayId, paypalOptions);\n }\n\n const onValidationPassed = () => {\n this.toggleLoadingIndicator(true);\n\n return resolve();\n };\n\n await onValidate(onValidationPassed, reject);\n }\n\n private handleApprove(\n { orderID }: ApproveCallbackPayload,\n submitForm: PayPalCommerceAlternativeMethodsPaymentOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n this.deinitializePollingMechanism();\n submitForm();\n this.toggleLoadingIndicator(false);\n }\n\n private handleError(\n error: Error,\n onError: PayPalCommerceAlternativeMethodsPaymentOptions['onError'],\n ): void {\n this.resetPollingMechanism();\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n\n /**\n *\n * Fields methods\n *\n * */\n private renderFields(\n methodId: string,\n paypalOptions: PayPalCommerceAlternativeMethodsPaymentOptions,\n ): void {\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const { firstName, lastName, email } = state.getBillingAddressOrThrow();\n\n const { apmFieldsContainer, apmFieldsStyles } = paypalOptions;\n\n if (!apmFieldsContainer) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommercealternativemethods\" argument should contain \"apmFieldsContainer\".',\n );\n }\n\n const fieldContainerElement = document.querySelector(apmFieldsContainer);\n\n if (fieldContainerElement) {\n fieldContainerElement.innerHTML = '';\n }\n\n const fieldsOptions = {\n fundingSource: methodId,\n style: apmFieldsStyles || {},\n fields: {\n name: {\n value: `${firstName} ${lastName}`,\n },\n email: {\n value: email,\n },\n },\n };\n\n const paypalPaymentFields = paypalSdk.PaymentFields(fieldsOptions);\n\n paypalPaymentFields.render(apmFieldsContainer);\n }\n\n /**\n *\n * Polling mechanism\n *\n *\n * */\n private async initializePollingMechanism(\n methodId: string,\n gatewayId: string,\n paypalOptions: PayPalCommerceAlternativeMethodsPaymentOptions,\n ): Promise {\n const { onError, submitForm } = paypalOptions;\n\n await new Promise((resolve, reject) => {\n const timeout = setTimeout(resolve, this.pollingInterval);\n\n this.stopPolling = () => {\n clearTimeout(timeout);\n reject();\n };\n });\n\n try {\n this.pollingTimer += this.pollingInterval;\n\n const orderStatus = await this.paypalCommerceIntegrationService.getOrderStatus();\n\n const isOrderApproved = orderStatus === PayPalOrderStatus.Approved;\n const isOrderPending =\n orderStatus === PayPalOrderStatus.Created ||\n orderStatus === PayPalOrderStatus.PayerActionRequired;\n\n if (isOrderApproved) {\n this.deinitializePollingMechanism();\n\n return submitForm();\n }\n\n if (isOrderPending && this.pollingTimer < this.maxPollingTime) {\n return await this.initializePollingMechanism(methodId, gatewayId, paypalOptions);\n }\n\n await this.reinitializeStrategy({\n methodId,\n gatewayId,\n paypalcommercealternativemethods: paypalOptions,\n });\n\n throw new TimeoutError();\n } catch (error) {\n this.handleError(error, onError);\n }\n }\n\n private deinitializePollingMechanism(): void {\n this.stopPolling();\n this.pollingTimer = 0;\n }\n\n private resetPollingMechanism(): void {\n this.deinitializePollingMechanism();\n this.toggleLoadingIndicator(false);\n }\n\n /**\n *\n * Loading Indicator methods\n *\n * */\n private toggleLoadingIndicator(isLoading: boolean): void {\n if (isLoading && this.loadingIndicatorContainer) {\n this.loadingIndicator.show(this.loadingIndicatorContainer);\n } else {\n this.loadingIndicator.hide();\n }\n }\n\n /**\n *\n * Utils\n *\n * */\n private isNonInstantPaymentMethod(methodId: string): boolean {\n return methodId.toUpperCase() in NonInstantAlternativePaymentMethods;\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceAlternativeMethodsPaymentStrategy from './paypal-commerce-alternative-methods-payment-strategy';\n\nconst createPayPalCommerceAlternativeMethodsPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceAlternativeMethodsPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceAlternativeMethodsPaymentStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n new LoadingIndicator({ styles: { backgroundColor: 'black' } }),\n );\n\nexport default toResolvableModule(createPayPalCommerceAlternativeMethodsPaymentStrategy, [\n { gateway: 'paypalcommercealternativemethods' },\n]);\n","import HostedFieldType from './hosted-field-type';\nimport { HostedCardFieldOptionsMap, HostedStoredCardFieldOptionsMap } from './hosted-form-options';\n\nexport default function isCreditCardFormFields(\n fields: HostedCardFieldOptionsMap | HostedStoredCardFieldOptionsMap,\n): fields is HostedCardFieldOptionsMap {\n return (\n HostedFieldType.CardNumber in fields &&\n HostedFieldType.CardName in fields &&\n HostedFieldType.CardExpiry in fields\n );\n}\n","import { isNil, omitBy } from 'lodash';\n\nimport {\n HostedCardFieldOptions,\n HostedCardFieldOptionsMap,\n HostedFieldBlurEventData,\n HostedFieldCardTypeChangeEventData,\n HostedFieldEnterEventData,\n HostedFieldFocusEventData,\n HostedFieldStylesMap,\n HostedFieldType,\n HostedFieldValidateEventData,\n HostedFormOptions,\n HostedInputStyles,\n HostedInputValidateErrorData,\n HostedInputValidateErrorDataMap,\n HostedInstrument,\n HostedStoredCardFieldOptionsMap,\n InvalidArgumentError,\n isCreditCardFormFields,\n isHostedInstrumentLike,\n isVaultedInstrument,\n NotInitializedError,\n NotInitializedErrorType,\n objectWithKebabCaseKeys,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStrategy,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n PayPalCommerceHostedFields,\n PayPalCommerceHostedFieldsRenderOptions,\n PayPalCommerceHostedFieldsState,\n PayPalCommerceHostedFieldsSubmitOptions,\n} from '../paypal-commerce-types';\n\nimport { WithPayPalCommerceCreditCardsPaymentInitializeOptions } from './paypal-commerce-credit-cards-payment-initialize-options';\n\nexport default class PayPalCommerceCreditCardsPaymentStrategy implements PaymentStrategy {\n private executionPaymentData?: OrderPaymentRequestBody['paymentData'];\n private isCreditCardForm?: boolean;\n private hostedFields?: PayPalCommerceHostedFields;\n private hostedFormOptions?: HostedFormOptions;\n private cardNameField?: HTMLInputElement;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithPayPalCommerceCreditCardsPaymentInitializeOptions,\n ): Promise {\n const { methodId, paypalcommercecreditcards, paypalcommerce } = options;\n const form = paypalcommercecreditcards?.form || paypalcommerce?.form;\n\n if (paypalcommerce) {\n console.warn(\n 'The \"options.paypalcommerce\" option is deprecated for PayPal Commerce Credit Card form, please use \"options.paypalcommercecreditcards\" instead',\n );\n }\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!form) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"options.paypalcommercecreditcards.form\" argument is not provided.',\n );\n }\n\n this.hostedFormOptions = form;\n this.isCreditCardForm = isCreditCardFormFields(form.fields);\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n await this.renderFields(form);\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const { methodId, paymentData } = payment || {};\n\n if (!payment || !methodId) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n this.executionPaymentData = paymentData;\n\n this.validateHostedFormOrThrow();\n\n const orderId = await this.submitHostedForm(methodId);\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paypalCommerceIntegrationService.submitPayment(methodId, orderId);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private async renderFields(formOptions: HostedFormOptions): Promise {\n const { fields, styles } = formOptions;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n\n const hostedFieldsOptions = {\n fields: this.mapFieldOptions(fields),\n styles: styles ? this.mapStyleOptions(styles) : {},\n paymentsSDK: true,\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder(\n 'paypalcommercecreditcardscheckout',\n this.getInstrumentParams(),\n ),\n };\n\n if (paypalSdk.HostedFields.isEligible()) {\n this.hostedFields = await paypalSdk.HostedFields.render(hostedFieldsOptions);\n\n this.setFormFieldEvents(this.hostedFields, formOptions);\n\n if (isCreditCardFormFields(fields)) {\n this.renderCardNameField(fields.cardName, styles);\n }\n } else {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n }\n\n /**\n *\n * Card Name field methods\n *\n */\n private renderCardNameField(\n field: HostedCardFieldOptions,\n styles?: HostedFieldStylesMap,\n ): void {\n const container = document.getElementById(field.containerId);\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"options.paypalcommercecreditcards.form.fields.cardName.containerId\" argument is not provided or the item is not defined in the dom.',\n );\n }\n\n const cardNameFiledStylesPreset = {\n backgroundColor: 'transparent',\n border: 0,\n display: 'block',\n height: '100%',\n margin: 0,\n outline: 'none',\n padding: 0,\n width: '100%',\n };\n\n const defaultCardNameFiledStyles = {\n ...cardNameFiledStylesPreset,\n ...styles?.default,\n };\n\n const focusCardNameFiledStyles = {\n ...cardNameFiledStylesPreset,\n ...styles?.focus,\n };\n\n const defaultStyleProperties = this.getValidStyleString(defaultCardNameFiledStyles);\n const focusStyleProperties = this.getValidStyleString(focusCardNameFiledStyles);\n\n this.cardNameField = document.createElement('input');\n\n this.setFieldStyleAttribute(defaultStyleProperties, this.cardNameField);\n\n this.cardNameField.addEventListener('blur', () =>\n this.setFieldStyleAttribute(defaultStyleProperties, this.cardNameField),\n );\n this.cardNameField.addEventListener('focus', () =>\n this.setFieldStyleAttribute(focusStyleProperties, this.cardNameField),\n );\n\n container.appendChild(this.cardNameField);\n }\n\n private setFieldStyleAttribute(style: string, item?: HTMLInputElement): void {\n item?.setAttribute('style', style);\n }\n\n /**\n *\n * Instrument params method\n *\n */\n private getInstrumentParams(): HostedInstrument | VaultedInstrument {\n if (!this.executionPaymentData) {\n return {};\n }\n\n if (isHostedInstrumentLike(this.executionPaymentData)) {\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } =\n this.executionPaymentData;\n\n return {\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n };\n }\n\n if (isVaultedInstrument(this.executionPaymentData)) {\n const { instrumentId } = this.executionPaymentData;\n\n return {\n instrumentId,\n };\n }\n\n return {};\n }\n\n /**\n *\n * Hosted form events\n *\n */\n private setFormFieldEvents(\n hostedFields: PayPalCommerceHostedFields,\n formOptions: HostedFormOptions,\n ): void {\n const eventsData = [\n {\n eventName: 'blur',\n formCallback: formOptions?.onBlur,\n eventHandler: (event: PayPalCommerceHostedFieldsState) =>\n formOptions?.onBlur?.(this.getFieldTypeByEmittedField(event)),\n },\n {\n eventName: 'focus',\n formCallback: formOptions?.onFocus,\n eventHandler: (event: PayPalCommerceHostedFieldsState) =>\n formOptions?.onFocus?.(this.getFieldTypeByEmittedField(event)),\n },\n {\n eventName: 'inputSubmitRequest',\n formCallback: formOptions?.onEnter,\n eventHandler: (event: PayPalCommerceHostedFieldsState) =>\n formOptions?.onEnter?.(this.getFieldTypeByEmittedField(event)),\n },\n {\n eventName: 'cardTypeChange',\n formCallback: formOptions?.onCardTypeChange,\n eventHandler: (event: PayPalCommerceHostedFieldsState) =>\n formOptions?.onCardTypeChange?.(this.getCardTypeByEvent(event)),\n },\n {\n eventName: 'validityChange',\n formCallback: formOptions?.onValidate,\n eventHandler: (event: PayPalCommerceHostedFieldsState) =>\n formOptions?.onValidate?.(this.getValidityData(event)),\n },\n ];\n\n eventsData.forEach(({ eventName, eventHandler, formCallback }) => {\n if (formCallback && typeof formCallback === 'function') {\n hostedFields.on(eventName, eventHandler);\n }\n });\n }\n\n private getFieldTypeByEmittedField({\n emittedBy,\n }: PayPalCommerceHostedFieldsState):\n | HostedFieldBlurEventData\n | HostedFieldEnterEventData\n | HostedFieldFocusEventData {\n return {\n fieldType: this.mapFieldType(emittedBy),\n };\n }\n\n private getCardTypeByEvent({\n cards,\n }: PayPalCommerceHostedFieldsState): HostedFieldCardTypeChangeEventData {\n return {\n cardType: cards?.[0]?.type,\n };\n }\n\n /**\n *\n * Hosted form submit method\n *\n * */\n private async submitHostedForm(methodId: string): Promise {\n const hostedFields = this.getHostedFieldsOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { is3dsEnabled } = paymentMethod.config;\n\n const options: PayPalCommerceHostedFieldsSubmitOptions = {\n ...(this.cardNameField?.value && {\n cardholderName: this.cardNameField.value,\n }),\n ...(is3dsEnabled && {\n contingencies: ['3D_SECURE'],\n }),\n };\n\n const { liabilityShift, orderId } = await hostedFields.submit(options);\n\n if (is3dsEnabled && (liabilityShift === 'NO' || liabilityShift === 'UNKNOWN')) {\n // FIXME: we should throw another error to have an ability to translate it\n throw new PaymentMethodFailedError(\n 'Failed authentication. Please try to authorize again.',\n );\n }\n\n return orderId;\n }\n\n /**\n *\n * Validation and errors\n *\n */\n private validateHostedFormOrThrow(): void {\n const hostedFields = this.getHostedFieldsOrThrow();\n const hostedFieldState = hostedFields.getState();\n const validationData = this.getValidityData(hostedFieldState);\n\n if (validationData.isValid) {\n return;\n }\n\n this.hostedFormOptions?.onValidate?.(validationData);\n\n throw new PaymentInvalidFormError(this.mapValidationErrors(validationData.errors));\n }\n\n private getValidityData({\n fields,\n }: PayPalCommerceHostedFieldsState): HostedFieldValidateEventData {\n const fieldsKeys = Object.keys(fields) as Array<\n keyof PayPalCommerceHostedFieldsState['fields']\n >;\n\n const isValid = fieldsKeys.every((key) => fields[key]?.isValid);\n const errors = fieldsKeys.reduce((fieldsErrors, key) => {\n const fieldType = this.mapFieldType(key);\n\n return {\n ...fieldsErrors,\n [fieldType]: fields[key]?.isValid\n ? undefined\n : [this.getInvalidErrorByFieldType(fieldType)],\n };\n }, {});\n\n return { isValid, errors };\n }\n\n private getInvalidErrorByFieldType(fieldType: string): HostedInputValidateErrorData {\n switch (fieldType) {\n case HostedFieldType.CardCode:\n case HostedFieldType.CardCodeVerification:\n return {\n fieldType,\n message: 'Invalid card code',\n type: 'invalid_card_code',\n };\n\n case HostedFieldType.CardNumber:\n case HostedFieldType.CardNumberVerification:\n return {\n fieldType,\n message: 'Invalid card number',\n type: 'invalid_card_number',\n };\n\n case HostedFieldType.CardExpiry:\n return {\n fieldType,\n message: 'Invalid card expiry',\n type: 'invalid_card_expiry',\n };\n\n default:\n return {\n fieldType,\n message: 'Invalid field',\n type: 'invalid',\n };\n }\n }\n\n private mapValidationErrors(\n validationErrors: HostedInputValidateErrorDataMap = {},\n ): PaymentInvalidFormErrorDetails {\n const errors: PaymentInvalidFormErrorDetails = {};\n const validationErrorsKeys = Object.keys(validationErrors) as Array<\n keyof HostedInputValidateErrorDataMap\n >;\n\n validationErrorsKeys.forEach((key) => {\n errors[key] = [\n {\n message: validationErrors[key]?.[0]?.message || '',\n type: key,\n },\n ];\n });\n\n return errors;\n }\n\n /**\n *\n * Fields mappers\n *\n */\n private mapFieldType(type: string): HostedFieldType {\n switch (type) {\n case 'number':\n return this.isCreditCardForm\n ? HostedFieldType.CardNumber\n : HostedFieldType.CardNumberVerification;\n\n case 'expirationDate':\n return HostedFieldType.CardExpiry;\n\n case 'cvv':\n return this.isCreditCardForm\n ? HostedFieldType.CardCode\n : HostedFieldType.CardCodeVerification;\n\n default:\n throw new Error('Unexpected field type');\n }\n }\n\n private mapFieldOptions(\n fields: HostedCardFieldOptionsMap | HostedStoredCardFieldOptionsMap,\n ): PayPalCommerceHostedFieldsRenderOptions['fields'] {\n if (isCreditCardFormFields(fields)) {\n const { cardNumber, cardExpiry, cardCode } = fields;\n\n return {\n ...(cardNumber && {\n number: {\n selector: `#${cardNumber.containerId}`,\n placeholder: cardNumber.placeholder,\n },\n }),\n ...(cardExpiry && {\n expirationDate: {\n selector: `#${cardExpiry.containerId}`,\n placeholder: cardExpiry.placeholder,\n },\n }),\n ...(cardCode && {\n cvv: {\n selector: `#${cardCode.containerId}`,\n placeholder: cardCode.placeholder,\n },\n }),\n };\n }\n\n const { cardNumberVerification, cardCodeVerification } = fields;\n\n return {\n ...(cardNumberVerification && {\n number: {\n selector: `#${cardNumberVerification.containerId}`,\n placeholder: cardNumberVerification.placeholder,\n },\n }),\n ...(cardCodeVerification && {\n cvv: {\n selector: `#${cardCodeVerification.containerId}`,\n placeholder: cardCodeVerification.placeholder,\n },\n }),\n };\n }\n\n /**\n *\n * Styles mappers\n *\n */\n private mapStyleOptions(\n styles: HostedFieldStylesMap,\n ): PayPalCommerceHostedFieldsRenderOptions['styles'] {\n return {\n input: this.mapStyles(styles.default),\n '.invalid': this.mapStyles(styles.error),\n ':focus': this.mapStyles(styles.focus),\n };\n }\n\n private mapStyles(styles: HostedInputStyles = {}): { [key: string]: string } {\n return omitBy(objectWithKebabCaseKeys(styles), isNil);\n }\n\n private getValidStyleString(styles: HostedInputStyles = {}): string {\n const validStyles = this.mapStyles(styles);\n\n return Object.keys(validStyles)\n .map((key) => `${key}: ${validStyles[key]}`)\n .join(';');\n }\n\n /**\n *\n * Utils\n *\n */\n private getHostedFieldsOrThrow(): PayPalCommerceHostedFields {\n if (!this.hostedFields) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.hostedFields;\n }\n}\n","import { kebabCase } from 'lodash';\n\nexport default function objectWithKebabCaseKeys(object: { [key: string]: any }) {\n const keys = Object.keys(object);\n\n return keys.reduce(\n (newObject, key) => ({\n ...newObject,\n [kebabCase(key)]: object[key],\n }),\n {},\n );\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceCreditCardsPaymentStrategy from './paypal-commerce-credit-cards-payment-strategy';\n\nconst createPaypalCommerceCreditCardsPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceCreditCardsPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditCardsPaymentStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPaypalCommerceCreditCardsPaymentStrategy, [\n { id: 'paypalcommercecreditcards' },\n]);\n","import { ExternalPaymentStrategy } from '@bigcommerce/checkout-sdk/external-integration';\n\nexport default class SezzlePaymentStrategy extends ExternalPaymentStrategy {\n protected redirectUrl(url: string): void {\n window.location.replace(url);\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport SezzlePaymentStrategy from './sezzle-payment-strategy';\n\nconst createSezzlePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => new SezzlePaymentStrategy(createFormPoster(), paymentIntegrationService);\n\nexport default toResolvableModule(createSezzlePaymentStrategy, [{ id: 'sezzle' }]);\n","import StandardError from './standard-error';\n\nconst defaultMessage =\n 'Payment cannot be processed for this order, please select another payment method';\n\nexport default class PaymentExecuteError extends StandardError {\n type = 'custom_provider_execute_error';\n subtype: string;\n\n constructor(subtype: string, name: string, message?: string) {\n super(message || defaultMessage);\n\n this.name = name;\n this.subtype = subtype;\n }\n}\n","import { fromEvent, merge, Subscription } from 'rxjs';\nimport { distinctUntilChanged, map } from 'rxjs/operators';\n\nimport {\n BillingAddress,\n guard,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentExecuteError,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport SquareV2PaymentInitializeOptions from './squarev2-payment-initialize-options';\nimport SquareV2ScriptLoader from './squarev2-script-loader';\nimport {\n BillingContact,\n Card,\n CardInputEvent,\n CardInputEventTypes,\n ChargeVerifyBuyerDetails,\n Payments,\n SqEvent,\n} from './types';\n\nexport interface SquareV2PaymentProcessorOptions {\n applicationId: string;\n locationId?: string;\n testMode?: boolean;\n}\n\nexport default class SquareV2PaymentProcessor {\n private _payments?: Payments;\n private _card?: Card;\n private _formValidationSubscription?: Subscription;\n\n constructor(\n private _scriptLoader: SquareV2ScriptLoader,\n private _paymentIntegrationService: PaymentIntegrationService,\n ) {}\n\n async initialize({\n testMode,\n applicationId,\n locationId,\n }: SquareV2PaymentProcessorOptions): Promise {\n const square = await this._scriptLoader.load(testMode);\n\n this._payments = square.payments(applicationId, locationId);\n }\n\n async deinitialize(): Promise {\n if (this._formValidationSubscription) {\n this._formValidationSubscription.unsubscribe();\n }\n\n if (this._card) {\n await this._card.destroy();\n }\n\n this._formValidationSubscription = undefined;\n this._card = undefined;\n this._payments = undefined;\n }\n\n async initializeCard({\n containerId,\n style,\n onValidationChange,\n }: SquareV2PaymentInitializeOptions): Promise {\n const { postalCode } = this._paymentIntegrationService.getState().getBillingAddress() || {};\n\n this._card = await this._getPayments().card();\n await this._card.attach(`#${containerId}`);\n\n try {\n await this._card.configure({ postalCode, style });\n } catch (_error) {\n /* Do nothing: we should not block shoppers from buying. */\n }\n\n if (onValidationChange) {\n this._formValidationSubscription = this._subscribeToFormValidation(\n this._card,\n onValidationChange,\n );\n }\n }\n\n async tokenize(): Promise {\n const result = await this._getCard().tokenize();\n\n if (result.status !== 'OK' || !result.token) {\n let errorMessage = `Tokenization failed with status: ${result.status}`;\n\n if (result.errors) {\n errorMessage += ` and errors: ${JSON.stringify(result.errors)}`;\n }\n\n throw new PaymentExecuteError(\n 'payment.errors.card_error',\n 'SquareV2TokenizationError',\n errorMessage,\n );\n }\n\n return result.token;\n }\n\n async verifyBuyer(token: string): Promise {\n const { getCheckoutOrThrow, getBillingAddressOrThrow } =\n this._paymentIntegrationService.getState();\n const { outstandingBalance, cart } = getCheckoutOrThrow();\n\n const details: ChargeVerifyBuyerDetails = {\n amount: outstandingBalance.toString(),\n billingContact: this._mapToSquareBillingContact(getBillingAddressOrThrow()),\n currencyCode: cart.currency.code,\n intent: 'CHARGE',\n };\n\n const response = await this._getPayments().verifyBuyer(token, details);\n\n return response ? response.token : '';\n }\n\n private _getPayments(): Payments {\n return guard(\n this._payments,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n private _subscribeToFormValidation(\n card: Card,\n observer: Required['onValidationChange'],\n ): Subscription {\n const blacklist = ['cardNumber', 'cvv'];\n const invalidFields = new Set(blacklist);\n const eventObservables = [\n 'focusClassAdded',\n 'focusClassRemoved',\n 'errorClassAdded',\n 'errorClassRemoved',\n 'cardBrandChanged',\n 'postalCodeChanged',\n ].map((eventType) => fromEvent(card, eventType as CardInputEventTypes));\n\n return merge(...eventObservables)\n .pipe(\n map((event: SqEvent): boolean => {\n const {\n detail: {\n field,\n currentState: { isCompletelyValid },\n },\n } = event;\n\n if (blacklist.includes(field)) {\n invalidFields[isCompletelyValid ? 'delete' : 'add'](field);\n }\n\n return invalidFields.size === 0;\n }),\n distinctUntilChanged(),\n )\n .subscribe(observer);\n }\n\n private _getCard(): Card {\n return guard(\n this._card,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n private _mapToSquareBillingContact({\n firstName: givenName,\n lastName: familyName,\n address1,\n address2,\n city,\n stateOrProvinceCode: state,\n postalCode,\n countryCode,\n email,\n phone,\n }: BillingAddress): BillingContact {\n return {\n givenName,\n familyName,\n addressLines: [address1, address2],\n city,\n state,\n postalCode,\n countryCode,\n email,\n phone,\n };\n }\n}\n","import {\n InvalidArgumentError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodInvalidError,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithSquareV2PaymentInitializeOptions } from './squarev2-payment-initialize-options';\nimport SquareV2PaymentProcessor from './squarev2-payment-processor';\nimport { SquarePaymentMethodInitializationData } from './types';\n\nexport default class SquareV2PaymentStrategy implements PaymentStrategy {\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _squareV2PaymentProcessor: SquareV2PaymentProcessor,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithSquareV2PaymentInitializeOptions,\n ): Promise {\n if (!options?.squarev2?.containerId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"containerId\" argument is not provided.',\n );\n }\n\n const { methodId, squarev2 } = options;\n const {\n config: { testMode },\n initializationData,\n } = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId);\n const { applicationId, locationId } = initializationData || {};\n\n if (!applicationId) {\n throw new PaymentMethodInvalidError();\n }\n\n await this._squareV2PaymentProcessor.initialize({\n applicationId,\n locationId,\n testMode,\n });\n await this._squareV2PaymentProcessor.initializeCard(squarev2);\n }\n\n async execute({ payment }: OrderRequestBody): Promise {\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n let nonce = await this._squareV2PaymentProcessor.tokenize();\n\n if (this._shouldVerify()) {\n nonce = JSON.stringify({\n nonce,\n token: await this._squareV2PaymentProcessor.verifyBuyer(nonce),\n });\n }\n\n await this._paymentIntegrationService.submitOrder();\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: { nonce },\n });\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return this._squareV2PaymentProcessor.deinitialize();\n }\n\n private _shouldVerify(): boolean {\n const { features } = this._paymentIntegrationService\n .getState()\n .getStoreConfigOrThrow().checkoutSettings;\n\n return features['PROJECT-3828.add_3ds_support_on_squarev2'];\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport assertSquareV2Window from './is-squarev2-window';\nimport { Square } from './types';\n\nexport enum SquareV2WebPaymentsSdkEnv {\n LIVE = 'https://web.squarecdn.com/v1/square.js',\n SANDBOX = 'https://sandbox.web.squarecdn.com/v1/square.js',\n}\n\nexport default class SquareV2ScriptLoader {\n constructor(private _scriptLoader: ScriptLoader) {}\n\n async load(testMode = false): Promise {\n await this._scriptLoader.loadScript(\n testMode ? SquareV2WebPaymentsSdkEnv.SANDBOX : SquareV2WebPaymentsSdkEnv.LIVE,\n );\n\n assertSquareV2Window(window);\n\n return window.Square;\n }\n}\n","import { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport type { Square } from './types';\n\ninterface SquareV2HostWindow extends Window {\n Square: Square;\n}\n\nfunction isSquareV2Window(window: Window): window is SquareV2HostWindow {\n return 'Square' in window;\n}\n\nexport default function assertSquareV2Window(window: Window): asserts window is SquareV2HostWindow {\n if (!isSquareV2Window(window)) {\n throw new PaymentMethodClientUnavailableError();\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n NotImplementedError,\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport SquareV2PaymentProcessor from './squarev2-payment-processor';\nimport SquareV2PaymentStrategy from './squarev2-payment-strategy';\nimport SquareV2ScriptLoader from './squarev2-script-loader';\n\nconst createSquareV2PaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const useV1 = !paymentIntegrationService.getState().getStoreConfig()?.checkoutSettings.features[\n 'PROJECT-4113.squarev2_web_payments_sdk'\n ];\n\n if (useV1) {\n throw new NotImplementedError();\n }\n\n return new SquareV2PaymentStrategy(\n paymentIntegrationService,\n new SquareV2PaymentProcessor(\n new SquareV2ScriptLoader(getScriptLoader()),\n paymentIntegrationService,\n ),\n );\n};\n\nexport default toResolvableModule(createSquareV2PaymentStrategy, [{ id: 'squarev2' }]);\n","import { Action } from '@bigcommerce/data-store';\n\nimport Country from './country';\n\nexport enum CountryActionType {\n LoadCountriesRequested = 'LOAD_COUNTRIES_REQUESTED',\n LoadCountriesSucceeded = 'LOAD_COUNTRIES_SUCCEEDED',\n LoadCountriesFailed = 'LOAD_COUNTRIES_FAILED',\n}\n\nexport type LoadCountriesAction =\n | LoadCountriesRequestedAction\n | LoadCountriesSucceededAction\n | LoadCountriesFailedAction;\n\nexport interface LoadCountriesRequestedAction extends Action {\n type: CountryActionType.LoadCountriesRequested;\n}\n\nexport interface LoadCountriesSucceededAction extends Action {\n type: CountryActionType.LoadCountriesSucceeded;\n}\n\nexport interface LoadCountriesFailedAction extends Action {\n type: CountryActionType.LoadCountriesFailed;\n}\n","import { Action, createAction, createErrorAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { RequestOptions } from '../common/http-request';\n\nimport Country from './country';\nimport { CountryActionType } from './country-actions';\nimport CountryRequestSender from './country-request-sender';\n\nexport default class CountryActionCreator {\n constructor(private _countryRequestSender: CountryRequestSender) {}\n\n loadCountries(options?: RequestOptions): Observable> {\n return Observable.create((observer: Observer>) => {\n observer.next(createAction(CountryActionType.LoadCountriesRequested));\n\n this._countryRequestSender\n .loadCountries(options)\n .then((response) => {\n observer.next(\n createAction(CountryActionType.LoadCountriesSucceeded, response.body.data),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(CountryActionType.LoadCountriesFailed, response),\n );\n });\n });\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nimport { CountryResponseBody } from './country-responses';\n\nexport default class CountryRequestSender {\n constructor(private _requestSender: RequestSender, private _config: { locale?: string }) {}\n\n loadCountries({ timeout }: RequestOptions = {}): Promise> {\n const url = '/internalapi/v1/store/countries';\n const headers = {\n 'Accept-Language': this._config.locale,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.get(url, { headers, timeout });\n }\n}\n","import {\n isResolvableModule,\n PaymentIntegrationService,\n PaymentStrategy,\n PaymentStrategyFactory,\n PaymentStrategyResolveId,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ResolveIdRegistry } from '../common/registry';\nimport * as defaultPaymentStrategyFactories from '../generated/payment-strategies';\n\nexport interface PaymentStrategyFactories {\n [key: string]: PaymentStrategyFactory;\n}\n\nexport default function createPaymentStrategyRegistry(\n paymentIntegrationService: PaymentIntegrationService,\n paymentStrategyFactories: PaymentStrategyFactories = defaultPaymentStrategyFactories,\n options: { useFallback: boolean } = { useFallback: false },\n): ResolveIdRegistry {\n const { useFallback } = options;\n const registry = new ResolveIdRegistry(useFallback);\n\n for (const [, createPaymentStrategy] of Object.entries(paymentStrategyFactories)) {\n if (\n !isResolvableModule, PaymentStrategyResolveId>(\n createPaymentStrategy,\n )\n ) {\n continue;\n }\n\n for (const resolverId of createPaymentStrategy.resolveIds) {\n registry.register(resolverId, () => createPaymentStrategy(paymentIntegrationService));\n }\n }\n\n return registry;\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if we are trying to make an order finalization request for a\n * payment method that does not require such procedure.\n */\nexport default class OrderFinalizationNotRequiredError extends StandardError {\n constructor() {\n super('The current order does not need to be finalized at this stage.');\n\n this.name = 'OrderFinalizationNotRequiredError';\n this.type = 'order_finalization_not_required';\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { LoadOrderPaymentsAction } from '../order';\n\nexport enum PaymentStrategyActionType {\n ExecuteFailed = 'PAYMENT_STRATEGY_EXECUTE_FAILED',\n ExecuteRequested = 'PAYMENT_STRATEGY_EXECUTE_REQUESTED',\n ExecuteSucceeded = 'PAYMENT_STRATEGY_EXECUTE_SUCCEEDED',\n FinalizeFailed = 'PAYMENT_STRATEGY_FINALIZE_FAILED',\n FinalizeRequested = 'PAYMENT_STRATEGY_FINALIZE_REQUESTED',\n FinalizeSucceeded = 'PAYMENT_STRATEGY_FINALIZE_SUCCEEDED',\n InitializeFailed = 'PAYMENT_STRATEGY_INITIALIZE_FAILED',\n InitializeRequested = 'PAYMENT_STRATEGY_INITIALIZE_REQUESTED',\n InitializeSucceeded = 'PAYMENT_STRATEGY_INITIALIZE_SUCCEEDED',\n DeinitializeFailed = 'PAYMENT_STRATEGY_DEINITIALIZE_FAILED',\n DeinitializeRequested = 'PAYMENT_STRATEGY_DEINITIALIZE_REQUESTED',\n DeinitializeSucceeded = 'PAYMENT_STRATEGY_DEINITIALIZE_SUCCEEDED',\n WidgetInteractionStarted = 'PAYMENT_STRATEGY_WIDGET_INTERACTION_STARTED',\n WidgetInteractionFinished = 'PAYMENT_STRATEGY_WIDGET_INTERACTION_FINISHED',\n WidgetInteractionFailed = 'PAYMENT_STRATEGY_WIDGET_INTERACTION_FAILED',\n}\n\nexport type PaymentStrategyAction =\n | PaymentStrategyExecuteAction\n | PaymentStrategyFinalizeAction\n | PaymentStrategyInitializeAction\n | PaymentStrategyDeinitializeAction\n | PaymentStrategyWidgetAction;\n\nexport type PaymentStrategyExecuteAction =\n | ExecuteRequestedAction\n | ExecuteSucceededAction\n | ExecuteFailedAction\n | LoadOrderPaymentsAction;\n\nexport type PaymentStrategyFinalizeAction =\n | FinalizeRequestedAction\n | FinalizeSucceededAction\n | FinalizeFailedAction\n | LoadOrderPaymentsAction;\n\nexport type PaymentStrategyInitializeAction =\n | InitializeRequestedAction\n | InitializeSucceededAction\n | InitializeFailedAction;\n\nexport type PaymentStrategyDeinitializeAction =\n | DeinitializeRequestedAction\n | DeinitializeSucceededAction\n | DeinitializeFailedAction;\n\nexport type PaymentStrategyWidgetAction =\n | WidgetInteractionStartedAction\n | WidgetInteractionFinishedAction\n | WidgetInteractionFailedAction;\n\nexport interface ExecuteRequestedAction extends Action {\n type: PaymentStrategyActionType.ExecuteRequested;\n}\n\nexport interface ExecuteSucceededAction extends Action {\n type: PaymentStrategyActionType.ExecuteSucceeded;\n}\n\nexport interface ExecuteFailedAction extends Action {\n type: PaymentStrategyActionType.ExecuteFailed;\n}\n\nexport interface FinalizeRequestedAction extends Action {\n type: PaymentStrategyActionType.FinalizeRequested;\n}\n\nexport interface FinalizeSucceededAction extends Action {\n type: PaymentStrategyActionType.FinalizeSucceeded;\n}\n\nexport interface FinalizeFailedAction extends Action {\n type: PaymentStrategyActionType.FinalizeFailed;\n}\n\nexport interface InitializeRequestedAction extends Action {\n type: PaymentStrategyActionType.InitializeRequested;\n}\n\nexport interface InitializeSucceededAction extends Action {\n type: PaymentStrategyActionType.InitializeSucceeded;\n}\n\nexport interface InitializeFailedAction extends Action {\n type: PaymentStrategyActionType.InitializeFailed;\n}\n\nexport interface DeinitializeRequestedAction extends Action {\n type: PaymentStrategyActionType.DeinitializeRequested;\n}\n\nexport interface DeinitializeSucceededAction extends Action {\n type: PaymentStrategyActionType.DeinitializeSucceeded;\n}\n\nexport interface DeinitializeFailedAction extends Action {\n type: PaymentStrategyActionType.DeinitializeFailed;\n}\n\nexport interface WidgetInteractionStartedAction extends Action {\n type: PaymentStrategyActionType.WidgetInteractionStarted;\n}\n\nexport interface WidgetInteractionFinishedAction extends Action {\n type: PaymentStrategyActionType.WidgetInteractionFinished;\n}\n\nexport interface WidgetInteractionFailedAction extends Action {\n type: PaymentStrategyActionType.WidgetInteractionFailed;\n}\n","enum PaymentStrategyType {\n ADYENV2 = 'adyenv2',\n ADYENV2_GOOGLEPAY = 'googlepayadyenv2',\n ADYENV3 = 'adyenv3',\n ADYENV3_GOOGLEPAY = 'googlepayadyenv3',\n AFFIRM = 'affirm',\n AFTERPAY = 'afterpay',\n AUTHORIZENET_GOOGLE_PAY = 'googlepayauthorizenet',\n AMAZONPAY = 'amazonpay',\n APPLEPAY = 'applepay',\n BARCLAYS = 'barclays',\n BLUESNAPV2 = 'bluesnapv2',\n BOLT = 'bolt',\n CBA_MPGS = 'cba_mpgs',\n CHECKOUTCOM = 'checkoutcom',\n CHECKOUTCOM_APM = 'checkoutcomapm',\n CHECKOUTCOM_FAWRY = 'checkoutcomfawry',\n CHECKOUTCOM_SEPA = 'checkoutcomsepa',\n CHECKOUTCOM_IDEAL = 'checkoutcomideal',\n CREDIT_CARD = 'creditcard',\n CHECKOUTCOM_GOOGLE_PAY = 'googlepaycheckoutcom',\n CLEARPAY = 'clearpay',\n CONVERGE = 'converge',\n CYBERSOURCE = 'cybersource',\n CYBERSOURCEV2 = 'cybersourcev2',\n BNZ = 'bnz',\n BNZ_GOOGLEPAY = 'googlepaybnz',\n DIGITALRIVER = 'digitalriver',\n CYBERSOURCEV2_GOOGLE_PAY = 'googlepaycybersourcev2',\n HUMM = 'humm',\n KLARNA = 'klarna',\n KLARNAV2 = 'klarnav2',\n LAYBUY = 'laybuy',\n LEGACY = 'legacy',\n MOLLIE = 'mollie',\n MONERIS = 'moneris',\n NO_PAYMENT_DATA_REQUIRED = 'nopaymentdatarequired',\n OFFLINE = 'offline',\n OFFSITE = 'offsite',\n OPY = 'opy',\n ORBITAL_GOOGLE_PAY = 'googlepayorbital',\n PAYPAL = 'paypal',\n PAYPAL_EXPRESS = 'paypalexpress',\n PAYPAL_EXPRESS_CREDIT = 'paypalexpresscredit',\n PAYPAL_COMMERCE = 'paypalcommerce',\n PAYPAL_COMMERCE_CREDIT = 'paypalcommercecredit',\n PAYPAL_COMMERCE_CREDIT_CARD = 'paypalcommercecreditcards',\n PAYPAL_COMMERCE_ALTERNATIVE_METHODS = 'paypalcommercealternativemethods',\n PAYPAL_COMMERCE_VENMO = 'paypalcommercevenmo',\n PPSDK = 'PAYMENT_TYPE_SDK',\n QUADPAY = 'quadpay',\n SAGE_PAY = 'sagepay',\n SQUARE = 'squarev2',\n STRIPEV3 = 'stripev3',\n STRIPE_UPE = 'stripeupe',\n STRIPE_UPE_GOOGLE_PAY = 'googlepaystripeupe',\n BRAINTREE = 'braintree',\n BRAINTREE_PAYPAL = 'braintreepaypal',\n BRAINTREE_VENMO = 'braintreevenmo',\n BRAINTREE_PAYPAL_CREDIT = 'braintreepaypalcredit',\n BRAINTREE_VISA_CHECKOUT = 'braintreevisacheckout',\n BRAINTREE_GOOGLE_PAY = 'googlepaybraintree',\n CHASE_PAY = 'chasepay',\n WE_PAY = 'wepay',\n WORLDPAYACCESS = 'worldpayaccess',\n WORLDPAYACCESS_GOOGLE_PAY = 'googlepayworldpayaccess',\n MASTERPASS = 'masterpass',\n STRIPE_GOOGLE_PAY = 'googlepaystripe',\n SEZZLE = 'sezzle',\n ZIP = 'zip',\n}\n\nexport default PaymentStrategyType;\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, empty, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { PaymentStrategy as PaymentStrategyV2 } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { InternalCheckoutSelectors, ReadableCheckoutStore } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\nimport {\n LoadOrderPaymentsAction,\n OrderActionCreator,\n OrderPaymentRequestBody,\n OrderRequestBody,\n} from '../order';\nimport { OrderFinalizationNotRequiredError } from '../order/errors';\nimport { SpamProtectionAction, SpamProtectionActionCreator } from '../spam-protection';\n\nimport PaymentMethod from './payment-method';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from './payment-request-options';\nimport {\n PaymentStrategyActionType,\n PaymentStrategyDeinitializeAction,\n PaymentStrategyExecuteAction,\n PaymentStrategyFinalizeAction,\n PaymentStrategyInitializeAction,\n PaymentStrategyWidgetAction,\n} from './payment-strategy-actions';\nimport PaymentStrategyRegistry from './payment-strategy-registry';\nimport PaymentStrategyRegistryV2 from './payment-strategy-registry-v2';\nimport PaymentStrategyType from './payment-strategy-type';\nimport { PaymentStrategy } from './strategies';\n\nexport default class PaymentStrategyActionCreator {\n constructor(\n private _strategyRegistry: PaymentStrategyRegistry,\n private _strategyRegistryV2: PaymentStrategyRegistryV2,\n private _orderActionCreator: OrderActionCreator,\n private _spamProtectionActionCreator: SpamProtectionActionCreator,\n ) {}\n\n execute(\n payload: OrderRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n const { payment = {} as OrderPaymentRequestBody, useStoreCredit } = payload;\n const meta = { methodId: payment.methodId };\n\n return (store) => {\n const { checkout } = store.getState();\n const { shouldExecuteSpamCheck } = checkout.getCheckoutOrThrow();\n\n return concat(\n shouldExecuteSpamCheck\n ? this._spamProtectionActionCreator.verifyCheckoutSpamProtection()(store)\n : empty(),\n of(createAction(PaymentStrategyActionType.ExecuteRequested, undefined, meta)),\n defer(() => {\n const state = store.getState();\n\n let strategy: PaymentStrategy | PaymentStrategyV2;\n\n if (state.payment.isPaymentDataRequired(useStoreCredit)) {\n const method = state.paymentMethods.getPaymentMethod(\n payment.methodId,\n payment.gatewayId,\n );\n\n if (!method) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n strategy = this._getStrategy(method);\n } else {\n strategy = this._strategyRegistryV2.get({\n id: PaymentStrategyType.NO_PAYMENT_DATA_REQUIRED,\n });\n }\n\n const promise: Promise = strategy.execute(\n payload,\n {\n ...options,\n methodId: payment.methodId,\n gatewayId: payment.gatewayId,\n },\n );\n\n return promise.then(() =>\n createAction(PaymentStrategyActionType.ExecuteSucceeded, undefined, meta),\n );\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(PaymentStrategyActionType.ExecuteFailed, error, meta),\n ),\n );\n };\n }\n\n finalize(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(PaymentStrategyActionType.FinalizeRequested)),\n this._loadOrderPaymentsIfNeeded(store, options),\n defer(async () => {\n const state = store.getState();\n const { providerId = '', gatewayId = '' } = state.payment.getPaymentId() || {};\n const method = state.paymentMethods.getPaymentMethod(providerId, gatewayId);\n\n if (!method) {\n throw new OrderFinalizationNotRequiredError();\n }\n\n const strategy = this._getStrategy(method);\n\n await strategy.finalize({\n ...options,\n methodId: method.id,\n gatewayId: method.gateway,\n });\n\n return createAction(PaymentStrategyActionType.FinalizeSucceeded, undefined, {\n methodId: method.id,\n });\n }),\n ).pipe(\n catchError((error) => {\n const state = store.getState();\n const payment = state.payment.getPaymentId();\n\n return throwErrorAction(PaymentStrategyActionType.FinalizeFailed, error, {\n methodId: payment && payment.providerId,\n });\n }),\n );\n }\n\n initialize(\n options: PaymentInitializeOptions,\n ): ThunkAction {\n const { methodId, gatewayId } = options;\n\n return (store) =>\n defer(() => {\n const state = store.getState();\n const method = state.paymentMethods.getPaymentMethod(methodId, gatewayId);\n\n if (!method) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (methodId && state.paymentStrategies.isInitialized({ methodId, gatewayId })) {\n return empty();\n }\n\n const strategy = this._getStrategy(method);\n\n const promise: Promise = strategy.initialize({\n ...options,\n methodId,\n gatewayId,\n });\n\n return concat(\n of(\n createAction(PaymentStrategyActionType.InitializeRequested, undefined, {\n methodId,\n gatewayId,\n }),\n ),\n promise.then(() =>\n createAction(PaymentStrategyActionType.InitializeSucceeded, undefined, {\n methodId,\n gatewayId,\n }),\n ),\n );\n }).pipe(\n catchError((error) =>\n throwErrorAction(PaymentStrategyActionType.InitializeFailed, error, {\n methodId,\n gatewayId,\n }),\n ),\n );\n }\n\n deinitialize(\n options: PaymentRequestOptions,\n ): ThunkAction {\n const { methodId, gatewayId } = options;\n\n return (store) =>\n defer(() => {\n const state = store.getState();\n const method = state.paymentMethods.getPaymentMethod(methodId, gatewayId);\n\n if (!method) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (methodId && !state.paymentStrategies.isInitialized({ methodId, gatewayId })) {\n return empty();\n }\n\n const strategy = this._getStrategy(method);\n\n const promise: Promise = strategy.deinitialize({\n ...options,\n methodId,\n gatewayId,\n });\n\n return concat(\n of(\n createAction(PaymentStrategyActionType.DeinitializeRequested, undefined, {\n methodId,\n gatewayId,\n }),\n ),\n promise.then(() =>\n createAction(PaymentStrategyActionType.DeinitializeSucceeded, undefined, {\n methodId,\n gatewayId,\n }),\n ),\n );\n }).pipe(\n catchError((error) =>\n throwErrorAction(PaymentStrategyActionType.DeinitializeFailed, error, {\n methodId,\n gatewayId,\n }),\n ),\n );\n }\n\n widgetInteraction(\n method: () => Promise,\n options?: PaymentRequestOptions,\n ): Observable {\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n return concat(\n of(createAction(PaymentStrategyActionType.WidgetInteractionStarted, undefined, meta)),\n defer(() =>\n method().then(() =>\n createAction(\n PaymentStrategyActionType.WidgetInteractionFinished,\n undefined,\n meta,\n ),\n ),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(PaymentStrategyActionType.WidgetInteractionFailed, error, meta),\n ),\n );\n }\n\n private _getStrategy(method: PaymentMethod): PaymentStrategy | PaymentStrategyV2 {\n let strategy: PaymentStrategy | PaymentStrategyV2;\n\n try {\n strategy = this._strategyRegistry.getByMethod(method);\n } catch {\n strategy = this._strategyRegistryV2.get({\n id: method.id,\n gateway: method.gateway,\n type: method.type,\n });\n }\n\n return strategy;\n }\n\n private _loadOrderPaymentsIfNeeded(\n store: ReadableCheckoutStore,\n options?: RequestOptions,\n ): Observable {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (checkout && checkout.orderId) {\n return this._orderActionCreator.loadOrderPayments(checkout.orderId, options);\n }\n\n return empty();\n }\n}\n","import { default as storage } from 'local-storage-fallback';\n\nexport default class BrowserStorage {\n constructor(private _namespace: string) {}\n\n getItem(key: string): TValue | null {\n const rawValue = storage.getItem(this.withNamespace(key));\n\n if (rawValue === null) {\n return null;\n }\n\n try {\n return JSON.parse(rawValue);\n } catch (error) {\n // Clean up invalid values\n this.removeItem(this.withNamespace(key));\n\n return null;\n }\n }\n\n getItemOnce(key: string): TValue | null {\n const value = this.getItem(key);\n\n this.removeItem(key);\n\n return value;\n }\n\n setItem(key: string, value: TValue): void {\n return storage.setItem(this.withNamespace(key), JSON.stringify(value));\n }\n\n removeItem(key: string): void {\n return storage.removeItem(this.withNamespace(key));\n }\n\n private withNamespace(key: string): string {\n return `${this._namespace}.${key}`;\n }\n}\n","export const HOSTED = 'PAYMENT_TYPE_HOSTED';\nexport const OFFLINE = 'PAYMENT_TYPE_OFFLINE';\n","import PaymentMethod from './payment-method';\nimport PaymentStrategyType from './payment-strategy-type';\n\ntype PPSDKRequiredProperties = 'initializationStrategy';\n\nexport type PPSDKPaymentMethod = PaymentMethod & {\n type: PaymentStrategyType.PPSDK;\n} & Required>;\n\nexport const isPPSDKPaymentMethod = (\n paymentMethod: PaymentMethod,\n): paymentMethod is PPSDKPaymentMethod => {\n const { type, initializationStrategy } = paymentMethod;\n\n return type === PaymentStrategyType.PPSDK && typeof initializationStrategy?.type === 'string';\n};\n","import { ReadableDataStore } from '@bigcommerce/data-store';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { InvalidArgumentError } from '../common/error/errors';\nimport { Registry, RegistryOptions } from '../common/registry';\n\nimport PaymentMethod from './payment-method';\nimport * as paymentMethodTypes from './payment-method-types';\nimport PaymentStrategyType from './payment-strategy-type';\nimport { isPPSDKPaymentMethod } from './ppsdk-payment-method';\nimport { PaymentStrategy } from './strategies';\n\nconst checkoutcomStrategies: {\n [key: string]: PaymentStrategyType;\n} = {\n card: PaymentStrategyType.CHECKOUTCOM,\n credit_card: PaymentStrategyType.CHECKOUTCOM,\n sepa: PaymentStrategyType.CHECKOUTCOM_SEPA,\n ideal: PaymentStrategyType.CHECKOUTCOM_IDEAL,\n fawry: PaymentStrategyType.CHECKOUTCOM_FAWRY,\n};\n\nexport default class PaymentStrategyRegistry extends Registry<\n PaymentStrategy,\n PaymentStrategyType\n> {\n constructor(\n private _store: ReadableDataStore,\n options?: PaymentStrategyRegistryOptions,\n ) {\n super(options);\n }\n\n getByMethod(paymentMethod?: PaymentMethod): PaymentStrategy {\n if (!paymentMethod) {\n return this.get();\n }\n\n const token = this._getToken(paymentMethod);\n\n const cacheToken = [paymentMethod.gateway, paymentMethod.id]\n .filter((value) => value !== undefined && value !== null)\n .join('-');\n\n return this.get(token, cacheToken);\n }\n\n private _getToken(paymentMethod: PaymentMethod): PaymentStrategyType {\n const features = this._store.getState().config.getStoreConfig()?.checkoutSettings.features;\n\n if (\n paymentMethod.id === 'squarev2' &&\n features &&\n features['PROJECT-4113.squarev2_web_payments_sdk']\n ) {\n throw new Error('SquareV2 requires using registryV2');\n }\n\n if (isPPSDKPaymentMethod(paymentMethod)) {\n return PaymentStrategyType.PPSDK;\n }\n\n if (paymentMethod.gateway === 'klarna') {\n return PaymentStrategyType.KLARNAV2;\n }\n\n if (paymentMethod.gateway === PaymentStrategyType.CHECKOUTCOM) {\n return paymentMethod.id in checkoutcomStrategies\n ? checkoutcomStrategies[paymentMethod.id]\n : PaymentStrategyType.CHECKOUTCOM_APM;\n }\n\n const methodId = paymentMethod.gateway || paymentMethod.id;\n\n if (this._hasFactoryForMethod(methodId)) {\n return methodId;\n }\n\n if (paymentMethod.type === paymentMethodTypes.OFFLINE) {\n return PaymentStrategyType.OFFLINE;\n }\n\n throw new InvalidArgumentError(`'${methodId}' is not registered.`);\n }\n\n private _hasFactoryForMethod(methodId: string): methodId is PaymentStrategyType {\n return this._hasFactory(methodId);\n }\n}\n\nexport interface PaymentStrategyRegistryOptions extends RegistryOptions {\n clientSidePaymentProviders?: string[];\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { ContentType, INTERNAL_USE_ONLY, SDK_VERSION_HEADERS } from '../common/http-request';\n\nexport default class StorefrontPaymentRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n async saveExternalId(methodId: string, token: string): Promise {\n const url = `/api/storefront/payment/${methodId}/save-external-id`;\n const options = {\n headers: {\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n body: {\n externalId: token,\n provider: methodId,\n },\n };\n\n await this._requestSender.post(url, options);\n }\n}\n","import { ScriptLoader, StylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { AdyenClient, AdyenConfiguration, AdyenHostWindow } from './adyenv2';\n\nexport default class AdyenV2ScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _stylesheetLoader: StylesheetLoader,\n private _window: AdyenHostWindow = window,\n ) {}\n\n async load(configuration: AdyenConfiguration): Promise {\n await Promise.all([\n this._stylesheetLoader.loadStylesheet(\n `https://checkoutshopper-${configuration.environment}.adyen.com/checkoutshopper/sdk/3.10.1/adyen.css`,\n ),\n this._scriptLoader.loadScript(\n `https://checkoutshopper-${configuration.environment}.adyen.com/checkoutshopper/sdk/3.10.1/adyen.js`,\n ),\n ]);\n\n if (!this._window.AdyenCheckout) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return new this._window.AdyenCheckout(configuration);\n }\n}\n","import { ScriptLoader, StylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { AdyenClient, AdyenConfiguration, AdyenHostWindow } from './adyenv3';\n\nexport default class AdyenV3ScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _stylesheetLoader: StylesheetLoader,\n private _window: AdyenHostWindow = window,\n ) {}\n\n async load(configuration: AdyenConfiguration): Promise {\n await Promise.all([\n this._stylesheetLoader.loadStylesheet(\n `https://checkoutshopper-${configuration.environment}.adyen.com/checkoutshopper/sdk/5.24.0/adyen.css`,\n ),\n this._scriptLoader.loadScript(\n `https://checkoutshopper-${configuration.environment}.adyen.com/checkoutshopper/sdk/5.24.0/adyen.js`,\n ),\n ]);\n\n if (!this._window.AdyenCheckout) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n const checkout = await this._window.AdyenCheckout(configuration);\n\n return checkout;\n }\n}\n","import { InvalidArgumentError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when we are unable to submit a payment because\n * the caller has not provided all the required fields, i.e.: if an argument is\n * missing or it is not the expected data type.\n */\nexport default class PaymentArgumentInvalidError extends InvalidArgumentError {\n constructor(invalidFields?: string[]) {\n let message = 'Unable to submit payment for the order because the payload is invalid.';\n\n if (invalidFields) {\n message = `${message} Make sure the following fields are provided correctly: ${invalidFields.join(\n ', ',\n )}.`;\n }\n\n super(message);\n\n this.name = 'PaymentArgumentInvalidError';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when the payment flow is cancelled. It could be\n * due to a deliberate user interaction, i.e.: the user clicks on a cancel\n * button which dismisses the payment modal.\n */\nexport default class PaymentMethodCancelledError extends StandardError {\n constructor(message?: string) {\n super(message || 'Payment process was cancelled.');\n\n this.name = 'PaymentMethodCancelledError';\n this.type = 'payment_cancelled';\n }\n}\n","import { PaymentMethodInvalidError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { LineItemCategory } from '../../../cart';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { AmountTransformer } from '../../../common/utility';\nimport { Order, OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { Consignment } from '../../../shipping';\nimport { PaymentArgumentInvalidError, PaymentMethodCancelledError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport {\n Affirm,\n AffirmAddress,\n AffirmDiscount,\n AffirmFailResponse,\n AffirmItem,\n AffirmRequestData,\n AffirmSuccessResponse,\n} from './affirm';\nimport AffirmScriptLoader from './affirm-script-loader';\n\nexport default class AffirmPaymentStrategy implements PaymentStrategy {\n private _affirm?: Affirm;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _affirmScriptLoader: AffirmScriptLoader,\n ) {}\n\n initialize(options: PaymentInitializeOptions): Promise {\n return this._store\n .dispatch(this._paymentMethodActionCreator.loadPaymentMethod(options.methodId))\n .then((state) => {\n const paymentMethod = state.paymentMethods.getPaymentMethod(options.methodId);\n\n if (!paymentMethod || !paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n config: { testMode },\n clientToken: publicKey,\n } = paymentMethod;\n\n return this._affirmScriptLoader.load(publicKey, testMode);\n })\n .then((affirm) => {\n this._affirm = affirm;\n\n return this._store.getState();\n });\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const methodId = payload.payment && payload.payment.methodId;\n const { useStoreCredit } = payload;\n const { _affirm } = this;\n\n if (!_affirm) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n return this._store\n .dispatch(this._orderActionCreator.submitOrder({ useStoreCredit }, options))\n .then(() => {\n _affirm.checkout(this._getCheckoutInformation());\n\n return new Promise((resolve, reject) => {\n _affirm.checkout.open({\n onFail: (failObject: AffirmFailResponse) => {\n failObject.reason === 'canceled'\n ? reject(new PaymentMethodCancelledError())\n : reject(new PaymentMethodInvalidError());\n },\n onSuccess: (successObject) => {\n resolve(successObject);\n },\n });\n _affirm.ui.error.on('close', () => {\n reject(new PaymentMethodCancelledError());\n });\n });\n })\n .then((result) => {\n const paymentPayload = {\n methodId,\n paymentData: { nonce: result.checkout_token },\n };\n\n return this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentPayload),\n );\n });\n }\n\n deinitialize(): Promise {\n if (this._affirm) {\n this._affirm = undefined;\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private _getCheckoutInformation(): AffirmRequestData {\n const state = this._store.getState();\n const config = state.config.getStoreConfig();\n const consignments = state.consignments.getConsignments();\n const order = state.order.getOrder();\n\n if (!config) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n if (!order) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const amountTransformer = new AmountTransformer(order.currency.decimalPlaces);\n const billingAddress = this._getBillingAddress();\n\n return {\n merchant: {\n user_confirmation_url: config.links.checkoutLink,\n user_cancel_url: config.links.checkoutLink,\n user_confirmation_url_action: 'POST',\n },\n shipping: this._getShippingAddress() || billingAddress,\n billing: billingAddress,\n items: this._getItems(amountTransformer, order),\n metadata: {\n shipping_type: this._getShippingType(consignments),\n mode: 'modal',\n platform_type: 'BigCommerce',\n platform_version: '',\n platform_affirm: '',\n },\n discounts: this._getDiscounts(amountTransformer, order),\n order_id: order.orderId ? order.orderId.toString() : '',\n shipping_amount: amountTransformer.toInteger(order.shippingCostTotal),\n tax_amount: amountTransformer.toInteger(order.taxTotal),\n total: amountTransformer.toInteger(order.orderAmount),\n };\n }\n\n private _getShippingType(consignments?: Consignment[]): string {\n if (!consignments) {\n return '';\n }\n\n const consignment = consignments[0];\n\n return consignment && consignment.selectedShippingOption\n ? consignment.selectedShippingOption.type\n : '';\n }\n\n private _getBillingAddress(): AffirmAddress {\n const state = this._store.getState();\n const billingAddress = state.billingAddress.getBillingAddress();\n\n if (!billingAddress) {\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n\n const billingInformation = {\n name: {\n first: billingAddress.firstName,\n last: billingAddress.lastName,\n full: `${billingAddress.firstName} ${billingAddress.lastName}`,\n },\n address: {\n line1: billingAddress.address1,\n line2: billingAddress.address2,\n city: billingAddress.city,\n state: billingAddress.stateOrProvinceCode,\n zipcode: billingAddress.postalCode,\n country: billingAddress.countryCode,\n },\n phone_number: billingAddress.phone,\n email: billingAddress.email,\n };\n\n return billingInformation;\n }\n\n private _getShippingAddress(): AffirmAddress | undefined {\n const state = this._store.getState();\n const shippingAddress = state.shippingAddress.getShippingAddress();\n\n if (!shippingAddress) {\n return;\n }\n\n const shippingInformation = {\n name: {\n first: shippingAddress.firstName,\n last: shippingAddress.lastName,\n full: `${shippingAddress.firstName} ${shippingAddress.lastName}`,\n },\n address: {\n line1: shippingAddress.address1,\n line2: shippingAddress.address2,\n city: shippingAddress.city,\n state: shippingAddress.stateOrProvinceCode,\n zipcode: shippingAddress.postalCode,\n country: shippingAddress.countryCode,\n },\n phone_number: shippingAddress.phone,\n };\n\n return shippingInformation;\n }\n\n private _getItems(amountTransformer: AmountTransformer, order: Order): AffirmItem[] {\n const items: AffirmItem[] = [];\n\n for (const item of order.lineItems.physicalItems) {\n items.push({\n display_name: item.name,\n sku: item.sku,\n unit_price: amountTransformer.toInteger(item.salePrice),\n qty: item.quantity,\n item_image_url: item.imageUrl,\n item_url: item.url,\n categories: this._getCategories(item.categories),\n });\n }\n\n for (const item of order.lineItems.digitalItems) {\n items.push({\n display_name: item.name,\n sku: item.sku,\n unit_price: amountTransformer.toInteger(item.salePrice),\n qty: item.quantity,\n item_image_url: item.imageUrl,\n item_url: item.url,\n categories: this._getCategories(item.categories),\n });\n }\n\n for (const item of order.lineItems.giftCertificates) {\n items.push({\n display_name: item.name,\n sku: '',\n unit_price: amountTransformer.toInteger(item.amount),\n qty: 1,\n item_image_url: '',\n item_url: '',\n });\n }\n\n if (order.lineItems.customItems) {\n for (const item of order.lineItems.customItems) {\n items.push({\n display_name: item.name,\n sku: item.sku,\n unit_price: amountTransformer.toInteger(item.listPrice),\n qty: item.quantity,\n item_image_url: '',\n item_url: '',\n });\n }\n }\n\n return items;\n }\n\n private _getDiscounts(amountTransformer: AmountTransformer, order: Order): AffirmDiscount {\n const discounts: AffirmDiscount = {};\n\n for (const line of order.coupons) {\n if (line.discountedAmount > 0) {\n discounts[line.code] = {\n discount_amount: amountTransformer.toInteger(line.discountedAmount),\n discount_display_name: line.displayName,\n };\n }\n }\n\n if (order.discountAmount > 0) {\n discounts.DISCOUNTED_AMOUNT = {\n discount_amount: amountTransformer.toInteger(order.discountAmount),\n discount_display_name: 'discount',\n };\n }\n\n return discounts;\n }\n\n private _getCategories(categories?: LineItemCategory[][]): string[][] {\n if (!categories) {\n return [[]];\n }\n\n return categories.map((categoryTree) => categoryTree.map((category) => category.name));\n }\n}\n","import { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { Affirm, AffirmHostWindow, AffirmScripts } from './affirm';\nimport loadAffirmJS from './affirmJs';\n\nexport default class AffirmScriptLoader {\n constructor(public _window: AffirmHostWindow = window) {}\n\n load(apikey = '', testMode?: boolean): Promise {\n const scriptURI = this._getScriptURI(testMode);\n\n loadAffirmJS(apikey, scriptURI);\n\n if (!this._window.affirm) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return Promise.resolve(this._window.affirm);\n }\n\n private _getScriptURI(testMode = false): string {\n const SCRIPTS_DEFAULT: AffirmScripts = {\n PROD: '//cdn1.affirm.com/js/v2/affirm.js',\n SANDBOX: '//cdn1-sandbox.affirm.com/js/v2/affirm.js',\n };\n\n return testMode ? SCRIPTS_DEFAULT.SANDBOX : SCRIPTS_DEFAULT.PROD;\n }\n}\n","/**\n * Used this approach as Affirm uses snipped for initializing. Please refer to Affirm documentation in: https://docs.affirm.com/Integrate_Affirm/Direct_API#1._Add_Affirm.js\n */\nimport { Affirm, AffirmHostWindow } from './affirm';\n\ninterface AffirmConfig {\n public_api_key: string;\n script: string;\n}\n\nexport default function loadAffirmJS(apiKey: string, scriptURL: string) {\n const _AFFIRM_CONFIG: AffirmConfig = {\n public_api_key: apiKey,\n script: scriptURL,\n };\n\n (function foo(\n m: AffirmHostWindow | any,\n g: AffirmConfig,\n n: 'affirm',\n d: 'checkout',\n a: 'ui',\n e: 'script',\n h: 'ready',\n c: 'jsReady',\n ) {\n const b = m[n] || {};\n const k = document.createElement(e);\n const p = document.getElementsByTagName(e)[0];\n const l = function bar(a: Affirm | any, b: keyof Affirm, c: string) {\n return function baz() {\n a[b]._.push([c, arguments]); /* eslint-disable-line */\n };\n };\n\n b[d] = l(b, d, 'set');\n\n const f = b[d];\n\n b[a] = {};\n b[a]._ = [];\n f._ = [];\n b._ = [];\n b[a][h] = l(b, a, h);\n\n b[c] = function qux() {\n b._.push([h, arguments]); /* eslint-disable-line */\n };\n\n let a1 = 0;\n\n for (\n const c1 = 'set add save post open empty reset on off trigger ready setProduct'.split(\n ' ',\n );\n a1 < c1.length;\n a1++\n ) {\n f[c1[a1]] = l(b, d, c1[a1]);\n }\n\n let a2 = 0;\n\n for (const c2 = ['get', 'token', 'url', 'items']; a2 < c2.length; a2++) {\n f[c2[a2]] = function foobar() {};\n }\n\n k.async = !0;\n k.src = g[e];\n\n if (p.parentNode) {\n p.parentNode.insertBefore(k, p);\n }\n\n delete (g as Partial)[e];\n f(g);\n m[n] = b;\n })(window, _AFFIRM_CONFIG, 'affirm', 'checkout', 'ui', 'script', 'ready', 'jsReady');\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if the order finalization request\n * was not completed successfully.\n */\nexport default class OrderFinalizationNotCompletedError extends StandardError {\n constructor(message?: string) {\n super(message || 'The current order could not be finalized successfully');\n\n this.name = 'OrderFinalizationNotCompletedError';\n this.type = 'order_finalization_not_completed';\n }\n}\n","import { CheckoutStore, CheckoutValidator, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { RequestOptions } from '../../../common/http-request';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotCompletedError } from '../../../order/errors';\nimport { RemoteCheckoutRequestSender } from '../../../remote-checkout';\nimport { StoreCreditActionCreator } from '../../../store-credit';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport AfterpayScriptLoader from './afterpay-script-loader';\nimport AfterpaySdk from './afterpay-sdk';\n\nexport default class AfterpayPaymentStrategy implements PaymentStrategy {\n private _afterpaySdk?: AfterpaySdk;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutValidator: CheckoutValidator,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _remoteCheckoutRequestSender: RemoteCheckoutRequestSender,\n private _storeCreditActionCreator: StoreCreditActionCreator,\n private _afterpayScriptLoader: AfterpayScriptLoader,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const state = this._store.getState();\n const paymentMethod = state.paymentMethods.getPaymentMethod(\n options.methodId,\n options.gatewayId,\n );\n const currencyCode = state.cart.getCart()?.currency.code || '';\n const countryCode = this._mapCurrencyToISO2(currencyCode);\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._afterpaySdk = await this._afterpayScriptLoader.load(paymentMethod, countryCode);\n\n return this._store.getState();\n }\n\n deinitialize(): Promise {\n if (this._afterpaySdk) {\n this._afterpaySdk = undefined;\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n if (!payload.payment) {\n throw new PaymentArgumentInvalidError(['payment.gatewayId', 'payment.methodId']);\n }\n\n const { gatewayId, methodId } = payload.payment;\n\n if (!gatewayId || !methodId) {\n throw new PaymentArgumentInvalidError(['payment.gatewayId', 'payment.methodId']);\n }\n\n let state = this._store.getState();\n const currencyCode = state.cart.getCart()?.currency.code || '';\n const countryCode = this._mapCurrencyToISO2(currencyCode);\n const { useStoreCredit } = payload;\n\n if (useStoreCredit !== undefined) {\n state = await this._store.dispatch(\n this._storeCreditActionCreator.applyStoreCredit(useStoreCredit),\n );\n }\n\n await this._checkoutValidator.validate(state.checkout.getCheckout(), options);\n\n state = await this._loadPaymentMethod(gatewayId, methodId, options);\n\n await this._redirectToAfterpay(\n countryCode,\n state.paymentMethods.getPaymentMethod(methodId, gatewayId),\n );\n\n // Afterpay will handle the rest of the flow so return a promise that doesn't really resolve\n return new Promise(() => {});\n }\n\n async finalize(options: PaymentRequestOptions): Promise {\n const state = this._store.getState();\n const payment = state.payment.getPaymentId();\n const config = state.config.getContextConfig();\n\n if (!payment) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!config || !config.payment.token) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const paymentPayload = {\n methodId: payment.providerId,\n paymentData: { nonce: config.payment.token },\n };\n\n await this._store.dispatch(this._orderActionCreator.submitOrder({}, options));\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentPayload),\n );\n } catch (error) {\n await this._remoteCheckoutRequestSender.forgetCheckout();\n await this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethods());\n\n throw new OrderFinalizationNotCompletedError(error.body?.errors?.[0]?.message);\n }\n }\n\n private _redirectToAfterpay(countryCode: string, paymentMethod?: PaymentMethod): void {\n if (!this._afterpaySdk || !paymentMethod || !paymentMethod.clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._afterpaySdk.initialize({ countryCode });\n this._afterpaySdk.redirect({ token: paymentMethod.clientToken });\n }\n\n private _mapCurrencyToISO2(currencyCode: string): string {\n const countryByCurrency: { [key: string]: string } = {\n AUD: 'AU',\n NZD: 'NZ',\n CAD: 'CA',\n USD: 'US',\n };\n\n return countryByCurrency[currencyCode] || 'AU';\n }\n\n private async _loadPaymentMethod(\n gatewayId: string,\n methodId: string,\n options?: RequestOptions,\n ): Promise {\n try {\n return await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(gatewayId, {\n ...options,\n params: { ...options?.params, method: methodId },\n }),\n );\n } catch (error) {\n if (error instanceof RequestError && error.body?.status === 422) {\n throw new InvalidArgumentError(\n \"Afterpay can't process your payment for this order, please try another payment method\",\n );\n }\n\n throw error;\n }\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport PaymentMethod from '../../payment-method';\n\nimport AfterpaySdk from './afterpay-sdk';\nimport AfterpayWindow from './afterpay-window';\n\ninterface AfterpayScripts {\n PROD: string;\n SANDBOX: string;\n}\n\nconst SCRIPTS_DEFAULT: AfterpayScripts = {\n PROD: '//portal.afterpay.com/afterpay-async.js',\n SANDBOX: '//portal-sandbox.afterpay.com/afterpay-async.js',\n};\n\nconst SCRIPTS_US: AfterpayScripts = {\n PROD: '//portal.afterpay.com/afterpay-async.js',\n SANDBOX: '//portal.sandbox.afterpay.com/afterpay-async.js',\n};\n\n/** Class responsible for loading the Afterpay SDK */\nexport default class AfterpayScriptLoader {\n constructor(private _scriptLoader: ScriptLoader) {}\n\n /**\n * Loads the appropriate Afterpay SDK depending on the payment method data.\n *\n * @param method the payment method data\n */\n load(method: PaymentMethod, countryCode: string): Promise {\n const testMode = method.config.testMode || false;\n const scriptURI = this._getScriptURI(countryCode, testMode);\n\n return this._scriptLoader\n .loadScript(scriptURI)\n .then(() => (window as unknown as AfterpayWindow).AfterPay);\n }\n\n private _getScriptURI(countryCode: string, testMode: boolean): string {\n if (countryCode === 'US') {\n return testMode ? SCRIPTS_US.SANDBOX : SCRIPTS_US.PROD;\n }\n\n return testMode ? SCRIPTS_DEFAULT.SANDBOX : SCRIPTS_DEFAULT.PROD;\n }\n}\n","import { noop } from 'lodash';\n\nimport { CheckoutSettings } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { guard } from '../../../../src/common/utility';\nimport { StoreProfile } from '../../../../src/config';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError, PaymentMethodCancelledError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategyActionCreator from '../../payment-strategy-action-creator';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { AmazonPayV2ChangeActionType, AmazonPayV2Placement } from './amazon-pay-v2';\nimport AmazonPayV2PaymentProcessor from './amazon-pay-v2-payment-processor';\n\nexport default class AmazonPayV2PaymentStrategy implements PaymentStrategy {\n private _amazonPayButton?: HTMLDivElement;\n\n constructor(\n private _store: CheckoutStore,\n private _paymentStrategyActionCreator: PaymentStrategyActionCreator,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _amazonPayV2PaymentProcessor: AmazonPayV2PaymentProcessor,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const { methodId, amazonpay } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n const { features } = this._store.getState().config.getStoreConfigOrThrow().checkoutSettings;\n const paymentMethod = this._store\n .getState()\n .paymentMethods.getPaymentMethodOrThrow(methodId);\n const {\n initializationData: { paymentToken, region },\n } = paymentMethod;\n\n await this._amazonPayV2PaymentProcessor.initialize(paymentMethod);\n\n if (this._isReadyToPay(paymentToken)) {\n if (amazonpay?.editButtonId) {\n this._bindEditButton(\n amazonpay.editButtonId,\n paymentToken,\n 'changePayment',\n this._isModalFlow(region),\n );\n }\n } else {\n const { id: containerId } = this._createContainer();\n\n this._amazonPayButton = this._amazonPayV2PaymentProcessor.renderAmazonPayButton({\n checkoutState: this._store.getState(),\n containerId,\n decoupleCheckoutInitiation: this._isOneTimeTransaction(\n features,\n region.toUpperCase(),\n ),\n methodId,\n placement: AmazonPayV2Placement.Checkout,\n });\n }\n\n return this._store.getState();\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId } = payment;\n\n const { features } = this._store.getState().config.getStoreConfigOrThrow().checkoutSettings;\n const { region, paymentToken } = this._store\n .getState()\n .paymentMethods.getPaymentMethodOrThrow(methodId).initializationData;\n\n if (\n this._isReadyToPay(paymentToken) ||\n this._isOneTimeTransaction(features, region.toUpperCase())\n ) {\n const paymentPayload = {\n methodId,\n paymentData: { nonce: paymentToken || 'apb' },\n };\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(payload, options));\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentPayload),\n );\n } catch (error) {\n if (\n error instanceof RequestError &&\n error.body.status === 'additional_action_required'\n ) {\n if (paymentToken) {\n return new Promise(() =>\n window.location.assign(\n error.body.additional_action_required.data.redirect_url,\n ),\n );\n }\n\n this._amazonPayV2PaymentProcessor.prepareCheckout(\n JSON.parse(error.body.additional_action_required.data.redirect_url),\n );\n } else {\n throw error;\n }\n }\n }\n\n this._getAmazonPayButton().click();\n\n // Focus of parent window used to try and detect the user cancelling the Amazon log in modal\n // Should be refactored if/when Amazon add a modal close hook to their SDK\n if (this._isModalFlow(region)) {\n return new Promise((_, reject) => {\n const onFocus = () => {\n window.removeEventListener('focus', onFocus);\n reject(\n new PaymentMethodCancelledError(\n 'Shopper needs to login to Amazonpay to continue',\n ),\n );\n };\n\n window.addEventListener('focus', onFocus);\n });\n }\n\n return new Promise(noop);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n await this._amazonPayV2PaymentProcessor.deinitialize();\n\n this._amazonPayButton = undefined;\n\n return this._store.getState();\n }\n\n private _bindEditButton(\n buttonId: string,\n sessionId: string,\n changeAction: AmazonPayV2ChangeActionType,\n isModalFlow: boolean,\n ): void {\n const button = document.getElementById(buttonId);\n\n if (!button || !button.parentNode) {\n return;\n }\n\n if (!isModalFlow) {\n const clone = button.cloneNode(true);\n\n button.parentNode.replaceChild(clone, button);\n\n clone.addEventListener('click', () => this._showLoadingSpinner());\n }\n\n this._amazonPayV2PaymentProcessor.bindButton(buttonId, sessionId, changeAction);\n }\n\n private _isModalFlow(region: string) {\n return region === 'us';\n }\n\n private _showLoadingSpinner(): Promise {\n return this._store.dispatch(\n this._paymentStrategyActionCreator.widgetInteraction(() => new Promise(noop)),\n { queueId: 'widgetInteraction' },\n );\n }\n\n private _createContainer(): HTMLDivElement {\n let container = document.getElementById('AmazonPayButton') as HTMLDivElement;\n\n if (container) {\n return container;\n }\n\n container = document.createElement('div');\n container.id = 'AmazonPayButton';\n container.style.display = 'none';\n\n return document.body.appendChild(container);\n }\n\n private _getAmazonPayButton() {\n return guard(\n this._amazonPayButton,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n private _isOneTimeTransaction(\n features: CheckoutSettings['features'],\n storeCountryCode: StoreProfile['storeCountryCode'],\n ): boolean {\n return (\n this._amazonPayV2PaymentProcessor.isPh4Enabled(features, storeCountryCode) &&\n features['INT-6399.amazon_pay_apb']\n );\n }\n\n private _isReadyToPay(paymentToken?: string): boolean {\n return !!paymentToken;\n }\n}\n","import { isNil, values } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { HostedForm, HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nexport default class CreditCardPaymentStrategy implements PaymentStrategy {\n protected _hostedForm?: HostedForm;\n protected _shouldRenderHostedForm?: boolean;\n\n constructor(\n protected _store: CheckoutStore,\n protected _orderActionCreator: OrderActionCreator,\n protected _paymentActionCreator: PaymentActionCreator,\n protected _hostedFormFactory: HostedFormFactory,\n ) {}\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n return this._isHostedPaymentFormEnabled(\n payload.payment?.methodId,\n payload.payment?.gatewayId,\n ) && this._shouldRenderHostedForm\n ? this._executeWithHostedForm(payload, options)\n : this._executeWithoutHostedForm(payload, options);\n }\n\n finalize(_options?: PaymentRequestOptions): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(options?: PaymentInitializeOptions): Promise {\n if (\n !this._isHostedPaymentFormEnabled(options?.methodId, options?.gatewayId) ||\n !this._isHostedFieldAvailable(options)\n ) {\n this._shouldRenderHostedForm = false;\n\n return Promise.resolve(this._store.getState());\n }\n\n const formOptions = options && options.creditCard && options.creditCard.form;\n const { config } = this._store.getState();\n const { paymentSettings: { bigpayBaseUrl: host = '' } = {} } =\n config.getStoreConfig() || {};\n\n if (!formOptions) {\n throw new InvalidArgumentError();\n }\n\n const form = this._hostedFormFactory.create(host, formOptions);\n\n return form.attach().then(() => {\n this._shouldRenderHostedForm = true;\n this._hostedForm = form;\n\n return this._store.getState();\n });\n }\n\n deinitialize(_options?: PaymentRequestOptions): Promise {\n if (this._hostedForm) {\n this._hostedForm.detach();\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n protected _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment && payment.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n return this._store\n .dispatch(this._orderActionCreator.submitOrder(order, options))\n .then(() =>\n this._store.dispatch(\n this._paymentActionCreator.submitPayment({ ...payment, paymentData }),\n ),\n );\n }\n\n protected _executeWithHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!payment || !payment.methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n return form\n .validate()\n .then(() => this._store.dispatch(this._orderActionCreator.submitOrder(order, options)))\n .then(() => form.submit(payment))\n .then(() => this._store.dispatch(this._orderActionCreator.loadCurrentOrder()));\n }\n\n protected _isHostedPaymentFormEnabled(methodId?: string, gatewayId?: string): boolean {\n if (!methodId) {\n return false;\n }\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(methodId, gatewayId);\n\n return paymentMethod.config.isHostedFormEnabled === true;\n }\n\n private _isHostedFieldAvailable(options?: PaymentInitializeOptions): boolean {\n return !values(options && options.creditCard && options.creditCard.form.fields).every(\n isNil,\n );\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { CardinalThreeDSecureFlowV2 } from '../cardinal';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class BarclaysPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _threeDSecureFlow: CardinalThreeDSecureFlowV2,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(options.methodId);\n\n if (paymentMethod.config.is3dsEnabled) {\n await this._threeDSecureFlow.prepare(paymentMethod);\n }\n\n return this._store.getState();\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment: { methodId = '' } = {} } = payload;\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n\n if (getPaymentMethodOrThrow(methodId).config.is3dsEnabled) {\n return this._threeDSecureFlow.start(\n super.execute.bind(this),\n payload,\n options,\n this._hostedForm,\n );\n }\n\n return super.execute(payload, options);\n }\n}\n","export const ACKNOWLEDGE = 'ACKNOWLEDGE';\nexport const FINALIZE = 'FINALIZE';\nexport const INITIALIZE = 'INITIALIZE';\n","import { noop } from 'lodash';\n\nimport { CancellablePromise } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError, PaymentMethodCancelledError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { BlueSnapV2StyleProps } from './bluesnapv2';\nimport { BlueSnapV2PaymentInitializeOptions } from './bluesnapv2-payment-options';\n\nconst IFRAME_NAME = 'bluesnapv2_hosted_payment_page';\n\nexport default class BlueSnapV2PaymentStrategy implements PaymentStrategy {\n private _initializeOptions?: BlueSnapV2PaymentInitializeOptions;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n ) {}\n\n async execute(\n orderRequest: OrderRequestBody,\n options?: PaymentInitializeOptions,\n ): Promise {\n const { payment } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!this._initializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { onLoad, style } = this._initializeOptions;\n const frame = this._createIframe(IFRAME_NAME, style);\n const promise = new CancellablePromise(new Promise(noop));\n\n onLoad(frame, () => promise.cancel(new PaymentMethodCancelledError()));\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(orderRequest, options));\n\n return this._store.dispatch(\n this._paymentActionCreator.initializeOffsitePayment({\n methodId: payment.methodId,\n gatewayId: payment.gatewayId,\n shouldSaveInstrument: false,\n target: frame.name,\n promise: promise.promise,\n }),\n );\n }\n\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this._store.getState();\n const order = state.order.getOrder();\n const status = state.payment.getPaymentStatus();\n\n if (\n order &&\n (status === paymentStatusTypes.ACKNOWLEDGE || status === paymentStatusTypes.FINALIZE)\n ) {\n return this._store.dispatch(\n this._orderActionCreator.finalizeOrder(order.orderId, options),\n );\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(options?: PaymentInitializeOptions): Promise {\n this._initializeOptions = options && options.bluesnapv2;\n\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n private _createIframe(name: string, style?: BlueSnapV2StyleProps): HTMLIFrameElement {\n const iframe = document.createElement('iframe');\n\n iframe.setAttribute(\n 'sandbox',\n 'allow-top-navigation allow-scripts allow-forms allow-same-origin',\n );\n\n iframe.name = name;\n\n if (style) {\n const { border, height, width } = style;\n\n iframe.style.border = border as string;\n iframe.style.height = height as string;\n iframe.style.width = width as string;\n }\n\n return iframe;\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { CardinalThreeDSecureFlowV2 } from '../cardinal';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class BNZPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _threeDSecureFlow: CardinalThreeDSecureFlowV2,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(options.methodId);\n\n if (paymentMethod.config.is3dsEnabled) {\n await this._threeDSecureFlow.prepare(paymentMethod);\n }\n\n return this._store.getState();\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n if (!payload.payment) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n const { methodId } = payload.payment;\n\n if (!methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n\n if (getPaymentMethodOrThrow(methodId).config.is3dsEnabled) {\n return this._threeDSecureFlow.start(\n super.execute.bind(this),\n payload,\n options,\n this._hostedForm,\n );\n }\n\n return super.execute(payload, options);\n }\n}\n","import getOverlayStyle from './overlay-style';\n\nexport interface OverlayOptions {\n background?: string;\n id?: string;\n transitionDuration?: number;\n hasCloseButton?: boolean;\n innerHtml?: HTMLElement | DocumentFragment;\n}\n\nexport interface OverlayShowOptions {\n onClick?(event: MouseEvent): void;\n onClickClose?(event: MouseEvent): void;\n}\n\nexport interface Elements {\n element: HTMLElement;\n mainElement: HTMLElement;\n closeElement?: HTMLElement;\n}\n\nexport default class Overlay {\n private _element: HTMLElement;\n private _mainElement: HTMLElement;\n private _closeElement?: HTMLElement;\n private _unregisterClick?: () => void;\n\n constructor(options?: OverlayOptions) {\n const { element, closeElement, mainElement } = this._createElements(options);\n\n this._element = element;\n this._closeElement = closeElement;\n this._mainElement = mainElement;\n }\n\n show(options?: OverlayShowOptions): void {\n if (this._mainElement.parentElement) {\n return;\n }\n\n this._registerClick(options);\n\n document.body.appendChild(this._mainElement);\n\n // Fade In\n setTimeout(() => (this._element.style.opacity = '1'));\n }\n\n remove(): void {\n if (!this._mainElement.parentElement) {\n return;\n }\n\n if (this._unregisterClick) {\n this._unregisterClick();\n }\n\n this._removeAfterTransition();\n\n setTimeout(() => (this._element.style.opacity = '0'));\n }\n\n private _createElements(options?: OverlayOptions): Elements {\n const element = document.createElement('div');\n const {\n background = 'rgba(0, 0, 0, 0.8)',\n id = 'checkoutOverlay',\n transitionDuration = 400,\n hasCloseButton = false,\n innerHtml = null,\n } = options || {};\n let mainElement = element;\n let closeElement: HTMLElement | undefined;\n let classLayout: string | undefined;\n let classClose: string | undefined;\n let classOverlayText: string | undefined;\n\n if (id) {\n element.id = id;\n }\n\n if (innerHtml) {\n const overlayText = document.createElement('div');\n\n classOverlayText = `${id}--overlayText`;\n overlayText.className = classOverlayText;\n overlayText.appendChild(innerHtml);\n\n element.appendChild(overlayText);\n }\n\n if (hasCloseButton) {\n classClose = `${id}--close`;\n closeElement = document.createElement('div');\n closeElement.className = classClose;\n\n classLayout = `${id}--layout`;\n mainElement = document.createElement('div');\n mainElement.className = classLayout;\n\n mainElement.appendChild(element);\n mainElement.appendChild(closeElement);\n }\n\n mainElement.appendChild(\n getOverlayStyle({\n id,\n background,\n transitionDuration,\n classLayout,\n classOverlayText,\n classClose,\n }),\n );\n\n return { element, closeElement, mainElement };\n }\n\n private _addEventListener(element?: HTMLElement, onClick?: (event: MouseEvent) => void): void {\n if (!element || !onClick) {\n return;\n }\n\n element.addEventListener('click', onClick);\n }\n\n private _removeEventListener(\n element?: HTMLElement,\n onClick?: (event: MouseEvent) => void,\n ): void {\n if (!element || !onClick) {\n return;\n }\n\n element.removeEventListener('click', onClick);\n }\n\n private _registerClick(options?: OverlayShowOptions): void {\n if (this._unregisterClick) {\n this._unregisterClick();\n }\n\n if (options) {\n const { onClick, onClickClose } = options;\n\n this._addEventListener(this._element, onClick);\n this._addEventListener(this._closeElement, onClickClose);\n\n this._unregisterClick = () => {\n this._removeEventListener(this._element, onClick);\n this._removeEventListener(this._closeElement, onClickClose);\n this._unregisterClick = undefined;\n };\n }\n }\n\n private _removeAfterTransition(): void {\n const handleTransition: (event: Event) => void = (event) => {\n // NOTE: `event` is not correctly typed in this version of TS\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n if ((event as TransitionEvent).propertyName !== 'opacity') {\n return;\n }\n\n if (this._mainElement.parentElement) {\n this._mainElement.remove();\n }\n\n this._element.removeEventListener('transitionend', handleTransition);\n };\n\n this._element.addEventListener('transitionend', handleTransition);\n }\n}\n","interface OverlayStyleOptions {\n background?: string;\n id?: string;\n transitionDuration?: number;\n classLayout?: string;\n classOverlayText?: string;\n classClose?: string;\n}\n\nexport default function getOverlayStyle(options: OverlayStyleOptions): HTMLElement {\n const { id, background, transitionDuration, classLayout, classOverlayText, classClose } =\n options;\n const styles = document.createElement('style');\n const addClassLayout = classLayout ? `, .${classLayout}` : '';\n\n styles.id = `${id}--styles`;\n styles.type = 'text/css';\n styles.innerText = `\n #${id}${addClassLayout} {\n display: block;\n height: 100%;\n width: 100%;\n left: 0;\n top: 0;\n position: fixed;\n z-index: 2147483647;\n }\n #${id} {\n transition: opacity ${transitionDuration}ms ease-out;\n background: ${background};\n opacity: 0;\n }\n `;\n\n if (classOverlayText) {\n styles.innerText += `\n #${id} {\n display: flex;\n align-items: center;\n justify-content: center;\n }\n #${id} .${classOverlayText} {\n color: white;\n max-width: 330px;\n font-size: 1.2em;\n text-align: center;\n }\n `;\n }\n\n if (classClose) {\n styles.innerText += `\n #${id} {\n opacity: 1;\n }\n .${classLayout} .${classClose} {\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 .${classLayout} .${classClose}::after, .${classLayout} .${classClose}::before {\n position: absolute;\n left: 8px;\n content: '';\n height: 16px;\n width: 2px;\n background-color: #fff;\n }\n .${classLayout} .${classClose}::after {\n transform: rotate(-45deg);\n }\n .${classLayout} .${classClose}::before {\n transform: rotate(45deg);\n }\n `;\n }\n\n return styles;\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport interface PaymentInvalidFormErrorDetails {\n [key: string]: Array<{ message: string; type: string }>;\n}\n\nexport default class PaymentInvalidFormError extends StandardError {\n constructor(public details: PaymentInvalidFormErrorDetails, message?: string) {\n super(message || 'Unable to proceed because the payment form contains invalid data.');\n\n this.name = 'PaymentInvalidFormError';\n this.type = 'payment_invalid_form';\n }\n}\n","import { BraintreeFormErrorsData, BraintreeVerifyPayload } from './braintree';\n\n/**\n * A set of options that are required to initialize the Braintree payment\n * method. You need to provide the options if you want to support 3D Secure\n * authentication flow.\n *\n * ```html\n * \n *
\n *
\n *
\n *
\n * ```\n *\n * ```js\n * service.initializePayment({\n * methodId: 'braintree',\n * braintree: {\n * form: {\n * fields: {\n * cardNumber: { containerId: 'card-number' },\n * cardName: { containerId: 'card-name' },\n * cardExpiry: { containerId: 'card-expiry' },\n * cardCode: { containerId: 'card-code' },\n * },\n * },\n * },\n * });\n * ```\n *\n * Additional options can be passed in to customize the fields and register\n * event callbacks.\n *\n * ```js\n * service.initializePayment({\n * methodId: 'braintree',\n * creditCard: {\n * form: {\n * fields: {\n * cardNumber: { containerId: 'card-number' },\n * cardName: { containerId: 'card-name' },\n * cardExpiry: { containerId: 'card-expiry' },\n * cardCode: { containerId: 'card-code' },\n * },\n * styles: {\n * default: {\n * color: '#000',\n * },\n * error: {\n * color: '#f00',\n * },\n * focus: {\n * color: '#0f0',\n * },\n * },\n * onBlur({ fieldType }) {\n * console.log(fieldType);\n * },\n * onFocus({ fieldType }) {\n * console.log(fieldType);\n * },\n * onEnter({ fieldType }) {\n * console.log(fieldType);\n * },\n * onCardTypeChange({ cardType }) {\n * console.log(cardType);\n * },\n * onValidate({ errors, isValid }) {\n * console.log(errors);\n * console.log(isValid);\n * },\n * },\n * },\n * });\n * ```\n */\nexport interface BraintreePaymentInitializeOptions {\n threeDSecure?: BraintreeThreeDSecureOptions;\n\n /**\n * @alpha\n * Please note that this option is currently in an early stage of\n * development. Therefore the API is unstable and not ready for public\n * consumption.\n */\n form?: BraintreeFormOptions;\n}\n\n/**\n * A set of options that are required to support 3D Secure authentication flow.\n *\n * If the customer uses a credit card that has 3D Secure enabled, they will be\n * asked to verify their identity when they pay. The verification is done\n * through a web page via an iframe provided by the card issuer.\n */\nexport interface BraintreeThreeDSecureOptions {\n /**\n * A callback that gets called when the iframe is ready to be added to the\n * current page. It is responsible for determining where the iframe should\n * be inserted in the DOM.\n *\n * @param error - Any error raised during the verification process;\n * undefined if there is none.\n * @param iframe - The iframe element containing the verification web page\n * provided by the card issuer.\n * @param cancel - A function, when called, will cancel the verification\n * process and remove the iframe.\n */\n addFrame(\n error: Error | undefined,\n iframe: HTMLIFrameElement,\n cancel: () => Promise | undefined,\n ): void;\n\n /**\n * A callback that gets called when the iframe is about to be removed from\n * the current page.\n */\n removeFrame(): void;\n}\n\nexport interface BraintreeFormOptions {\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap;\n styles?: BraintreeFormFieldStylesMap;\n onBlur?(data: BraintreeFormFieldBlurEventData): void;\n onCardTypeChange?(data: BraintreeFormFieldCardTypeChangeEventData): void;\n onFocus?(data: BraintreeFormFieldFocusEventData): void;\n onValidate?(data: BraintreeFormFieldValidateEventData): void;\n onEnter?(data: BraintreeFormFieldEnterEventData): void;\n}\n\nexport enum BraintreeFormFieldType {\n CardCode = 'cardCode',\n CardCodeVerification = 'cardCodeVerification',\n CardExpiry = 'cardExpiry',\n CardName = 'cardName',\n CardNumber = 'cardNumber',\n CardNumberVerification = 'cardNumberVerification',\n}\n\nexport interface BraintreeFormFieldsMap {\n [BraintreeFormFieldType.CardCode]?: BraintreeFormFieldOptions;\n [BraintreeFormFieldType.CardExpiry]: BraintreeFormFieldOptions;\n [BraintreeFormFieldType.CardName]: BraintreeFormFieldOptions;\n [BraintreeFormFieldType.CardNumber]: BraintreeFormFieldOptions;\n}\n\nexport interface BraintreeStoredCardFieldsMap {\n [BraintreeFormFieldType.CardCodeVerification]?: BraintreeStoredCardFieldOptions;\n [BraintreeFormFieldType.CardNumberVerification]?: BraintreeStoredCardFieldOptions;\n}\n\nexport interface BraintreeFormFieldOptions {\n accessibilityLabel?: string;\n containerId: string;\n placeholder?: string;\n}\n\nexport interface BraintreeStoredCardFieldOptions extends BraintreeFormFieldOptions {\n instrumentId: string;\n}\n\nexport interface BraintreeFormFieldStylesMap {\n default?: BraintreeFormFieldStyles;\n error?: BraintreeFormFieldStyles;\n focus?: BraintreeFormFieldStyles;\n}\n\nexport type BraintreeFormFieldStyles = Partial<\n Pick\n>;\n\nexport interface BraintreeFormFieldKeyboardEventData {\n fieldType: string;\n errors?: BraintreeFormErrorsData;\n}\n\nexport type BraintreeFormFieldBlurEventData = BraintreeFormFieldKeyboardEventData;\nexport type BraintreeFormFieldEnterEventData = BraintreeFormFieldKeyboardEventData;\nexport type BraintreeFormFieldFocusEventData = BraintreeFormFieldKeyboardEventData;\n\nexport interface BraintreeFormFieldCardTypeChangeEventData {\n cardType?: string;\n}\n\nexport interface BraintreeFormFieldValidateEventData {\n errors: {\n [BraintreeFormFieldType.CardCode]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardExpiry]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardName]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardNumber]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardCodeVerification]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardNumberVerification]?: BraintreeFormFieldValidateErrorData[];\n };\n isValid: boolean;\n}\n\nexport interface BraintreeFormFieldValidateErrorData {\n fieldType: string;\n message: string;\n type: string;\n}\n","import { InvalidArgumentError } from '../../../common/error/errors';\n\nimport {\n BraintreeFormFieldOptions,\n BraintreeFormFieldStyles,\n BraintreeFormFieldStylesMap,\n} from './braintree-payment-options';\n\nexport default class BraintreeRegularField {\n private _input: HTMLInputElement;\n\n constructor(\n private _options: BraintreeFormFieldOptions,\n private _styles?: BraintreeFormFieldStylesMap,\n ) {\n this._input = document.createElement('input');\n this._input.style.backgroundColor = 'transparent';\n this._input.style.border = '0';\n this._input.style.display = 'block';\n this._input.style.height = '100%';\n this._input.style.margin = '0';\n this._input.style.outline = 'none';\n this._input.style.padding = '0';\n this._input.style.width = '100%';\n this._input.placeholder = this._options.placeholder || '';\n\n this._input.setAttribute('aria-label', this._options.accessibilityLabel || '');\n\n this._input.addEventListener('blur', this._handleBlur);\n this._input.addEventListener('focus', this._handleFocus);\n\n this._applyStyles(this._styles?.default);\n }\n\n getValue(): string {\n return this._input.value;\n }\n\n attach(): void {\n const container = document.getElementById(this._options.containerId);\n\n if (!container) {\n throw new InvalidArgumentError();\n }\n\n container.appendChild(this._input);\n }\n\n detach(): void {\n this._input.parentNode?.removeChild(this._input);\n }\n\n on(event: string, callback: () => void): void {\n this._input.addEventListener(event, callback);\n }\n\n off(event: string, callback: () => void): void {\n this._input.removeEventListener(event, callback);\n }\n\n private _applyStyles(styles?: BraintreeFormFieldStyles): void {\n if (!styles) {\n return;\n }\n\n const styleKeys = Object.keys(styles) as Array;\n\n styleKeys.forEach((key) => {\n this._input.style[key] = styles[key] || '';\n });\n }\n\n private _handleBlur: (event: Event) => void = () => {\n this._applyStyles(this._styles?.default);\n };\n\n private _handleFocus: (event: Event) => void = () => {\n this._applyStyles(this._styles?.focus);\n };\n}\n","import { BraintreeFormFieldsMap, BraintreeStoredCardFieldsMap } from './braintree-payment-options';\n\nexport function isBraintreeFormFieldsMap(\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap,\n): fields is BraintreeFormFieldsMap {\n return !!(fields as BraintreeFormFieldsMap).cardNumber;\n}\n\nexport function isBraintreeStoredCardFieldsMap(\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap,\n): fields is BraintreeStoredCardFieldsMap {\n return !!(\n (fields as BraintreeStoredCardFieldsMap).cardCodeVerification ||\n (fields as BraintreeStoredCardFieldsMap).cardNumberVerification\n );\n}\n","import { Dictionary, isEmpty, isNil, omitBy } from 'lodash';\n\nimport { Address } from '../../../address';\nimport { NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { PaymentInvalidFormError, PaymentInvalidFormErrorDetails } from '../../errors';\nimport { NonceInstrument } from '../../payment';\n\nimport {\n BraintreeBillingAddressRequestData,\n BraintreeFormErrorDataKeys,\n BraintreeFormErrorsData,\n BraintreeHostedFields,\n BraintreeHostedFieldsCreatorConfig,\n BraintreeHostedFieldsState,\n BraintreeHostedFormError,\n} from './braintree';\nimport {\n BraintreeFormFieldsMap,\n BraintreeFormFieldStyles,\n BraintreeFormFieldStylesMap,\n BraintreeFormFieldType,\n BraintreeFormFieldValidateErrorData,\n BraintreeFormFieldValidateEventData,\n BraintreeFormOptions,\n BraintreeStoredCardFieldsMap,\n} from './braintree-payment-options';\nimport BraintreeRegularField from './braintree-regular-field';\nimport BraintreeSDKCreator from './braintree-sdk-creator';\nimport { isBraintreeFormFieldsMap } from './is-braintree-form-fields-map';\n\nenum BraintreeHostedFormType {\n CreditCard,\n StoredCardVerification,\n}\n\nexport default class BraintreeHostedForm {\n private _cardFields?: BraintreeHostedFields;\n private _cardNameField?: BraintreeRegularField;\n private _formOptions?: BraintreeFormOptions;\n private _type?: BraintreeHostedFormType;\n private _isInitializedHostedForm = false;\n\n constructor(private _braintreeSDKCreator: BraintreeSDKCreator) {}\n\n async initialize(options: BraintreeFormOptions): Promise {\n this._formOptions = options;\n\n this._type = isBraintreeFormFieldsMap(options.fields)\n ? BraintreeHostedFormType.CreditCard\n : BraintreeHostedFormType.StoredCardVerification;\n\n const fields = this._mapFieldOptions(options.fields);\n\n if (isEmpty(fields)) {\n this._isInitializedHostedForm = false;\n\n return;\n }\n\n this._cardFields = await this._braintreeSDKCreator.createHostedFields({\n fields,\n styles: options.styles && this._mapStyleOptions(options.styles),\n });\n\n this._cardFields.on('blur', this._handleBlur);\n this._cardFields.on('focus', this._handleFocus);\n this._cardFields.on('cardTypeChange', this._handleCardTypeChange);\n this._cardFields.on('validityChange', this._handleValidityChange);\n this._cardFields.on('inputSubmitRequest', this._handleInputSubmitRequest);\n\n if (isBraintreeFormFieldsMap(options.fields)) {\n this._cardNameField = new BraintreeRegularField(\n options.fields.cardName,\n options.styles,\n );\n this._cardNameField.on('blur', this._handleNameBlur);\n this._cardNameField.on('focus', this._handleNameFocus);\n this._cardNameField.attach();\n }\n\n this._isInitializedHostedForm = true;\n }\n\n isInitialized(): boolean {\n return !!this._isInitializedHostedForm;\n }\n\n async deinitialize(): Promise {\n this._isInitializedHostedForm = false;\n\n await this._cardFields?.teardown();\n this._cardNameField?.detach();\n }\n\n async tokenize(billingAddress: Address): Promise {\n if (!this._cardFields) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n try {\n const { nonce } = await this._cardFields.tokenize(\n omitBy(\n {\n billingAddress: billingAddress && this._mapBillingAddress(billingAddress),\n cardholderName: this._cardNameField?.getValue(),\n },\n isNil,\n ),\n );\n\n this._formOptions?.onValidate?.({\n isValid: true,\n errors: {},\n });\n\n return { nonce };\n } catch (error) {\n const errors = this._mapTokenizeError(error);\n\n if (errors) {\n this._formOptions?.onValidate?.({\n isValid: false,\n errors,\n });\n\n throw new PaymentInvalidFormError(errors as PaymentInvalidFormErrorDetails);\n }\n\n throw error;\n }\n }\n\n async tokenizeForStoredCardVerification(): Promise {\n if (!this._cardFields) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n try {\n const { nonce } = await this._cardFields.tokenize(\n omitBy(\n {\n cardholderName: this._cardNameField?.getValue(),\n },\n isNil,\n ),\n );\n\n this._formOptions?.onValidate?.({\n isValid: true,\n errors: {},\n });\n\n return { nonce };\n } catch (error) {\n const errors = this._mapTokenizeError(error, true);\n\n if (errors) {\n this._formOptions?.onValidate?.({\n isValid: false,\n errors,\n });\n\n throw new PaymentInvalidFormError(errors as PaymentInvalidFormErrorDetails);\n }\n\n throw error;\n }\n }\n\n private _mapBillingAddress(billingAddress: Address): BraintreeBillingAddressRequestData {\n return {\n countryName: billingAddress.country,\n postalCode: billingAddress.postalCode,\n streetAddress: billingAddress.address2\n ? `${billingAddress.address1} ${billingAddress.address2}`\n : billingAddress.address1,\n };\n }\n\n private _mapFieldOptions(\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap,\n ): BraintreeHostedFieldsCreatorConfig['fields'] {\n if (isBraintreeFormFieldsMap(fields)) {\n return omitBy(\n {\n number: {\n container: `#${fields.cardNumber.containerId}`,\n placeholder: fields.cardNumber.placeholder,\n internalLabel: fields.cardNumber.accessibilityLabel,\n },\n expirationDate: {\n container: `#${fields.cardExpiry.containerId}`,\n placeholder: fields.cardExpiry.placeholder,\n internalLabel: fields.cardExpiry.accessibilityLabel,\n },\n cvv: fields.cardCode && {\n container: `#${fields.cardCode.containerId}`,\n placeholder: fields.cardCode.placeholder,\n internalLabel: fields.cardCode.accessibilityLabel,\n },\n },\n isNil,\n );\n }\n\n return omitBy(\n {\n number: fields.cardNumberVerification && {\n container: `#${fields.cardNumberVerification.containerId}`,\n placeholder: fields.cardNumberVerification.placeholder,\n },\n cvv: fields.cardCodeVerification && {\n container: `#${fields.cardCodeVerification.containerId}`,\n placeholder: fields.cardCodeVerification.placeholder,\n },\n },\n isNil,\n );\n }\n\n private _mapStyleOptions(\n options: BraintreeFormFieldStylesMap,\n ): BraintreeHostedFieldsCreatorConfig['styles'] {\n const mapStyles = (styles: BraintreeFormFieldStyles = {}) =>\n omitBy(\n {\n color: styles.color,\n 'font-family': styles.fontFamily,\n 'font-size': styles.fontSize,\n 'font-weight': styles.fontWeight,\n },\n isNil,\n ) as Dictionary;\n\n return {\n input: mapStyles(options.default),\n '.invalid': mapStyles(options.error),\n ':focus': mapStyles(options.focus),\n };\n }\n\n private _mapFieldType(type: string): BraintreeFormFieldType {\n switch (type) {\n case 'number':\n return this._type === BraintreeHostedFormType.StoredCardVerification\n ? BraintreeFormFieldType.CardNumberVerification\n : BraintreeFormFieldType.CardNumber;\n\n case 'expirationDate':\n return BraintreeFormFieldType.CardExpiry;\n\n case 'cvv':\n return this._type === BraintreeHostedFormType.StoredCardVerification\n ? BraintreeFormFieldType.CardCodeVerification\n : BraintreeFormFieldType.CardCode;\n\n default:\n throw new Error('Unexpected field type');\n }\n }\n\n private _mapErrors(fields: BraintreeHostedFieldsState['fields']): BraintreeFormErrorsData {\n const errors: BraintreeFormErrorsData = {};\n\n if (fields) {\n for (const [key, value] of Object.entries(fields)) {\n if (value && this._isValidParam(key)) {\n const { isValid, isEmpty, isPotentiallyValid } = value;\n\n errors[key] = {\n isValid,\n isEmpty,\n isPotentiallyValid,\n };\n }\n }\n }\n\n return errors;\n }\n\n private _mapValidationErrors(\n fields: BraintreeHostedFieldsState['fields'],\n ): BraintreeFormFieldValidateEventData['errors'] {\n return (Object.keys(fields) as Array).reduce(\n (result, fieldKey) => ({\n ...result,\n [this._mapFieldType(fieldKey)]: fields[fieldKey]?.isValid\n ? undefined\n : [this._createInvalidError(this._mapFieldType(fieldKey))],\n }),\n {},\n );\n }\n\n private _mapTokenizeError(\n error: BraintreeHostedFormError,\n isStoredCard = false,\n ): BraintreeFormFieldValidateEventData['errors'] | undefined {\n if (error.code === 'HOSTED_FIELDS_FIELDS_EMPTY') {\n const cvvValidation = {\n [this._mapFieldType('cvv')]: [this._createRequiredError(this._mapFieldType('cvv'))],\n };\n\n const expirationDateValidation = {\n [this._mapFieldType('expirationDate')]: [\n this._createRequiredError(this._mapFieldType('expirationDate')),\n ],\n };\n\n const cardNumberValidation = {\n [this._mapFieldType('number')]: [\n this._createRequiredError(this._mapFieldType('number')),\n ],\n };\n\n return isStoredCard\n ? cvvValidation\n : {\n ...cvvValidation,\n ...expirationDateValidation,\n ...cardNumberValidation,\n };\n }\n\n return error.details?.invalidFieldKeys?.reduce(\n (result, fieldKey) => ({\n ...result,\n [this._mapFieldType(fieldKey)]: [\n this._createInvalidError(this._mapFieldType(fieldKey)),\n ],\n }),\n {},\n );\n }\n\n private _createRequiredError(\n fieldType: BraintreeFormFieldType,\n ): BraintreeFormFieldValidateErrorData {\n switch (fieldType) {\n case BraintreeFormFieldType.CardCodeVerification:\n case BraintreeFormFieldType.CardCode:\n return {\n fieldType,\n message: 'CVV is required',\n type: 'required',\n };\n\n case BraintreeFormFieldType.CardNumberVerification:\n case BraintreeFormFieldType.CardNumber:\n return {\n fieldType,\n message: 'Credit card number is required',\n type: 'required',\n };\n\n case BraintreeFormFieldType.CardExpiry:\n return {\n fieldType,\n message: 'Expiration date is required',\n type: 'required',\n };\n\n case BraintreeFormFieldType.CardName:\n return {\n fieldType,\n message: 'Full name is required',\n type: 'required',\n };\n\n default:\n return {\n fieldType,\n message: 'Field is required',\n type: 'required',\n };\n }\n }\n\n private _createInvalidError(\n fieldType: BraintreeFormFieldType,\n ): BraintreeFormFieldValidateErrorData {\n switch (fieldType) {\n case BraintreeFormFieldType.CardCodeVerification:\n return {\n fieldType,\n message: 'Invalid card code',\n type: 'invalid_card_code',\n };\n\n case BraintreeFormFieldType.CardNumberVerification:\n return {\n fieldType,\n message: 'Invalid card number',\n type: 'invalid_card_number',\n };\n\n case BraintreeFormFieldType.CardCode:\n return {\n fieldType,\n message: 'Invalid card code',\n type: 'invalid_card_code',\n };\n\n case BraintreeFormFieldType.CardExpiry:\n return {\n fieldType,\n message: 'Invalid card expiry',\n type: 'invalid_card_expiry',\n };\n\n case BraintreeFormFieldType.CardNumber:\n return {\n fieldType,\n message: 'Invalid card number',\n type: 'invalid_card_number',\n };\n\n default:\n return {\n fieldType,\n message: 'Invalid field',\n type: 'invalid',\n };\n }\n }\n\n private _handleBlur: (event: BraintreeHostedFieldsState) => void = (event) => {\n this._formOptions?.onBlur?.({\n fieldType: this._mapFieldType(event.emittedBy),\n errors: this._mapErrors(event.fields),\n });\n };\n\n private _handleNameBlur: () => void = () => {\n this._formOptions?.onBlur?.({\n fieldType: BraintreeFormFieldType.CardName,\n });\n };\n\n private _handleFocus: (event: BraintreeHostedFieldsState) => void = (event) => {\n this._formOptions?.onFocus?.({\n fieldType: this._mapFieldType(event.emittedBy),\n });\n };\n\n private _handleNameFocus: () => void = () => {\n this._formOptions?.onFocus?.({\n fieldType: BraintreeFormFieldType.CardName,\n });\n };\n\n private _handleCardTypeChange: (event: BraintreeHostedFieldsState) => void = (event) => {\n this._formOptions?.onCardTypeChange?.({\n cardType:\n event.cards.length === 1\n ? event.cards[0].type.replace(/^master\\-card$/, 'mastercard',) /* eslint-disable-line */\n : undefined,\n });\n };\n\n private _handleInputSubmitRequest: (event: BraintreeHostedFieldsState) => void = (event) => {\n this._formOptions?.onEnter?.({\n fieldType: this._mapFieldType(event.emittedBy),\n });\n };\n\n private _handleValidityChange: (event: BraintreeHostedFieldsState) => void = (event) => {\n this._formOptions?.onValidate?.({\n isValid: (\n Object.keys(event.fields) as Array\n ).every((key) => event.fields[key]?.isValid),\n errors: this._mapValidationErrors(event.fields),\n });\n };\n\n private _isValidParam(\n formErrorDataKey: string,\n ): formErrorDataKey is BraintreeFormErrorDataKeys {\n switch (formErrorDataKey) {\n case 'number':\n case 'cvv':\n case 'expirationDate':\n case 'postalCode':\n case 'cardholderName':\n case 'cardType':\n return true;\n\n default:\n return false;\n }\n }\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@braintree/browser-detection\");","import { supportsPopups } from '@braintree/browser-detection';\nimport { isEmpty } from 'lodash';\n\nimport { CancellablePromise } from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { Overlay } from '@bigcommerce/checkout-sdk/ui';\n\nimport { Address } from '../../../address';\nimport { NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { OrderPaymentRequestBody } from '../../../order';\nimport {\n PaymentArgumentInvalidError,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n PaymentMethodCancelledError,\n} from '../../errors';\nimport { CreditCardInstrument, NonceInstrument } from '../../payment';\n\nimport {\n BraintreePaypal,\n BraintreeRequestData,\n BraintreeShippingAddressOverride,\n BraintreeThreeDSecure,\n BraintreeTokenizePayload,\n BraintreeVenmoCheckout,\n BraintreeVerifyPayload,\n} from './braintree';\nimport BraintreeHostedForm from './braintree-hosted-form';\nimport {\n BraintreeFormOptions,\n BraintreePaymentInitializeOptions,\n BraintreeThreeDSecureOptions,\n} from './braintree-payment-options';\nimport BraintreeSDKCreator from './braintree-sdk-creator';\nimport isCreditCardInstrumentLike from './is-credit-card-instrument-like';\n\nexport interface PaypalConfig {\n amount: number;\n currency: string;\n locale: string;\n offerCredit?: boolean;\n shippingAddressEditable?: boolean;\n shippingAddressOverride?: BraintreeShippingAddressOverride;\n shouldSaveInstrument?: boolean;\n}\n\nexport default class BraintreePaymentProcessor {\n private _threeDSecureOptions?: BraintreeThreeDSecureOptions;\n\n constructor(\n private _braintreeSDKCreator: BraintreeSDKCreator,\n private _braintreeHostedForm: BraintreeHostedForm,\n private _overlay: Overlay,\n ) {}\n\n initialize(clientToken: string, options?: BraintreePaymentInitializeOptions): void {\n this._braintreeSDKCreator.initialize(clientToken);\n this._threeDSecureOptions = options?.threeDSecure;\n }\n\n deinitialize(): Promise {\n return this._braintreeSDKCreator.teardown();\n }\n\n preloadPaypal(): Promise {\n return this._braintreeSDKCreator.getPaypal();\n }\n\n async tokenizeCard(\n payment: OrderPaymentRequestBody,\n billingAddress: Address,\n ): Promise {\n const { paymentData } = payment;\n\n if (!isCreditCardInstrumentLike(paymentData)) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const errors = this._getErrorsRequiredFields(paymentData);\n\n if (!isEmpty(errors)) {\n throw new PaymentInvalidFormError(errors);\n }\n\n const requestData = this._mapToCreditCard(paymentData, billingAddress);\n const client = await this._braintreeSDKCreator.getClient();\n const { creditCards } = await client.request(requestData);\n\n return { nonce: creditCards[0].nonce };\n }\n\n async verifyCard(\n payment: OrderPaymentRequestBody,\n billingAddress: Address,\n amount: number,\n ): Promise {\n const { nonce } = await this.tokenizeCard(payment, billingAddress);\n\n return this.challenge3DSVerification(nonce, amount);\n }\n\n paypal({ shouldSaveInstrument, ...config }: PaypalConfig): Promise {\n const newWindowFlow = supportsPopups();\n\n return this._braintreeSDKCreator\n .getPaypal()\n .then((paypal) => {\n if (newWindowFlow) {\n this._overlay.show({\n onClick: () => paypal.focusWindow(),\n });\n }\n\n return paypal.tokenize({\n enableShippingAddress: true,\n flow: shouldSaveInstrument ? 'vault' : 'checkout',\n useraction: 'commit',\n ...config,\n });\n })\n .then((response) => {\n this._overlay.remove();\n\n return response;\n })\n .catch((error) => {\n this._overlay.remove();\n\n throw error;\n });\n }\n\n getSessionId(): Promise {\n return this._braintreeSDKCreator.getDataCollector().then(({ deviceData }) => deviceData);\n }\n\n /**\n * @deprecated Use getSessionId() and combine them in the consumer.\n */\n appendSessionId(processedPayment: Promise): Promise {\n return processedPayment\n .then((paymentData) =>\n Promise.all([paymentData, this._braintreeSDKCreator.getDataCollector()]),\n )\n .then(([paymentData, { deviceData }]) => ({\n ...paymentData,\n deviceSessionId: deviceData,\n }));\n }\n\n async initializeHostedForm(options: BraintreeFormOptions): Promise {\n return this._braintreeHostedForm.initialize(options);\n }\n\n isInitializedHostedForm(): boolean {\n return this._braintreeHostedForm.isInitialized();\n }\n\n async deinitializeHostedForm(): Promise {\n await this._braintreeHostedForm.deinitialize();\n }\n\n tokenizeHostedForm(billingAddress: Address): Promise {\n return this._braintreeHostedForm.tokenize(billingAddress);\n }\n\n tokenizeHostedFormForStoredCardVerification(): Promise {\n return this._braintreeHostedForm.tokenizeForStoredCardVerification();\n }\n\n async verifyCardWithHostedForm(\n billingAddress: Address,\n amount: number,\n ): Promise {\n const { nonce } = await this._braintreeHostedForm.tokenize(billingAddress);\n\n return this.challenge3DSVerification(nonce, amount);\n }\n\n async challenge3DSVerification(nonce: string, amount: number): Promise {\n const threeDSecure = await this._braintreeSDKCreator.get3DS();\n\n return this._present3DSChallenge(threeDSecure, amount, nonce);\n }\n\n async getVenmoCheckout(): Promise {\n return new Promise((resolve, reject) => {\n this._braintreeSDKCreator.getVenmoCheckout(resolve, reject);\n });\n }\n\n private _getErrorsRequiredFields(\n paymentData: CreditCardInstrument,\n ): PaymentInvalidFormErrorDetails {\n const { ccNumber, ccExpiry } = paymentData;\n const errors: PaymentInvalidFormErrorDetails = {};\n\n if (!ccNumber) {\n errors.ccNumber = [\n {\n message: 'Credit card number is required',\n type: 'required',\n },\n ];\n }\n\n if (!ccExpiry) {\n errors.ccExpiry = [\n {\n message: 'Expiration date is required',\n type: 'required',\n },\n ];\n }\n\n return errors;\n }\n\n private _present3DSChallenge(\n threeDSecure: BraintreeThreeDSecure,\n amount: number,\n nonce: string,\n ): Promise {\n if (!this._threeDSecureOptions || !nonce) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { addFrame, removeFrame } = this._threeDSecureOptions;\n const cancelVerifyCard = async () => {\n const response = await threeDSecure.cancelVerifyCard();\n\n verification.cancel(new PaymentMethodCancelledError());\n\n return response;\n };\n\n const roundedAmount = amount.toFixed(2);\n\n const verification = new CancellablePromise(\n threeDSecure.verifyCard({\n addFrame: (error, iframe) => {\n addFrame(error, iframe, cancelVerifyCard);\n },\n amount: Number(roundedAmount),\n challengeRequested: true,\n nonce,\n removeFrame,\n onLookupComplete: (_data, next) => {\n next();\n },\n }),\n );\n\n return verification.promise;\n }\n\n private _mapToCreditCard(\n creditCard: CreditCardInstrument,\n billingAddress?: Address,\n ): BraintreeRequestData {\n return {\n data: {\n creditCard: {\n cardholderName: creditCard.ccName,\n number: creditCard.ccNumber,\n cvv: creditCard.ccCvv,\n expirationDate: `${creditCard.ccExpiry.month}/${creditCard.ccExpiry.year}`,\n options: {\n validate: false,\n },\n billingAddress: billingAddress && {\n countryCodeAlpha2: billingAddress.countryCode,\n locality: billingAddress.city,\n countryName: billingAddress.country,\n postalCode: billingAddress.postalCode,\n streetAddress: billingAddress.address2\n ? `${billingAddress.address1} ${billingAddress.address2}`\n : billingAddress.address1,\n },\n },\n },\n endpoint: 'payment_methods/credit_cards',\n method: 'post',\n };\n }\n}\n","import { CreditCardInstrument } from '../../payment';\n\nexport default function isCreditCardInstrumentLike(\n instrument: any,\n): instrument is CreditCardInstrument {\n return (\n instrument &&\n typeof instrument.ccExpiry === 'object' &&\n typeof instrument.ccNumber === 'string' &&\n typeof instrument.ccName === 'string'\n );\n}\n","import { HostedInstrument } from './payment';\n\nexport default function isHostedInstrumentLike(\n instrument: unknown,\n): instrument is HostedInstrument {\n return (\n typeof instrument === 'object' &&\n instrument !== null &&\n (typeof (instrument as HostedInstrument).shouldSaveInstrument === 'undefined' ||\n typeof (instrument as HostedInstrument).shouldSaveInstrument === 'boolean') &&\n (typeof (instrument as HostedInstrument).shouldSetAsDefaultInstrument === 'undefined' ||\n typeof (instrument as HostedInstrument).shouldSetAsDefaultInstrument === 'boolean')\n );\n}\n","import { some } from 'lodash';\n\nimport { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Address } from '../../../address';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { MissingDataError, MissingDataErrorType, RequestError } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport { isHostedInstrumentLike, PaymentMethod } from '../../index';\nimport isVaultedInstrument from '../../is-vaulted-instrument';\nimport {\n CreditCardInstrument,\n NonceInstrument,\n PaymentInstrument,\n PaymentInstrumentMeta,\n} from '../../payment';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport BraintreePaymentProcessor from './braintree-payment-processor';\n\nexport default class BraintreeCreditCardPaymentStrategy implements PaymentStrategy {\n private _is3dsEnabled?: boolean;\n private _isHostedFormInitialized?: boolean;\n private _deviceSessionId?: string;\n private _paymentMethod?: PaymentMethod;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _braintreePaymentProcessor: BraintreePaymentProcessor,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(options.methodId),\n );\n\n this._paymentMethod = state.paymentMethods.getPaymentMethod(options.methodId);\n\n if (!this._paymentMethod?.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n try {\n this._braintreePaymentProcessor.initialize(\n this._paymentMethod.clientToken,\n options.braintree,\n );\n\n if (\n this._isHostedPaymentFormEnabled(options.methodId, options.gatewayId) &&\n options.braintree?.form\n ) {\n await this._braintreePaymentProcessor.initializeHostedForm(options.braintree.form);\n this._isHostedFormInitialized =\n this._braintreePaymentProcessor.isInitializedHostedForm();\n }\n\n this._is3dsEnabled = this._paymentMethod.config.is3dsEnabled;\n this._deviceSessionId = await this._braintreePaymentProcessor.getSessionId();\n } catch (error) {\n this._handleError(error);\n }\n\n return this._store.getState();\n }\n\n async execute(\n orderRequest: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const state = await this._store.dispatch(\n this._orderActionCreator.submitOrder(order, options),\n );\n\n const {\n billingAddress: { getBillingAddressOrThrow },\n order: { getOrderOrThrow },\n payment: { isPaymentDataRequired },\n } = state;\n\n if (!isPaymentDataRequired(order.useStoreCredit)) {\n return state;\n }\n\n const billingAddress = getBillingAddressOrThrow();\n const orderAmount = getOrderOrThrow().orderAmount;\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n ...payment,\n paymentData: this._isHostedFormInitialized\n ? await this._prepareHostedPaymentData(payment, billingAddress, orderAmount)\n : await this._preparePaymentData(payment, billingAddress, orderAmount),\n }),\n );\n } catch (error) {\n return this._processAdditionalAction(error, payment, orderAmount);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n this._isHostedFormInitialized = false;\n\n await Promise.all([\n this._braintreePaymentProcessor.deinitialize(),\n this._braintreePaymentProcessor.deinitializeHostedForm(),\n ]);\n\n return this._store.getState();\n }\n\n private _handleError(error: Error): never {\n if (error.name === 'BraintreeError') {\n throw new PaymentMethodFailedError(error.message);\n }\n\n throw error;\n }\n\n private async _preparePaymentData(\n payment: OrderPaymentRequestBody,\n billingAddress: Address,\n orderAmount: number,\n ): Promise {\n const { paymentData } = payment;\n const commonPaymentData = { deviceSessionId: this._deviceSessionId };\n\n if (this._isSubmittingWithStoredCard(payment) || this._isStoringNewCard(payment)) {\n return {\n ...commonPaymentData,\n ...paymentData,\n };\n }\n\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n\n const { nonce } = this._shouldPerform3DSVerification(payment)\n ? await this._braintreePaymentProcessor.verifyCard(payment, billingAddress, orderAmount)\n : await this._braintreePaymentProcessor.tokenizeCard(payment, billingAddress);\n\n return {\n ...commonPaymentData,\n nonce,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n };\n }\n\n private async _prepareHostedPaymentData(\n payment: OrderPaymentRequestBody,\n billingAddress: Address,\n orderAmount: number,\n ): Promise {\n const { paymentData } = payment;\n const commonPaymentData = { deviceSessionId: this._deviceSessionId };\n\n if (this._isSubmittingWithStoredCard(payment)) {\n const { nonce } =\n await this._braintreePaymentProcessor.tokenizeHostedFormForStoredCardVerification();\n\n return {\n ...commonPaymentData,\n ...paymentData,\n nonce,\n };\n }\n\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n\n const { nonce } = this._shouldPerform3DSVerification(payment)\n ? await this._braintreePaymentProcessor.verifyCardWithHostedForm(\n billingAddress,\n orderAmount,\n )\n : await this._braintreePaymentProcessor.tokenizeHostedForm(billingAddress);\n\n return {\n ...commonPaymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n nonce,\n };\n }\n\n private async _processAdditionalAction(\n error: Error,\n payment: OrderPaymentRequestBody,\n orderAmount: number,\n ): Promise {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return this._handleError(error);\n }\n\n try {\n const { payer_auth_request: storedCreditCardNonce } = error.body.three_ds_result || {};\n const { nonce } = await this._braintreePaymentProcessor.challenge3DSVerification(\n storedCreditCardNonce,\n orderAmount,\n );\n\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n ...payment,\n paymentData: {\n deviceSessionId: this._deviceSessionId,\n nonce,\n },\n }),\n );\n } catch (error) {\n return this._handleError(error);\n }\n }\n\n private _isHostedPaymentFormEnabled(methodId?: string, gatewayId?: string): boolean {\n if (!methodId) {\n return false;\n }\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(methodId, gatewayId);\n\n return paymentMethod.config.isHostedFormEnabled === true;\n }\n\n private _isSubmittingWithStoredCard(payment: OrderPaymentRequestBody): boolean {\n return !!(payment.paymentData && isVaultedInstrument(payment.paymentData));\n }\n\n private _isStoringNewCard(payment: OrderPaymentRequestBody): boolean {\n return !!(\n payment.paymentData &&\n (payment.paymentData as CreditCardInstrument | NonceInstrument).shouldSaveInstrument\n );\n }\n\n private _shouldPerform3DSVerification(payment: OrderPaymentRequestBody): boolean {\n return !!(this._is3dsEnabled && !this._isSubmittingWithStoredCard(payment));\n }\n}\n","import { BraintreeError } from './braintree';\n\nexport default function isBraintreeError(error: BraintreeError | Error): error is BraintreeError {\n return error.name === 'BraintreeError';\n}\n","import { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError, PaymentMethodCancelledError } from '../../errors';\nimport { isHostedInstrumentLike } from '../../index';\nimport isVaultedInstrument, { isHostedVaultedInstrument } from '../../is-vaulted-instrument';\nimport Payment, { FormattedPayload, PaypalInstrument } from '../../payment';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { BraintreePaymentInitializeOptions } from '../../strategies/braintree';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { BraintreeError } from './braintree';\nimport BraintreePaymentProcessor from './braintree-payment-processor';\nimport isBraintreeError from './is-braintree-error';\nimport mapToBraintreeShippingAddressOverride from './map-to-braintree-shipping-address-override';\n\nexport default class BraintreePaypalPaymentStrategy implements PaymentStrategy {\n private _paymentMethod?: PaymentMethod;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _braintreePaymentProcessor: BraintreePaymentProcessor,\n private _credit: boolean = false,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const { braintree: braintreeOptions, methodId } = options;\n\n if (!this._paymentMethod || !this._paymentMethod.nonce) {\n this._paymentMethod = this._store\n .getState()\n .paymentMethods.getPaymentMethodOrThrow(methodId);\n }\n\n if (this._paymentMethod.clientToken) {\n return this._loadPaypal(braintreeOptions);\n }\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n\n this._paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n if (!this._paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n return this._loadPaypal(braintreeOptions);\n }\n\n execute(\n orderRequest: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n return (\n payment\n ? this._preparePaymentData(payment, order.useStoreCredit)\n : Promise.resolve(payment)\n )\n .then((payment) =>\n Promise.all([\n payment,\n this._store.dispatch(this._orderActionCreator.submitOrder(order, options)),\n ]),\n )\n .then(([payment]) =>\n this._store.dispatch(this._paymentActionCreator.submitPayment(payment)),\n )\n .catch((error: Error) => this._handleError(error));\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return this._braintreePaymentProcessor.deinitialize().then(() => this._store.getState());\n }\n\n private _handleError(error: BraintreeError | Error): never {\n if (!isBraintreeError(error)) {\n throw error;\n }\n\n if (error.code === 'PAYPAL_POPUP_CLOSED') {\n throw new PaymentMethodCancelledError(error.message);\n }\n\n throw new PaymentMethodFailedError(error.message);\n }\n\n private async _preparePaymentData(\n payment: OrderPaymentRequestBody,\n useStoreCredit?: boolean,\n ): Promise {\n const state = this._store.getState();\n\n const grandTotal = state.checkout.getOutstandingBalance(useStoreCredit);\n const config = state.config.getStoreConfig();\n\n if (!grandTotal) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!config) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n if (!this._paymentMethod) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const {\n currency,\n storeProfile: { storeLanguage },\n } = config;\n const {\n nonce,\n config: { isVaultingEnabled },\n } = this._paymentMethod;\n const { methodId, paymentData = {} } = payment;\n\n if (nonce) {\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n\n this._paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n return Promise.resolve({ ...payment, paymentData: this._formattedPayload(nonce) });\n }\n\n if (isVaultedInstrument(paymentData) || isHostedVaultedInstrument(paymentData)) {\n if (!isVaultingEnabled) {\n throw new InvalidArgumentError(\n 'Vaulting is disabled but a vaulted instrument was being used for this transaction',\n );\n }\n\n return Promise.resolve(payment);\n }\n\n if (!isHostedInstrumentLike(paymentData)) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = paymentData;\n\n if (shouldSaveInstrument && !isVaultingEnabled) {\n throw new InvalidArgumentError(\n 'Vaulting is disabled but shouldSaveInstrument is set to true',\n );\n }\n\n const shippingAddress = state.shippingAddress.getShippingAddress();\n\n const shippingAddressOverride = shippingAddress\n ? mapToBraintreeShippingAddressOverride(shippingAddress)\n : undefined;\n\n return Promise.all([\n this._braintreePaymentProcessor.paypal({\n amount: grandTotal,\n locale: storeLanguage,\n currency: currency.code,\n offerCredit: this._credit,\n shippingAddressOverride,\n shouldSaveInstrument: shouldSaveInstrument || false,\n shippingAddressEditable: false,\n }),\n this._braintreePaymentProcessor.getSessionId(),\n ]).then(([{ nonce, details } = {} as any, sessionId]) => ({\n ...payment,\n paymentData: this._formattedPayload(\n nonce,\n details && details.email,\n sessionId,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n ),\n }));\n }\n\n private _formattedPayload(\n token: string,\n email?: string,\n sessionId?: string,\n vaultPaymentInstrument?: boolean,\n shouldSetAsDefaultInstrument?: boolean,\n ): FormattedPayload {\n return {\n formattedPayload: {\n vault_payment_instrument: vaultPaymentInstrument || null,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n device_info: sessionId || null,\n paypal_account: {\n token,\n email: email || null,\n },\n },\n };\n }\n\n private _loadPaypal(\n braintreeOptions?: BraintreePaymentInitializeOptions,\n ): Promise {\n if (!this._paymentMethod || !this._paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n try {\n this._braintreePaymentProcessor.initialize(\n this._paymentMethod.clientToken,\n braintreeOptions,\n );\n\n this._braintreePaymentProcessor.preloadPaypal();\n } catch (error) {\n this._handleError(error);\n }\n\n return Promise.resolve(this._store.getState());\n }\n}\n","import { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError, PaymentMethodCancelledError } from '../../errors';\nimport Payment, { FormattedPayload, PaypalInstrument } from '../../payment';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { BraintreeError, BraintreeTokenizePayload, BraintreeVenmoCheckout } from './braintree';\nimport BraintreePaymentProcessor from './braintree-payment-processor';\nimport isBraintreeError from './is-braintree-error';\n\nexport default class BraintreeVenmoPaymentStrategy implements PaymentStrategy {\n private _braintreeVenmoCheckout?: BraintreeVenmoCheckout;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _braintreePaymentProcessor: BraintreePaymentProcessor,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const { methodId } = options;\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n\n const { clientToken } = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n await this._initializeBraintreeVenmo(clientToken);\n\n return this._store.getState();\n }\n\n async execute(\n orderRequest: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n try {\n const paymentData = await this._preparePaymentData(payment);\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentData),\n );\n } catch (error) {\n this._handleError(error);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n await this._braintreePaymentProcessor.deinitialize();\n\n return this._store.getState();\n }\n\n private _handleError(error: BraintreeError | Error): never {\n if (!isBraintreeError(error)) {\n throw error;\n }\n\n if (error.code === 'PAYPAL_POPUP_CLOSED') {\n throw new PaymentMethodCancelledError(error.message);\n }\n\n throw new PaymentMethodFailedError(error.message);\n }\n\n private async _initializeBraintreeVenmo(clientToken?: string): Promise {\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n try {\n this._braintreePaymentProcessor.initialize(clientToken);\n this._braintreeVenmoCheckout = await this._braintreePaymentProcessor.getVenmoCheckout();\n } catch (error) {\n this._handleError(error);\n }\n }\n\n private async _preparePaymentData(payment: OrderPaymentRequestBody): Promise {\n const { nonce } = this._store\n .getState()\n .paymentMethods.getPaymentMethodOrThrow(payment.methodId);\n\n if (nonce) {\n return { ...payment, paymentData: this._formattedPayload(nonce) };\n }\n\n const tokenizeResult = await this._braintreeVenmoTokenize();\n const sessionId = await this._braintreePaymentProcessor.getSessionId();\n\n return {\n ...payment,\n paymentData: this._formattedPayload(\n tokenizeResult.nonce,\n tokenizeResult.details.email,\n sessionId,\n ),\n };\n }\n\n private _formattedPayload(\n token: string,\n email?: string,\n sessionId?: string,\n ): FormattedPayload {\n return {\n formattedPayload: {\n vault_payment_instrument: null,\n set_as_default_stored_instrument: null,\n device_info: sessionId || null,\n paypal_account: {\n token,\n email: email || null,\n },\n },\n };\n }\n\n private _braintreeVenmoTokenize(): Promise {\n return new Promise((resolve, reject) => {\n this._braintreeVenmoCheckout?.tokenize(\n (error: BraintreeError, payload: BraintreeTokenizePayload) => {\n if (error) {\n return reject(error);\n }\n\n resolve(payload);\n },\n );\n });\n }\n}\n","import { noop } from 'lodash';\n\nimport { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategyActionCreator from '../../payment-strategy-action-creator';\nimport PaymentStrategy from '../payment-strategy';\n\nimport BraintreeVisaCheckoutPaymentProcessor from './braintree-visacheckout-payment-processor';\nimport { VisaCheckoutPaymentSuccessPayload } from './visacheckout';\nimport VisaCheckoutScriptLoader from './visacheckout-script-loader';\n\nexport default class BraintreeVisaCheckoutPaymentStrategy implements PaymentStrategy {\n private _paymentMethod?: PaymentMethod;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentStrategyActionCreator: PaymentStrategyActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _orderActionCreator: OrderActionCreator,\n private _braintreeVisaCheckoutPaymentProcessor: BraintreeVisaCheckoutPaymentProcessor,\n private _visaCheckoutScriptLoader: VisaCheckoutScriptLoader,\n ) {}\n\n initialize(options: PaymentInitializeOptions): Promise {\n const { braintreevisacheckout: visaCheckoutOptions, methodId } = options;\n\n if (!visaCheckoutOptions) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.braintreevisacheckout\" argument is not provided.',\n );\n }\n\n return this._store\n .dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId))\n .then((state) => {\n this._paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n const checkout = state.checkout.getCheckout();\n const storeConfig = state.config.getStoreConfig();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n if (!this._paymentMethod || !this._paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { onError = noop, onPaymentSelect = noop } = visaCheckoutOptions;\n\n const initOptions = {\n locale: storeConfig.storeProfile.storeLanguage,\n collectShipping: false,\n subtotal: checkout.subtotal,\n currencyCode: storeConfig.currency.code,\n };\n\n return Promise.all([\n this._visaCheckoutScriptLoader.load(this._paymentMethod.config.testMode),\n this._braintreeVisaCheckoutPaymentProcessor.initialize(\n this._paymentMethod.clientToken,\n initOptions,\n ),\n ]).then(([visaCheckout, visaInitOptions]) => {\n visaCheckout.init(visaInitOptions);\n visaCheckout.on(\n 'payment.success',\n (paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) =>\n this._paymentInstrumentSelected(paymentSuccessPayload)\n .then(() => onPaymentSelect())\n .catch((error) => onError(error)),\n );\n visaCheckout.on('payment.error', (_, error) => onError(error));\n });\n })\n .then(() => this._store.getState());\n }\n\n execute(\n orderRequest: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new InvalidArgumentError(\n 'Unable to submit payment because \"payload.payment\" argument is not provided.',\n );\n }\n\n if (\n !this._paymentMethod ||\n !this._paymentMethod.initializationData ||\n !this._paymentMethod.initializationData.nonce\n ) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { nonce } = this._paymentMethod.initializationData;\n\n return this._store\n .dispatch(this._orderActionCreator.submitOrder(order, options))\n .then(() =>\n this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n ...payment,\n paymentData: { nonce },\n }),\n ),\n )\n .catch((error: Error) => this._handleError(error));\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return this._braintreeVisaCheckoutPaymentProcessor\n .deinitialize()\n .then(() => this._store.getState());\n }\n\n private _paymentInstrumentSelected(paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) {\n const state = this._store.getState();\n\n if (!this._paymentMethod) {\n throw new Error('Payment method not initialized');\n }\n\n const { id: methodId } = this._paymentMethod;\n\n return this._store.dispatch(\n this._paymentStrategyActionCreator.widgetInteraction(\n () => {\n return this._braintreeVisaCheckoutPaymentProcessor\n .handleSuccess(\n paymentSuccessPayload,\n state.shippingAddress.getShippingAddress(),\n state.billingAddress.getBillingAddress(),\n )\n .then(() =>\n Promise.all([\n this._store.dispatch(\n this._checkoutActionCreator.loadCurrentCheckout(),\n ),\n this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n ),\n ]),\n );\n },\n { methodId },\n ),\n { queueId: 'widgetInteraction' },\n );\n }\n\n private _handleError(error: Error): never {\n if (error.name === 'BraintreeError') {\n throw new PaymentMethodFailedError(error.message);\n }\n\n throw error;\n }\n}\n","import { merge, some } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { RequestError } from '../../../common/error/errors';\nimport { HostedForm } from '../../../hosted-form';\nimport { OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { InstrumentSelector } from '../../instrument';\nimport isCreditCardLike from '../../is-credit-card-like';\nimport isVaultedInstrument from '../../is-vaulted-instrument';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { CardinalThreeDSecureToken } from './cardinal';\nimport CardinalClient, { CardinalOrderData } from './cardinal-client';\n\nexport default class CardinalThreeDSecureFlowV2 {\n constructor(\n private _store: CheckoutStore,\n private _paymentActionCreator: PaymentActionCreator,\n private _cardinalClient: CardinalClient,\n ) {}\n\n async prepare(method: PaymentMethod): Promise {\n await this._cardinalClient.load(method.id, method.config.testMode);\n }\n\n async start(\n execute: PaymentStrategy['execute'],\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n hostedForm?: HostedForm,\n ): Promise {\n const {\n instruments: { getCardInstrument },\n } = this._store.getState();\n const { payment = { methodId: '' } } = payload;\n const { paymentData = {} } = payment;\n\n try {\n return await execute(payload, options);\n } catch (error) {\n if (\n error instanceof RequestError &&\n error.body.status === 'additional_action_required'\n ) {\n const token = error.body.additional_action_required?.data?.token;\n const xid = error.body.three_ds_result?.payer_auth_request;\n\n await this._cardinalClient.configure(token);\n\n const bin = this._getBin(paymentData, getCardInstrument, hostedForm);\n\n if (bin) {\n await this._cardinalClient.runBinProcess(bin);\n }\n\n try {\n return await this._submitPayment(payment, { xid }, hostedForm);\n } catch (error) {\n if (\n error instanceof RequestError &&\n some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n const threeDsResult = error.body.three_ds_result;\n const token = threeDsResult?.payer_auth_request;\n\n await this._cardinalClient.getThreeDSecureData(\n threeDsResult,\n this._getOrderData(),\n );\n\n return await this._submitPayment(payment, { token }, hostedForm);\n }\n\n throw error;\n }\n }\n\n throw error;\n }\n }\n\n private _getOrderData(): CardinalOrderData {\n const store = this._store.getState();\n const billingAddress = store.billingAddress.getBillingAddressOrThrow();\n const shippingAddress = store.shippingAddress.getShippingAddress();\n const {\n cart: {\n currency: { code: currencyCode },\n cartAmount: amount,\n },\n } = store.checkout.getCheckoutOrThrow();\n const id = store.order.getOrderOrThrow().orderId.toString();\n\n return { billingAddress, shippingAddress, currencyCode, id, amount };\n }\n\n private async _submitPayment(\n payment: OrderPaymentRequestBody,\n threeDSecure: CardinalThreeDSecureToken,\n hostedForm?: HostedForm,\n ): Promise {\n const paymentPayload = merge({}, payment, { paymentData: { threeDSecure } });\n\n if (!hostedForm) {\n return this._store.dispatch(this._paymentActionCreator.submitPayment(paymentPayload));\n }\n\n await hostedForm.submit(paymentPayload);\n\n return this._store.getState();\n }\n\n private _getBin(\n paymentData: NonNullable,\n getCardInstrument: InstrumentSelector['getCardInstrument'],\n hostedForm?: HostedForm,\n ): string {\n const instrument =\n isVaultedInstrument(paymentData) && getCardInstrument(paymentData.instrumentId);\n const ccNumber = isCreditCardLike(paymentData) && paymentData.ccNumber;\n const bin = instrument ? instrument.iin : hostedForm ? hostedForm.getBin() : ccNumber;\n\n return bin || '';\n }\n}\n","import isVaultedInstrument from './is-vaulted-instrument';\nimport { CreditCardInstrument, PaymentInstrument } from './payment';\n\nexport default function isCreditCardLike(\n instrument: PaymentInstrument,\n): instrument is CreditCardInstrument {\n const card = instrument as CreditCardInstrument;\n\n return (\n !isVaultedInstrument(card) &&\n typeof card.ccName === 'string' &&\n typeof card.ccNumber === 'string' &&\n typeof card.ccExpiry === 'object' &&\n typeof card.ccExpiry.month === 'string' &&\n typeof card.ccExpiry.year === 'string'\n );\n}\n","import { ThreeDSecure, ThreeDSecureToken } from '../../payment';\n\nexport const CardinalSignatureValidationErrors = [100004, 1010, 1011, 1020];\n\nexport interface CardinalSDK {\n configure(params: CardinalConfiguration): void;\n on(params: CardinalEventType, callback: CardinalEventMap[CardinalEventType]): void;\n off(params: CardinalEventType): void;\n setup(\n initializationType: K,\n initializationData: CardinalInitializationDataMap[K],\n ): void;\n trigger(\n event: CardinalTriggerEvents,\n data?: string,\n ): Promise;\n continue(\n paymentBrand: CardinalPaymentBrand,\n continueObject: CardinalContinue,\n order: CardinalPartialOrder,\n ): void;\n start(paymentBrand: CardinalPaymentBrand, order: CardinalPartialOrder, jwt?: string): void;\n}\n\nexport interface CardinalWindow extends Window {\n Cardinal?: CardinalSDK;\n}\n\nexport interface CardinalEventMap {\n [CardinalEventType.SetupCompleted](setupCompleteData: CardinalSetupCompletedData): void;\n [CardinalEventType.Validated](data: CardinalValidatedData, jwt?: string): void;\n}\n\nexport type CardinalConfiguration = Partial<{\n logging: {\n level: string;\n };\n payment: {\n view: string;\n framework: string;\n displayLoading: boolean;\n };\n}>;\n\nexport interface CardinalSetupCompletedData {\n sessionId: string;\n modules: CardinalModuleState[];\n}\n\nexport interface CardinalModuleState {\n loaded: boolean;\n module: string;\n}\n\nexport enum CardinalInitializationType {\n Init = 'init',\n Complete = 'complete',\n Confirm = 'confirm',\n}\n\nexport interface CardinalInitializationDataMap {\n [CardinalInitializationType.Init]: CardinalInitTypeData;\n [CardinalInitializationType.Complete]: CardinalCompleteTypeData;\n [CardinalInitializationType.Confirm]: CardinalConfirmTypeData;\n}\n\nexport interface CardinalInitTypeData {\n jwt: string;\n}\n\nexport interface CardinalCompleteTypeData {\n Status: string;\n}\n\nexport interface CardinalConfirmTypeData {\n jwt: string;\n cardinalResponseJwt: string;\n}\n\nexport interface CardinalValidatedData {\n ActionCode?: CardinalValidatedAction;\n ErrorDescription: string;\n ErrorNumber: number;\n Validated?: boolean;\n Payment?: CardinalPayment;\n}\n\nexport interface CardinalPayment {\n ExtendedData?: CardinalCCAExtendedData;\n ProcessorTransactionId: string;\n Type: CardinalPaymentType;\n}\n\nexport interface CardinalBinProcessResponse {\n Status: boolean;\n}\n\nexport interface CardinalContinue {\n AcsUrl: string;\n Payload: string;\n}\n\nexport interface CardinalPartialOrder {\n OrderDetails: CardinalOrderDetails;\n Consumer?: CardinalConsumer;\n}\n\nexport interface CardinalConsumer {\n Email1?: string;\n Email2?: string;\n ShippingAddress?: CardinalAddress;\n BillingAddress?: CardinalAddress;\n Account?: CardinalAccount;\n}\n\nexport interface CardinalAccount {\n AccountNumber: number;\n ExpirationMonth: number;\n ExpirationYear: number;\n NameOnAccount: string;\n CardCode: number;\n}\n\nexport interface CardinalAddress {\n FullName?: string;\n FirstName: string;\n MiddleName?: string;\n LastName: string;\n Address1: string;\n Address2?: string;\n Address3?: string;\n City: string;\n State: string;\n PostalCode: string;\n CountryCode: string;\n Phone1?: string;\n Phone2?: string;\n}\n\nexport interface CardinalOrderDetails {\n OrderNumber: string;\n Amount: number;\n CurrencyCode: string;\n OrderDescription?: string;\n OrderChannel: string;\n TransactionId?: string;\n}\n\nexport type CardinalCCAExtendedData = Partial<{\n CAVV: string;\n ECIFlag: string;\n PAResStatus: string;\n SignatureVerification: string;\n XID: string;\n UCAFIndicator: string;\n ChallengeCancel: string;\n}>;\n\nexport enum CardinalEventType {\n SetupCompleted = 'payments.setupComplete',\n Validated = 'payments.validated',\n}\n\nexport enum CardinalValidatedAction {\n Success = 'SUCCESS',\n NoAction = 'NOACTION',\n Failure = 'FAILURE',\n Error = 'ERROR',\n}\n\nexport enum CardinalPaymentType {\n CCA = 'CCA',\n Paypal = 'Paypal',\n Wallet = 'Wallet',\n VisaCheckout = 'VisaCheckout',\n ApplePay = 'ApplePay',\n DiscoverWallet = 'DiscoverWallet',\n}\n\nexport enum CardinalTriggerEvents {\n BinProcess = 'bin.process',\n}\n\nexport enum CardinalPaymentBrand {\n CCA = 'cca',\n}\n\nexport enum CardinalSignatureVerification {\n Yes = 'Y',\n No = 'N',\n}\n\nexport type CardinalThreeDSecureToken = Pick | ThreeDSecureToken;\n","import { includes } from 'lodash';\n\nimport { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Address } from '../../../address';\nimport { BillingAddress } from '../../../billing';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { CreditCardInstrument, ThreeDSecureToken, VaultedInstrument } from '../../payment';\nimport { ThreeDsResult } from '../../payment-response-body';\n\nimport {\n CardinalAccount,\n CardinalAddress,\n CardinalConsumer,\n CardinalEventType,\n CardinalInitializationType,\n CardinalPartialOrder,\n CardinalPaymentBrand,\n CardinalSDK,\n CardinalSignatureValidationErrors,\n CardinalSignatureVerification,\n CardinalTriggerEvents,\n CardinalValidatedAction,\n CardinalValidatedData,\n} from './cardinal';\nimport CardinalScriptLoader from './cardinal-script-loader';\n\nexport type CardinalSupportedPaymentInstrument = CreditCardInstrument | VaultedInstrument;\n\nexport interface CardinalOrderData {\n billingAddress: BillingAddress;\n shippingAddress?: Address;\n currencyCode: string;\n id: string;\n amount: number;\n paymentData?: CreditCardInstrument;\n}\n\nexport default class CardinalClient {\n private _provider = '';\n private _testMode = false;\n private _sdk?: Promise;\n private _configurationToken = '';\n\n constructor(private _scriptLoader: CardinalScriptLoader) {}\n\n load(provider: string, testMode = false): Promise {\n this._provider = provider;\n this._testMode = testMode;\n\n if (!this._sdk) {\n this._sdk = this._scriptLoader.load(provider, testMode);\n }\n\n return this._sdk.then(() => {});\n }\n\n configure(clientToken: string): Promise {\n if (this._configurationToken) {\n if (this._configurationToken === clientToken) {\n return Promise.resolve();\n }\n\n this._sdk = this._scriptLoader.load(`${this._provider}.${Date.now()}`, this._testMode);\n }\n\n return this._getClientSDK().then(\n (client) =>\n new Promise((resolve, reject) => {\n client.on(CardinalEventType.SetupCompleted, () => {\n client.off(CardinalEventType.SetupCompleted);\n client.off(CardinalEventType.Validated);\n\n this._configurationToken = clientToken;\n\n resolve();\n });\n\n client.on(CardinalEventType.Validated, (data: CardinalValidatedData) => {\n client.off(CardinalEventType.SetupCompleted);\n client.off(CardinalEventType.Validated);\n\n switch (data.ActionCode) {\n case CardinalValidatedAction.Error:\n if (includes(CardinalSignatureValidationErrors, data.ErrorNumber)) {\n reject(\n new MissingDataError(\n MissingDataErrorType.MissingPaymentMethod,\n ),\n );\n }\n\n reject(new PaymentMethodFailedError(data.ErrorDescription));\n break;\n }\n });\n\n client.setup(CardinalInitializationType.Init, {\n jwt: clientToken,\n });\n }),\n );\n }\n\n runBinProcess(binNumber: string): Promise {\n return this._getClientSDK()\n .then((client) =>\n client.trigger(CardinalTriggerEvents.BinProcess, binNumber).catch(() => {}),\n )\n .then((result) => {\n if (!result || !result.Status) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n });\n }\n\n getThreeDSecureData(\n threeDSecureData: ThreeDsResult,\n orderData: CardinalOrderData,\n ): Promise {\n return this._getClientSDK().then((client) => {\n return new Promise((resolve, reject) => {\n client.on(\n CardinalEventType.Validated,\n (data: CardinalValidatedData, jwt?: string) => {\n client.off(CardinalEventType.Validated);\n\n if (!jwt) {\n return reject(\n new PaymentMethodFailedError(\n data.ErrorDescription\n ? data.ErrorDescription\n : 'An error was encountered while processing the transaction.',\n ),\n );\n }\n\n if (!data.ActionCode) {\n return resolve({ token: jwt });\n }\n\n switch (data.ActionCode) {\n case CardinalValidatedAction.Success:\n return resolve({ token: jwt });\n\n case CardinalValidatedAction.NoAction:\n if (data.ErrorNumber > 0) {\n return reject(\n new PaymentMethodFailedError(data.ErrorDescription),\n );\n } else if (\n !data.Payment ||\n !data.Payment.ExtendedData ||\n data.Payment.ExtendedData.SignatureVerification !==\n CardinalSignatureVerification.Yes\n ) {\n return reject(\n new PaymentMethodFailedError(\n 'Transaction signature could not be validated.',\n ),\n );\n }\n\n return resolve({ token: jwt });\n\n case CardinalValidatedAction.Failure:\n return reject(\n new PaymentMethodFailedError(\n 'User failed authentication or an error was encountered while processing the transaction.',\n ),\n );\n\n case CardinalValidatedAction.Error:\n return reject(new PaymentMethodFailedError(data.ErrorDescription));\n }\n },\n );\n\n const continueObject = {\n AcsUrl: threeDSecureData.acs_url,\n Payload: threeDSecureData.merchant_data,\n };\n\n const partialOrder = this._mapToPartialOrder(\n orderData,\n threeDSecureData.payer_auth_request,\n );\n\n client.continue(CardinalPaymentBrand.CCA, continueObject, partialOrder);\n });\n });\n }\n\n private _mapToPartialOrder(\n orderData: CardinalOrderData,\n transactionId: string,\n ): CardinalPartialOrder {\n const consumer: CardinalConsumer = {\n BillingAddress: this._mapToCardinalAddress(orderData.billingAddress),\n };\n\n if (orderData.paymentData) {\n consumer.Account = this._mapToCardinalAccount(orderData.paymentData);\n }\n\n if (orderData.billingAddress.email) {\n consumer.Email1 = orderData.billingAddress.email;\n }\n\n if (orderData.shippingAddress) {\n consumer.ShippingAddress = this._mapToCardinalAddress(orderData.shippingAddress);\n }\n\n return {\n Consumer: consumer,\n OrderDetails: {\n OrderNumber: orderData.id,\n Amount: orderData.amount,\n CurrencyCode: orderData.currencyCode,\n OrderChannel: 'S',\n TransactionId: transactionId,\n },\n };\n }\n\n private _mapToCardinalAccount(paymentData: CreditCardInstrument): CardinalAccount {\n return {\n AccountNumber: Number(paymentData.ccNumber),\n ExpirationMonth: Number(paymentData.ccExpiry.month),\n ExpirationYear: Number(paymentData.ccExpiry.year),\n NameOnAccount: paymentData.ccName,\n CardCode: Number(paymentData.ccCvv),\n };\n }\n\n private _mapToCardinalAddress(address: Address): CardinalAddress {\n const cardinalAddress: CardinalAddress = {\n FirstName: address.firstName,\n LastName: address.lastName,\n Address1: address.address1,\n City: address.city,\n State: address.stateOrProvince,\n PostalCode: address.postalCode,\n CountryCode: address.countryCode,\n };\n\n if (address.address2) {\n cardinalAddress.Address2 = address.address2;\n }\n\n if (address.phone) {\n cardinalAddress.Phone1 = address.phone;\n }\n\n return cardinalAddress;\n }\n\n private _getClientSDK(): Promise {\n if (!this._sdk) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._sdk;\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { CardinalSDK, CardinalWindow } from './cardinal';\n\nconst SDK_TEST_URL = 'https://songbirdstag.cardinalcommerce.com/edge/v1/songbird.js';\nconst SDK_PROD_URL = 'https://songbird.cardinalcommerce.com/edge/v1/songbird.js';\n\nexport default class CardinalScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, private _window: CardinalWindow = window) {}\n\n load(provider: string, testMode?: boolean): Promise {\n const url = testMode ? SDK_TEST_URL : SDK_PROD_URL;\n\n return this._scriptLoader.loadScript(`${url}?v=${provider}`).then(() => {\n if (!this._window.Cardinal) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.Cardinal;\n });\n }\n}\n","import { merge, some } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { RequestError } from '../../../common/error/errors';\nimport { HostedForm } from '../../../hosted-form';\nimport { OrderRequestBody } from '../../../order';\nimport isVaultedInstrument from '../../is-vaulted-instrument';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport CardinalClient, { CardinalOrderData } from './cardinal-client';\n\nexport default class CardinalThreeDSecureFlow {\n constructor(\n private _store: CheckoutStore,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _cardinalClient: CardinalClient,\n ) {}\n\n async prepare(method: PaymentMethod): Promise {\n await this._cardinalClient.load(method.id, method.config.testMode);\n await this._cardinalClient.configure(await this._getClientToken(method));\n }\n\n async start(\n execute: PaymentStrategy['execute'],\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n hostedForm?: HostedForm,\n ): Promise {\n const {\n instruments: { getCardInstrument },\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const { payment: { methodId = '', paymentData = {} } = {} } = payload;\n const instrument =\n isVaultedInstrument(paymentData) && getCardInstrument(paymentData.instrumentId);\n const bin = instrument ? instrument.iin : hostedForm && hostedForm.getBin();\n\n if (bin) {\n await this._cardinalClient.runBinProcess(bin);\n }\n\n try {\n return await execute(\n merge(payload, {\n payment: {\n paymentData: {\n threeDSecure: { token: getPaymentMethodOrThrow(methodId).clientToken },\n },\n },\n }),\n options,\n );\n } catch (error) {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n throw error;\n }\n\n const threeDSecure = await this._cardinalClient.getThreeDSecureData(\n error.body.three_ds_result,\n this._getOrderData(),\n );\n\n if (!hostedForm) {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment(\n merge(payload.payment, {\n paymentData: { threeDSecure },\n }),\n ),\n );\n }\n\n await hostedForm.submit(\n merge(payload.payment, {\n paymentData: { threeDSecure },\n }),\n );\n\n return this._store.getState();\n }\n }\n\n private async _getClientToken(method: PaymentMethod): Promise {\n if (method.clientToken) {\n return method.clientToken;\n }\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(method.id),\n );\n\n return getPaymentMethodOrThrow(method.id).clientToken || '';\n }\n\n private _getOrderData(): CardinalOrderData {\n const state = this._store.getState();\n const billingAddress = state.billingAddress.getBillingAddressOrThrow();\n const shippingAddress = state.shippingAddress.getShippingAddress();\n const checkout = state.checkout.getCheckoutOrThrow();\n const order = state.order.getOrderOrThrow();\n\n return {\n billingAddress,\n shippingAddress,\n currencyCode: checkout.cart.currency.code,\n id: order.orderId.toString(),\n amount: checkout.cart.cartAmount,\n };\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if a payment method explicitly returns a declined error and\n * the shopper has to choose a different payment method if they wish to continue\n * their checkout process.\n */\nexport default class PaymentMethodDeclinedError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'The selected payment method was declined. Please select another payment method.',\n );\n\n this.name = 'PaymentMethodDeclinedError';\n this.type = 'payment_declined';\n }\n}\n","export const THREE_D_SECURE_PROCEED = 'PROCEED';\nexport const THREE_D_SECURE_BUSY = 'SERVER_BUSY';\nexport const THREE_D_SECURE_AVAILABLE = 'AUTHENTICATION_AVAILABLE';\n\nexport interface CBAMPGSHostWindow extends Window {\n ThreeDS?: ThreeDSjs;\n}\n\nexport interface ThreeDSjs {\n // Configuration method for initializing the API.\n configure(config: ThreeDSConfiguration): Promise;\n // Convenience method to check if the API has been configured successfully.\n isConfigured(): boolean;\n // Authentication for the arguments passed.\n initiateAuthentication(\n orderId: string,\n transactionId: string,\n callback: (data: ThreeDSAuthenticationResponse) => void,\n ): void;\n authenticatePayer(\n orderId: string,\n transactionId: string,\n callback: (data: ThreeDSAuthenticationResponse) => void,\n optionalParams?: AuthenticatePayerOptionalParams,\n ): void;\n}\n\nexport interface RestApiResponse {\n transaction: {\n authenticationStatus: string;\n };\n}\n\n// Configuration required to configure ThreeDS\nexport interface ThreeDSConfiguration {\n merchantId: string;\n sessionId: string;\n configuration: ThreeDSAPIConfiguration;\n callback(): void;\n}\n\nexport interface ThreeDSAuthenticationResponse {\n error?: ThreeDSAuthenticationError;\n restApiResponse: RestApiResponse;\n gatewayRecommendation: string;\n}\n\nexport interface AuthenticatePayerOptionalParams {\n fullScreenRedirect: boolean;\n}\n\nexport interface ThreeDSAuthenticationError {\n code: string;\n msg: string;\n cause?: string;\n}\n\n// JSON value supporting data elements like userLanguage, REST API version (wsVersion)\nexport interface ThreeDSAPIConfiguration {\n // A language identifier or IETF language tag to control the language of the payment page displayed to the payer.\n // For example, \"en_US\", es, \"fr-CA\". By default, the language is \"en_US\".\n userLanguage: string;\n // The Web Services API version that you submitted the request in. IE: 62\n wsVersion: number;\n}\n","import { noop, some } from 'lodash';\n\nimport { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError, PaymentMethodDeclinedError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nimport {\n RestApiResponse,\n THREE_D_SECURE_AVAILABLE,\n THREE_D_SECURE_BUSY,\n THREE_D_SECURE_PROCEED,\n ThreeDSjs,\n} from './cba-mpgs';\nimport CBAMPGSScriptLoader from './cba-mpgs-script-loader';\n\nexport default class CBAMPGSPaymentStrategy extends CreditCardPaymentStrategy {\n private _threeDSjs?: ThreeDSjs;\n private _sessionId = '';\n\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _CBAMGPSScriptLoader: CBAMPGSScriptLoader,\n private _locale: string,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const { methodId } = options;\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n const {\n clientToken,\n initializationData: { isTestModeFlagEnabled = false, merchantId },\n config: { is3dsEnabled },\n } = paymentMethod;\n\n if (is3dsEnabled) {\n this._threeDSjs = await this._CBAMGPSScriptLoader.load(isTestModeFlagEnabled);\n\n if (!this._threeDSjs) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!clientToken || !merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._sessionId = clientToken;\n\n await this._threeDSjs.configure({\n merchantId,\n sessionId: this._sessionId,\n callback: () => {\n if (this._threeDSjs?.isConfigured()) {\n return this._store.getState();\n }\n\n throw new PaymentMethodFailedError('Failed to configure 3DS API.');\n },\n configuration: {\n userLanguage: this._locale,\n wsVersion: 62,\n },\n });\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment } = payload;\n const paymentData = payment && payment.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(payment.methodId);\n\n const { is3dsEnabled } = paymentMethod.config;\n\n if (is3dsEnabled) {\n const newPaymentData = {\n ...paymentData,\n threeDSecure: { token: this._sessionId },\n };\n\n if (payload.payment) {\n payload.payment.paymentData = newPaymentData;\n }\n }\n\n return super.execute(payload, options).catch((error) => {\n if (\n !is3dsEnabled ||\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return Promise.reject(error);\n }\n\n const state = this._store.getState();\n const order = state.order.getOrder();\n const {\n storeProfile: { storeId },\n } = state.config.getStoreConfigOrThrow();\n\n if (!order || !this._sessionId) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const orderId = `${storeId}_${order.orderId}`;\n\n const {\n three_ds_result: { token: transactionId },\n } = error.body;\n\n if (!transactionId) {\n return Promise.reject(error);\n }\n\n return this._initiateAuthentication(orderId, transactionId);\n });\n }\n\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this._store.getState();\n const order = state.order.getOrder();\n\n if (order && state.payment.getPaymentStatus() === paymentStatusTypes.FINALIZE) {\n return this._store.dispatch(\n this._orderActionCreator.finalizeOrder(order.orderId, options),\n );\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this._threeDSjs = undefined;\n this._sessionId = '';\n\n return super.deinitialize();\n }\n\n private async _initiateAuthentication(\n orderId: string,\n transactionId: string,\n ): Promise {\n const response: RestApiResponse = await new Promise((resolve, reject) => {\n if (!this._threeDSjs) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._threeDSjs.initiateAuthentication(orderId, transactionId, (data) => {\n const error = data.error;\n\n if (error) {\n return reject(new PaymentMethodDeclinedError(error.msg));\n }\n\n if (this._threeDSjs && data.gatewayRecommendation === THREE_D_SECURE_PROCEED) {\n return resolve(data.restApiResponse);\n }\n\n return reject(new PaymentMethodDeclinedError());\n });\n });\n\n if (\n response.transaction &&\n response.transaction.authenticationStatus === THREE_D_SECURE_AVAILABLE\n ) {\n return this._authenticatePayer(orderId, transactionId);\n }\n\n throw new PaymentMethodDeclinedError();\n }\n\n private async _authenticatePayer(\n orderId: string,\n transactionId: string,\n attempt = 1,\n ): Promise {\n return new Promise((_resolve, reject) => {\n if (!this._threeDSjs) {\n return reject(\n new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n this._threeDSjs.authenticatePayer(\n orderId,\n transactionId,\n async (data) => {\n const error = data.error;\n\n if (error) {\n if (error.cause && error.cause === THREE_D_SECURE_BUSY && attempt < 5) {\n // Wait 3 seconds for MPGS server to process the `initiateAuthentication` call\n // See: Step 1: Initiate Authentication -> Initiate Authentication Request:\n // https://ap-gateway.mastercard.com/api/documentation/integrationGuidelines/supportedFeatures/pickAdditionalFunctionality/authentication/3DS/integrationModelAPI.html?locale=en_US#x_3DSTest\n await new Promise((resolve) => setTimeout(resolve, 3000));\n\n return this._authenticatePayer(orderId, transactionId, ++attempt);\n }\n\n return reject(new PaymentMethodDeclinedError());\n }\n\n // ThreeDSjs will handle the redirect so return a promise that doesn't really resolve\n return new Promise(noop);\n },\n { fullScreenRedirect: true },\n );\n });\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { CBAMPGSHostWindow, ThreeDSjs } from './cba-mpgs';\n\nexport default class CBAMPGSScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, private _window: CBAMPGSHostWindow = window) {}\n\n async load(testMode?: boolean): Promise {\n await this._scriptLoader.loadScript(\n `//${\n testMode ? 'test' : 'ap'\n }-gateway.mastercard.com/static/threeDS/1.3.0/three-ds.min.js`,\n );\n\n if (!this._window.ThreeDS) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.ThreeDS;\n }\n}\n","export enum ChasePayEventType {\n StartCheckout = 'startCheckout',\n CompleteCheckout = 'completeCheckout',\n CancelCheckout = 'cancelCheckout',\n}\n\nexport interface ChasePayEventMap {\n [ChasePayEventType.StartCheckout](digitalSessionId: string): void;\n [ChasePayEventType.CompleteCheckout](payload: ChasePaySuccessPayload): void;\n [ChasePayEventType.CancelCheckout](): void;\n}\n\nexport interface ChasePayHostWindow extends Window {\n JPMC?: JPMC;\n}\n\nexport interface JPMC {\n ChasePay: ChasePay;\n}\n\nexport interface ChasePaySuccessPayload {\n sessionToken: string;\n}\n\nexport interface ChasePayInsertOptions {\n color?: string;\n containers?: string[];\n height?: number;\n width?: number;\n}\n\nexport interface ChasePayConfigureOptions {\n language?: string;\n zindex?: number;\n sessionWarningTime?: number;\n sessionTimeoutTime?: number;\n}\n\nexport interface ChasePay {\n EventType: {\n START_CHECKOUT: ChasePayEventType.StartCheckout;\n COMPLETE_CHECKOUT: ChasePayEventType.CompleteCheckout;\n CANCEL_CHECKOUT: ChasePayEventType.CancelCheckout;\n };\n isChasePayUp: boolean;\n insertButtons(options: ChasePayInsertOptions): void;\n insertBrandings(options: ChasePayInsertOptions): void;\n startCheckout(digitalSessionId?: string): void;\n showLoadingAnimation(): void;\n configure(options: ChasePayConfigureOptions): void;\n on(\n eventType: ChasePayEventType,\n callback: ChasePayEventMap[ChasePayEventType],\n ): void;\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\nimport { Subject } from 'rxjs';\nimport { take } from 'rxjs/operators';\n\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { SDK_VERSION_HEADERS } from '../../../common/http-request';\nimport { bindDecorator as bind } from '../../../common/utility';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentMethodCancelledError } from '../../errors';\nimport Payment from '../../payment';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategyActionCreator from '../../payment-strategy-action-creator';\nimport PaymentStrategy from '../payment-strategy';\nimport { WepayRiskClient } from '../wepay';\n\nimport { ChasePay, ChasePayEventType, ChasePaySuccessPayload } from './chasepay';\nimport ChasePayInitializeOptions from './chasepay-initialize-options';\nimport ChasePayScriptLoader from './chasepay-script-loader';\n\nexport default class ChasePayPaymentStrategy implements PaymentStrategy {\n private _chasePayClient?: ChasePay;\n private _methodId!: string;\n private _walletButton?: HTMLElement;\n private _walletEvent$: Subject<{ type: ChasePayEventType }>;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentStrategyActionCreator: PaymentStrategyActionCreator,\n private _requestSender: RequestSender,\n private _chasePayScriptLoader: ChasePayScriptLoader,\n private _wepayRiskClient: WepayRiskClient,\n ) {\n this._walletEvent$ = new Subject();\n }\n\n initialize(options: PaymentInitializeOptions): Promise {\n this._methodId = options.methodId;\n\n if (!options.chasepay) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.chasepay\" argument is not provided.',\n );\n }\n\n const walletButton =\n options.chasepay.walletButton && document.getElementById(options.chasepay.walletButton);\n\n if (walletButton) {\n this._walletButton = walletButton;\n this._walletButton.addEventListener('click', this._handleWalletButtonClick);\n }\n\n return this._configureWallet(options.chasepay).then(() => this._store.getState());\n }\n\n deinitialize(): Promise {\n if (this._walletButton) {\n this._walletButton.removeEventListener('click', this._handleWalletButtonClick);\n }\n\n this._walletButton = undefined;\n this._chasePayClient = undefined;\n\n return Promise.resolve(this._store.getState());\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n return this._getPayment()\n .catch((error) => {\n if (error.subtype === MissingDataErrorType.MissingPayment) {\n return this._displayWallet().then(() => this._getPayment());\n }\n\n throw error;\n })\n .then((payment) => this._createOrder(payment, payload.useStoreCredit, options));\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private _configureWallet(options: ChasePayInitializeOptions): Promise {\n const state = this._store.getState();\n const paymentMethod = state.paymentMethods.getPaymentMethod(this._methodId);\n const storeConfig = state.config.getStoreConfig();\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n return this._chasePayScriptLoader\n .load(paymentMethod.config.testMode)\n .then(({ ChasePay }) => {\n this._chasePayClient = ChasePay;\n\n if (options.logoContainer && document.getElementById(options.logoContainer)) {\n this._chasePayClient.insertBrandings({\n color: 'white',\n containers: [options.logoContainer],\n });\n }\n\n this._chasePayClient.configure({\n language: storeConfig.storeProfile.storeLanguage,\n });\n\n this._chasePayClient.on(ChasePayEventType.CancelCheckout, () => {\n this._walletEvent$.next({ type: ChasePayEventType.CancelCheckout });\n\n if (options.onCancel) {\n options.onCancel();\n }\n });\n\n this._chasePayClient.on(\n ChasePayEventType.CompleteCheckout,\n (payload: ChasePaySuccessPayload) => {\n this._setSessionToken(payload.sessionToken).then(() => {\n this._walletEvent$.next({ type: ChasePayEventType.CompleteCheckout });\n\n if (options.onPaymentSelect) {\n options.onPaymentSelect();\n }\n });\n },\n );\n });\n }\n\n private _displayWallet(): Promise {\n return this._store.dispatch(\n this._paymentStrategyActionCreator.widgetInteraction(\n () => {\n this._store\n .dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(this._methodId),\n )\n .then((state) => {\n const paymentMethod = state.paymentMethods.getPaymentMethod(\n this._methodId,\n );\n\n if (!this._chasePayClient) {\n throw new NotInitializedError(\n NotInitializedErrorType.PaymentNotInitialized,\n );\n }\n\n if (!paymentMethod) {\n throw new MissingDataError(\n MissingDataErrorType.MissingPaymentMethod,\n );\n }\n\n this._chasePayClient.showLoadingAnimation();\n this._chasePayClient.startCheckout(\n paymentMethod.initializationData.digitalSessionId,\n );\n });\n\n // Wait for payment selection\n return new Promise((resolve, reject) => {\n this._walletEvent$\n .pipe(take(1))\n .subscribe((event: { type: ChasePayEventType }) => {\n if (event.type === ChasePayEventType.CancelCheckout) {\n reject(new PaymentMethodCancelledError());\n } else if (event.type === ChasePayEventType.CompleteCheckout) {\n resolve();\n }\n });\n });\n },\n { methodId: this._methodId },\n ),\n { queueId: 'widgetInteraction' },\n );\n }\n\n private _setSessionToken(sessionToken: string): Promise {\n const state = this._store.getState();\n const paymentMethod = state.paymentMethods.getPaymentMethod(this._methodId);\n const merchantRequestId =\n paymentMethod && paymentMethod.initializationData.merchantRequestId;\n\n return (\n this._requestSender\n .post('checkout.php', {\n headers: {\n Accept: 'text/html',\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n ...SDK_VERSION_HEADERS,\n },\n body: {\n action: 'set_external_checkout',\n provider: this._methodId,\n sessionToken,\n merchantRequestId,\n },\n })\n // Re-hydrate checkout data\n .then(() =>\n Promise.all([\n this._store.dispatch(this._checkoutActionCreator.loadCurrentCheckout()),\n this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(this._methodId),\n ),\n ]),\n )\n .then(() => this._store.getState())\n );\n }\n\n private _getPayment(): Promise {\n return this._store\n .dispatch(this._paymentMethodActionCreator.loadPaymentMethod(this._methodId))\n .then(() => {\n if (this._methodId === 'wepay') {\n return this._wepayRiskClient\n .initialize()\n .then((client) => client.getRiskToken());\n }\n\n return '';\n })\n .then((riskToken) => {\n const state = this._store.getState();\n const paymentMethod = state.paymentMethods.getPaymentMethod(this._methodId);\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (!paymentMethod.initializationData.paymentCryptogram) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n const paymentData = {\n method: this._methodId,\n cryptogramId: paymentMethod.initializationData.paymentCryptogram,\n eci: paymentMethod.initializationData.eci,\n transactionId: btoa(paymentMethod.initializationData.reqTokenId),\n ccExpiry: {\n month: paymentMethod.initializationData.expDate.toString().substr(0, 2),\n year: paymentMethod.initializationData.expDate.toString().substr(2, 2),\n },\n ccNumber: paymentMethod.initializationData.accountNum,\n accountMask: paymentMethod.initializationData.accountMask,\n extraData: riskToken ? { riskToken } : undefined,\n };\n\n return {\n methodId: this._methodId,\n paymentData,\n };\n });\n }\n\n private _createOrder(\n payment: Payment,\n useStoreCredit?: boolean,\n options?: PaymentRequestOptions,\n ): Promise {\n return this._store\n .dispatch(this._orderActionCreator.submitOrder({ useStoreCredit }, options))\n .then(() => this._store.dispatch(this._paymentActionCreator.submitPayment(payment)));\n }\n\n @bind\n private _handleWalletButtonClick(event: Event): void {\n event.preventDefault();\n\n this._displayWallet();\n }\n}\n","export default interface PaymentResponseBody {\n status: string;\n id: string;\n avs_result: AvsResult | {};\n cvv_result: CvvResult | {};\n three_ds_result: ThreeDsResult | {};\n fraud_review: boolean;\n transaction_type: string;\n additional_action_required?: AdditionalActionRequired;\n errors?: Array<{\n code: string;\n message: string;\n }>;\n}\n\nexport interface AvsResult {\n code: string;\n message: string;\n street_match: string;\n postal_match: string;\n}\n\nexport interface CvvResult {\n code: string;\n message: string;\n}\n\nexport interface ThreeDsResult {\n acs_url: string;\n payer_auth_request: string;\n merchant_data: string;\n callback_url: string;\n}\n\nexport interface AdditionalActionRequired {\n type: AdditionalActionType;\n data: AdditionalRedirectData;\n}\n\nexport interface AdditionalRedirectData {\n redirect_url: string;\n transaction_id?: string;\n}\n\nexport enum AdditionalActionType {\n OffsiteRedirect = 'offsite_redirect',\n}\n","import { InternalCheckoutSelectors } from '../../../checkout';\nimport {\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport { AdditionalActionRequired, AdditionalActionType } from '../../payment-response-body';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class CheckoutcomCustomPaymentStrategy extends CreditCardPaymentStrategy {\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this._store.getState();\n const order = state.order.getOrder();\n\n if (order && state.payment.getPaymentStatus() === paymentStatusTypes.FINALIZE) {\n return this._store.dispatch(\n this._orderActionCreator.finalizeOrder(order.orderId, options),\n );\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n protected async _executeWithHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!payment || !payment.methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n try {\n await form.validate();\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n await form.submit(payment);\n } catch (error) {\n return this._processResponse(error);\n }\n\n return this._store.dispatch(this._orderActionCreator.loadCurrentOrder());\n }\n\n protected _processResponse(error: RequestError): Promise {\n if (!(error instanceof RequestError)) {\n return Promise.reject(error);\n }\n\n const additionalActionRequired: AdditionalActionRequired =\n error.body.additional_action_required;\n\n // TODO validate all possible responses and perform respective additional actions\n if (\n additionalActionRequired &&\n additionalActionRequired.type === AdditionalActionType.OffsiteRedirect\n ) {\n return this._performRedirect(additionalActionRequired);\n }\n\n return Promise.reject(error);\n }\n\n private _performRedirect(\n additionalActionRequired: AdditionalActionRequired,\n ): Promise {\n return new Promise(() => {\n window.location.replace(additionalActionRequired.data.redirect_url);\n });\n }\n}\n","import { InternalCheckoutSelectors } from '../../../../checkout';\nimport { OrderRequestBody } from '../../../../order';\nimport { PaymentArgumentInvalidError } from '../../../errors';\nimport { PaymentInstrument, WithDocumentInstrument } from '../../../payment';\nimport { PaymentRequestOptions } from '../../../payment-request-options';\nimport CheckoutcomCustomPaymentStrategy from '../checkoutcom-custom-payment-strategy';\n\nconst DOCUMENT_SUPPORTED_APMS = ['boleto', 'oxxo', 'qpay', 'ideal'];\n\nexport default class CheckoutcomAPMPaymentStrategy extends CheckoutcomCustomPaymentStrategy {\n protected async _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment?.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n ...payment,\n paymentData: {\n ...paymentData,\n formattedPayload: this._createFormattedPayload(\n payment.methodId,\n paymentData,\n ),\n },\n }),\n );\n } catch (error) {\n return this._processResponse(error);\n }\n }\n\n private _createFormattedPayload(\n methodId: string,\n paymentData: PaymentInstrument,\n ): WithDocumentInstrument {\n const formattedPayload: WithDocumentInstrument = { ccDocument: '' };\n const ccDocument = 'ccDocument' in paymentData ? paymentData.ccDocument : '';\n\n if (DOCUMENT_SUPPORTED_APMS.indexOf(methodId) !== -1 && ccDocument) {\n formattedPayload.ccDocument = ccDocument;\n }\n\n return formattedPayload;\n }\n}\n","import { InternalCheckoutSelectors } from '../../../../checkout';\nimport { OrderRequestBody } from '../../../../order';\nimport { PaymentArgumentInvalidError } from '../../../errors';\nimport { PaymentInstrument, WithCheckoutcomFawryInstrument } from '../../../payment';\nimport { PaymentRequestOptions } from '../../../payment-request-options';\nimport CheckoutcomCustomPaymentStrategy from '../checkoutcom-custom-payment-strategy';\n\nconst CHECKOUTCOM_FAWRY_PAYMENT_METHOD = 'fawry';\n\nexport default class CheckoutcomFawryPaymentStrategy extends CheckoutcomCustomPaymentStrategy {\n protected async _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment && payment.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n ...payment,\n paymentData: {\n ...paymentData,\n formattedPayload: this._createFormattedPayload(\n payment.methodId,\n paymentData,\n ),\n },\n }),\n );\n } catch (error) {\n return this._processResponse(error);\n }\n }\n\n private _createFormattedPayload(\n methodId: string,\n paymentData: PaymentInstrument,\n ): WithCheckoutcomFawryInstrument | undefined {\n if (\n CHECKOUTCOM_FAWRY_PAYMENT_METHOD === methodId &&\n 'customerMobile' in paymentData &&\n 'customerEmail' in paymentData\n ) {\n return {\n customerMobile: paymentData.customerMobile,\n customerEmail: paymentData.customerEmail,\n };\n }\n }\n}\n","import { InternalCheckoutSelectors } from '../../../../checkout';\nimport { OrderRequestBody } from '../../../../order';\nimport { PaymentArgumentInvalidError } from '../../../errors';\nimport { PaymentInstrument, WithCheckoutcomiDealInstrument } from '../../../payment';\nimport { PaymentRequestOptions } from '../../../payment-request-options';\nimport CheckoutcomCustomPaymentStrategy from '../checkoutcom-custom-payment-strategy';\n\nconst CHECKOUTCOM_IDEAL_PAYMENT_METHOD = 'ideal';\n\nexport default class CheckoutcomiDealPaymentStrategy extends CheckoutcomCustomPaymentStrategy {\n protected async _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment?.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n ...payment,\n paymentData: {\n ...paymentData,\n formattedPayload: this._createFormattedPayload(\n payment.methodId,\n paymentData,\n ),\n },\n }),\n );\n } catch (error) {\n return this._processResponse(error);\n }\n }\n\n private _createFormattedPayload(\n methodId: string,\n paymentData: PaymentInstrument,\n ): WithCheckoutcomiDealInstrument | undefined {\n if (CHECKOUTCOM_IDEAL_PAYMENT_METHOD === methodId && 'bic' in paymentData) {\n return { bic: paymentData.bic };\n }\n }\n}\n","import { InternalCheckoutSelectors } from '../../../../checkout';\nimport { OrderRequestBody } from '../../../../order';\nimport { PaymentArgumentInvalidError } from '../../../errors';\nimport { PaymentInstrument, WithCheckoutcomSEPAInstrument } from '../../../payment';\nimport { PaymentRequestOptions } from '../../../payment-request-options';\nimport CheckoutcomCustomPaymentStrategy from '../checkoutcom-custom-payment-strategy';\n\nconst CHECKOUTCOM_SEPA_PAYMENT_METHOD = 'sepa';\n\nexport default class CheckoutcomSEPAPaymentStrategy extends CheckoutcomCustomPaymentStrategy {\n protected async _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment?.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n ...payment,\n paymentData: {\n ...paymentData,\n formattedPayload: this._createFormattedPayload(\n payment.methodId,\n paymentData,\n ),\n },\n }),\n );\n } catch (error) {\n return this._processResponse(error);\n }\n }\n\n private _createFormattedPayload(\n methodId: string,\n paymentData: PaymentInstrument,\n ): WithCheckoutcomSEPAInstrument {\n const formattedPayload: WithCheckoutcomSEPAInstrument = { iban: '', bic: '' };\n const { iban, bic } = 'iban' in paymentData ? paymentData : formattedPayload;\n\n if (methodId === CHECKOUTCOM_SEPA_PAYMENT_METHOD && document) {\n formattedPayload.iban = iban;\n formattedPayload.bic = bic;\n }\n\n return formattedPayload;\n }\n}\n","import { noop } from 'lodash';\n\nimport { CheckoutStore, CheckoutValidator, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { RequestOptions } from '../../../common/http-request';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotCompletedError } from '../../../order/errors';\nimport { RemoteCheckoutRequestSender } from '../../../remote-checkout';\nimport { StoreCreditActionCreator } from '../../../store-credit';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport ClearpayScriptLoader from './clearpay-script-loader';\nimport ClearpaySdk from './clearpay-sdk';\n\nexport default class ClearpayPaymentStrategy implements PaymentStrategy {\n private _clearpaySdk?: ClearpaySdk;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutValidator: CheckoutValidator,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _remoteCheckoutRequestSender: RemoteCheckoutRequestSender,\n private _storeCreditActionCreator: StoreCreditActionCreator,\n private _clearpayScriptLoader: ClearpayScriptLoader,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(options.methodId, options.gatewayId);\n\n this._clearpaySdk = await this._clearpayScriptLoader.load(paymentMethod);\n\n return this._store.getState();\n }\n\n deinitialize(): Promise {\n this._clearpaySdk = undefined;\n\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n if (!payload.payment) {\n throw new PaymentArgumentInvalidError(['payment.gatewayId', 'payment.methodId']);\n }\n\n const { gatewayId, methodId } = payload.payment;\n\n if (!gatewayId || !methodId) {\n throw new PaymentArgumentInvalidError(['payment.gatewayId', 'payment.methodId']);\n }\n\n const { isStoreCreditApplied: useStoreCredit } = this._store\n .getState()\n .checkout.getCheckoutOrThrow();\n let state = this._store.getState();\n\n if (useStoreCredit !== undefined) {\n state = await this._store.dispatch(\n this._storeCreditActionCreator.applyStoreCredit(useStoreCredit),\n );\n }\n\n await this._checkoutValidator.validate(state.checkout.getCheckout(), options);\n\n const { countryCode } = this._store.getState().billingAddress.getBillingAddressOrThrow();\n\n if (!this._isCountrySupported(countryCode)) {\n throw new InvalidArgumentError(\n 'Unable to proceed because billing country is not supported.',\n );\n }\n\n state = await this._loadPaymentMethod(gatewayId, methodId, options);\n\n await this._redirectToClearpay(\n countryCode,\n state.paymentMethods.getPaymentMethod(methodId, gatewayId),\n );\n\n // Clearpay will handle the rest of the flow so return a promise that doesn't really resolve\n return new Promise(noop);\n }\n\n async finalize(options: PaymentRequestOptions): Promise {\n const state = this._store.getState();\n const payment = state.payment.getPaymentId();\n const config = state.config.getContextConfig();\n\n if (!payment) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!config || !config.payment.token) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const paymentPayload = {\n methodId: payment.providerId,\n paymentData: { nonce: config.payment.token },\n };\n\n await this._store.dispatch(this._orderActionCreator.submitOrder({}, options));\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentPayload),\n );\n } catch (error) {\n await this._remoteCheckoutRequestSender.forgetCheckout();\n await this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethods());\n\n throw new OrderFinalizationNotCompletedError(error.body?.errors?.[0]?.message);\n }\n }\n\n private _redirectToClearpay(countryCode: string, paymentMethod?: PaymentMethod): void {\n if (!this._clearpaySdk || !paymentMethod || !paymentMethod.clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._clearpaySdk.initialize({ countryCode });\n this._clearpaySdk.redirect({ token: paymentMethod.clientToken });\n }\n\n private _isCountrySupported(countryCode: string): boolean {\n return countryCode === 'GB';\n }\n\n private async _loadPaymentMethod(\n gatewayId: string,\n methodId: string,\n options?: RequestOptions,\n ): Promise {\n try {\n return await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(gatewayId, {\n ...options,\n params: { ...options?.params, method: methodId },\n }),\n );\n } catch (error) {\n if (error instanceof RequestError && error.body?.status === 422) {\n throw new InvalidArgumentError(\n \"Clearpay can't process your payment for this order, please try another payment method\",\n );\n }\n\n throw error;\n }\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\nimport PaymentMethod from '../../payment-method';\n\nimport ClearpaySdk from './clearpay-sdk';\nimport ClearpayWindow from './clearpay-window';\n\nconst SCRIPTS_DEFAULT = {\n PROD: '//portal.clearpay.co.uk/afterpay-async.js',\n SANDBOX: '//portal.sandbox.clearpay.co.uk/afterpay-async.js',\n};\n\nexport default class ClearpayScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, public _window: ClearpayWindow = window) {}\n\n async load(method: PaymentMethod): Promise {\n await this._scriptLoader.loadScript(this._getScriptUrl(method.config.testMode));\n\n if (!this._window.AfterPay) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.AfterPay;\n }\n\n private _getScriptUrl(testMode?: boolean): string {\n return testMode ? SCRIPTS_DEFAULT.SANDBOX : SCRIPTS_DEFAULT.PROD;\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { some } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { RequestError } from '../../../common/error/errors';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class ConvergePaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _formPoster: FormPoster,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n return super.execute(payload, options).catch((error) => {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return Promise.reject(error);\n }\n\n return new Promise(() => {\n this._formPoster.postForm(error.body.three_ds_result.acs_url, {\n PaReq: error.body.three_ds_result.payer_auth_request,\n TermUrl: error.body.three_ds_result.callback_url,\n MD: error.body.three_ds_result.merchant_data,\n });\n });\n });\n }\n\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this._store.getState();\n const order = state.order.getOrder();\n\n if (order && state.payment.getPaymentStatus() === paymentStatusTypes.FINALIZE) {\n return this._store.dispatch(\n this._orderActionCreator.finalizeOrder(order.orderId, options),\n );\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { some } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class CreditCardRedirectPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n protected _store: CheckoutStore,\n protected _orderActionCreator: OrderActionCreator,\n protected _paymentActionCreator: PaymentActionCreator,\n protected _hostedFormFactory: HostedFormFactory,\n protected _formPoster: FormPoster,\n ) {\n super(_store, _orderActionCreator, _paymentActionCreator, _hostedFormFactory);\n }\n\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this._store.getState();\n const order = state.order.getOrder();\n\n if (order && state.payment.getPaymentStatus() === paymentStatusTypes.FINALIZE) {\n return this._store.dispatch(\n this._orderActionCreator.finalizeOrder(order.orderId, options),\n );\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n protected async _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment && payment.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({ ...payment, paymentData }),\n );\n } catch (error) {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return Promise.reject(error);\n }\n\n return new Promise(() =>\n this._formPoster.postForm(error.body.three_ds_result.acs_url, {\n PaReq: error.body.three_ds_result.payer_auth_request || null,\n TermUrl: error.body.three_ds_result.callback_url || null,\n MD: error.body.three_ds_result.merchant_data || null,\n }),\n );\n }\n }\n\n protected async _executeWithHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!payment || !payment.methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n try {\n await form.validate();\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n await form.submit(payment);\n } catch (error) {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return Promise.reject(error);\n }\n\n return new Promise(() =>\n this._formPoster.postForm(error.body.three_ds_result.acs_url, {\n PaReq: error.body.three_ds_result.payer_auth_request || null,\n TermUrl: error.body.three_ds_result.callback_url || null,\n MD: error.body.three_ds_result.merchant_data || null,\n }),\n );\n }\n\n return this._store.dispatch(this._orderActionCreator.loadCurrentOrder());\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { CardinalThreeDSecureFlow } from '../cardinal';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class CyberSourcePaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _threeDSecureFlow: CardinalThreeDSecureFlow,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(options.methodId);\n\n if (paymentMethod.config.is3dsEnabled) {\n await this._threeDSecureFlow.prepare(paymentMethod);\n }\n\n return this._store.getState();\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment: { methodId = '' } = {} } = payload;\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n\n if (getPaymentMethodOrThrow(methodId).config.is3dsEnabled) {\n return this._threeDSecureFlow.start(\n super.execute.bind(this),\n payload,\n options,\n this._hostedForm,\n );\n }\n\n return super.execute(payload, options);\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { CardinalThreeDSecureFlowV2 } from '../cardinal';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class CyberSourceV2PaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _threeDSecureFlow: CardinalThreeDSecureFlowV2,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(options.methodId);\n\n if (paymentMethod.config.is3dsEnabled) {\n await this._threeDSecureFlow.prepare(paymentMethod);\n }\n\n return this._store.getState();\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment: { methodId = '' } = {} } = payload;\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n\n if (getPaymentMethodOrThrow(methodId).config.is3dsEnabled) {\n return this._threeDSecureFlow.start(\n super.execute.bind(this),\n payload,\n options,\n this._hostedForm,\n );\n }\n\n return super.execute(payload, options);\n }\n}\n","export interface DigitalRiverWindow extends Window {\n /**\n * Object to create an instance of the DigitalRiver object. This is called a Digital River publishable API key\n * This function accepts an optional options object using the following format DigitalRiver(publishableApiKey{, options})\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/digitalriver.js/reference/digital-river-publishable-api-key\n */\n DigitalRiver?: DigitalRiverClass;\n}\n\nexport type DigitalRiverClass = new (\n apiKey: string,\n options?: DigitalRiverJSOptions,\n) => DigitalRiverJS;\n\nexport default interface DigitalRiverJS {\n createDropin(configuration: DigitalRiverDropInConfiguration): DigitalRiverDropIn;\n authenticateSource(\n data: DigitalRiverAuthenticateSourceRequest,\n ): Promise;\n createElement(type: string, options: DigitalRiverElementOptions): DigitalRiverElement;\n}\n\nexport interface DigitalRiverElementOptions {\n classes: {\n base: string;\n };\n compliance: {\n entity: string;\n };\n}\n\ninterface DigitalRiverAuthenticateSourceRequest {\n sessionId: string;\n sourceId: string;\n sourceClientSecret: string;\n}\n\nexport interface DigitalRiverAdditionalProviderData {\n source_id: string;\n source_client_secret: string;\n}\n\nexport interface DigitalRiverAuthenticateSourceResponse {\n status: AuthenticationSourceStatus;\n}\n\nexport enum AuthenticationSourceStatus {\n complete = 'complete',\n authentication_not_required = 'authentication_not_required',\n failed = 'failed',\n}\n\nexport interface DigitalRiverJSOptions {\n /**\n * The locale used to localize the various display and error strings within DigitalRiver.js\n * Currently supported locales:\n * ar-EG, cs-CZ, da-DK, de-AT, de-CH, de-DE, el-GR, en-AU, en-BE, en-CA, en-CH, en-DK, en-FI, en-GB, en-IE, en-IN,\n * en-MY, en-NL, en-NO, en-NZ, en-PR, en-SE, en-SG, en-US, en-ZA, es-AR, es-CL, es-CO, es-EC, es-ES, es-MX, es-PE,\n * es-VE, et-EE, fi-FI, fr-BE, fr-CA, fr-CH, fr-FR, hu-HU, it-CH, it-IT, iw-IL, ja-JP, ko-KR, lt-LT, lv-LV, nl-BE,\n * nl-NL, no-NO, pl-PL, pt-BR, pt-PT, ro-RO, ru-RU, sk-SK, sl-SI, sr-YU, sv-SE, th-TH, tr-TR, zh-CN, zh-HK, zh-TW\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/digitalriver.js/reference/digital-river-publishable-api-key\n */\n locale?: string;\n}\n\n/**\n * Create a Configuration object for Drop-in\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#step-5-configure-hydrate\n */\nexport interface DigitalRiverDropInConfiguration {\n /**\n * The payment session identifier returned by Digital River.\n */\n sessionId: string;\n\n /**\n * you can specify options to trigger different features or functionality\n */\n options?: OptionsResponse;\n billingAddress: {\n firstName: string;\n lastName: string;\n email: string;\n phoneNumber: string;\n address: {\n line1: string;\n line2?: string;\n city?: string;\n state?: string;\n postalCode: string;\n country: string;\n };\n };\n\n /**\n * Additional configuration details for configuration structure (classes, styles etc..)\n */\n paymentMethodConfiguration?: BaseElementOptions;\n\n /**\n * The function called when the shopper has authorized payment and a payment source has been successfully created.\n */\n onSuccess?(data: OnSuccessResponse): void;\n\n /**\n * The function called when the shopper cancels the payment process before authorizing payment.\n */\n onCancel?(error: OnCancelOrErrorResponse): void;\n\n /**\n * The function called when an error has occurred.\n */\n onError?(error: OnCancelOrErrorResponse): void;\n\n /**\n * The function called when Drop-in is ready for user interaction.\n */\n onReady?(data: OnReadyResponse): void;\n}\n\nexport interface OnCancelOrErrorResponse {\n /**\n * If an error occurs, Drop-in emits an event that identifies the payment method associated with the error.\n * Instruct your customer to provide a new method of payment.\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#onerror\n * Or When your customer chooses to pay with a specific payment method and decides to cancel during the redirect phase,\n * Drop-in emits an event that identifies the cancelled payment method.\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#oncancel\n */\n errors: ErrorData[];\n}\n\nexport interface ErrorData {\n code: string;\n message: string;\n}\n\nexport interface OnReadyResponse {\n /**\n * When ready, Drop-in will emit an event that contains a \"paymentMethodTypes\" array of the available payment methods.\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#onready\n */\n paymentMethodTypes: string[];\n}\n\n/**\n * When creating your Drop-in instance, you can specify options to trigger different features or functionality.\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#drop-in-options\n */\nexport interface OptionsResponse {\n /**\n * Use this option if you are using Drop-in within a standard checkout flow. Example Value: \"checkout\"\n */\n flow?: string;\n\n /**\n * When enabled, presents the customer with an option to save their payment details for future use within Drop-in.\n * Enabling this feature will show the appropriate check boxes and localized disclosure statements and facilitate\n * any necessary Strong Customer Authentication.\n * If disabled, Drop-in will not present the customer with an option to save their payment details.\n */\n showSavePaymentAgreement?: boolean;\n\n /**\n * Will show a localized compliance link section as part of Drop-in. This is an important piece for accessing the Digital River business model.\n */\n showComplianceSection?: boolean;\n\n /**\n * Use this option to customize the text of the Drop-in button.\n */\n button?: ButtonResponse;\n\n /**\n * Use this option to specify the future use of a source.\n */\n usage?: string;\n\n /**\n * Use this option to show the required terms of sale disclosure. These localized terms automatically update if recurring products are purchased.\n */\n showTermsOfSaleDisclosure?: boolean;\n\n /**\n * Additional configuration details for drop-in.\n */\n paymentMethodConfiguration?: BaseElementOptions;\n}\n\nexport interface ButtonResponse {\n /**\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#customizing-the-text-of-the-drop-in-button\n * The text of the Drop-in button is customizable. You can either display pre-configured text or you can specify a unique text\n * Examples type: \"payNow\" || type: \"buyNow\" || type: \"completeOrder\" || type: \"submitOrder\"\n */\n type: string;\n}\n\nexport interface OnSuccessResponse {\n /**\n * Event that gets triggered after the customer's payment has provided with the necessary details for payment\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#onsuccess\n */\n source: {\n id: string;\n reusable: boolean;\n browserInfo?: {\n browserIp?: string;\n };\n owner?: {\n email: string;\n firstName: string;\n lastName: string;\n phoneNumber: string;\n address: {\n city: string;\n country: string;\n line1: string;\n postalCode: string;\n state: string;\n };\n };\n };\n\n /**\n * Indicates whether the source has been enabled for future use.\n * Important: If this value is true, it does not mean the customer can use this source multiple times.\n * This flag identifies whether the necessary downstream actions have been triggered to prepare the source for storage.\n * You must attach the source to your customer for it to be truly reusable.\n */\n readyForStorage: boolean;\n}\n\nexport interface DigitalRiverDropIn {\n /**\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#step-7-place-drop-in-on-your-checkout-or-customer-page\n * example \"drop-in\"\n */\n mount(dropInId: string): void;\n}\n\ninterface DigitalRiverElement {\n /**\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#step-7-place-drop-in-on-your-checkout-or-customer-page\n * example \"drop-in\"\n */\n mount(dropInId: string): void;\n}\n\ninterface BaseElementOptions {\n /**\n * Set custom class names on the container DOM element when the Digital River element is in a particular state.\n */\n classes?: DigitalRiverElementClasses;\n /**\n * Use disabledPaymentMethods to disable specific payment methods.\n */\n disabledPaymentMethods?: string[];\n}\n\n/**\n * Custom classes\n * You can specify custom classes as part of a Class object included within the Options object when you create or\n * update an element. If you do not provide custom classes, the system uses the default options.\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/digitalriver.js/reference/elements#custom-classes\n */\nexport interface DigitalRiverElementClasses {\n /**\n * The Element is in its base state. The user either has not entered anything into the input field or is currently typing.\n */\n base?: string;\n\n /**\n * The Element is in its complete state. The user has input value, and it meets the basic validation requirements of that field.\n */\n complete?: string;\n\n /**\n * The Element is empty. The Element once had value but is now empty.\n */\n empty?: string;\n\n /**\n * The Element has focus.\n */\n focus?: string;\n\n /**\n * The Element has value, but it does not meet the basic validation requirements of the field.\n */\n invalid?: string;\n\n /**\n * The element has a value that has been automatically filled by the browser.\n */\n webkitAutofill?: string;\n}\n\nexport interface DigitalRiverInitializeToken {\n sessionId: string;\n checkoutData: DigitalRiverCheckoutData;\n}\n\ninterface DigitalRiverCheckoutData {\n checkoutId: string;\n sellingEntity: string;\n}\n","import { StandardError } from '../../../common/error/errors';\n\nconst defaultMessage =\n 'There was an error while processing your payment. Please try again or contact us.';\n\nexport default class DigitalRiverError extends StandardError {\n constructor(type: string, name: string, message?: string) {\n super(message || defaultMessage);\n\n this.type = type;\n this.name = name;\n }\n}\n","import { some } from 'lodash';\n\nimport { BillingAddressActionCreator } from '../../../billing';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { StoreCreditActionCreator } from '../../../store-credit';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport { HostedInstrument, isVaultedInstrument } from '../../index';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport DigitalRiverJS, {\n AuthenticationSourceStatus,\n DigitalRiverAdditionalProviderData,\n DigitalRiverAuthenticateSourceResponse,\n DigitalRiverDropIn,\n DigitalRiverElementOptions,\n DigitalRiverInitializeToken,\n OnCancelOrErrorResponse,\n OnReadyResponse,\n OnSuccessResponse,\n} from './digitalriver';\nimport DigitalRiverError from './digitalriver-error';\nimport DigitalRiverPaymentInitializeOptions from './digitalriver-payment-initialize-options';\nimport DigitalRiverScriptLoader from './digitalriver-script-loader';\n\nexport default class DigitalRiverPaymentStrategy implements PaymentStrategy {\n private _digitalRiverJS?: DigitalRiverJS;\n private _digitalRiverDropComponent?: DigitalRiverDropIn;\n private _submitFormEvent?: () => void;\n private _loadSuccessResponse?: OnSuccessResponse;\n private _digitalRiverCheckoutData?: DigitalRiverInitializeToken;\n private _unsubscribe?: () => void;\n private _digitalRiverInitializeOptions?: DigitalRiverPaymentInitializeOptions;\n\n constructor(\n private _store: CheckoutStore,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _storeCreditActionCreator: StoreCreditActionCreator,\n private _digitalRiverScriptLoader: DigitalRiverScriptLoader,\n private _billingAddressActionCreator: BillingAddressActionCreator,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n this._digitalRiverInitializeOptions = options.digitalriver;\n\n const paymentMethod = this._store\n .getState()\n .paymentMethods.getPaymentMethodOrThrow(options.methodId);\n const { publicKey, paymentLanguage: locale } = paymentMethod.initializationData;\n const { containerId } = this._getDigitalRiverInitializeOptions();\n\n this._digitalRiverJS = await this._digitalRiverScriptLoader.load(publicKey, locale);\n\n this._unsubscribe = await this._store.subscribe(\n async (state) => {\n if (\n state.paymentStrategies.isInitialized({\n methodId: options.methodId,\n gatewayId: options.gatewayId,\n })\n ) {\n const container = document.getElementById(containerId);\n\n if (container) {\n container.innerHTML = '';\n\n this._digitalRiverJS = await this._digitalRiverScriptLoader.load(\n publicKey,\n locale,\n );\n }\n\n await this._loadWidget(options);\n }\n },\n (state) => {\n const checkout = state.checkout.getCheckout();\n\n return checkout && checkout.outstandingBalance;\n },\n (state) => {\n const checkout = state.checkout.getCheckout();\n\n return checkout && checkout.coupons;\n },\n );\n\n return this._loadWidget(options);\n }\n\n deinitialize(): Promise {\n if (this._unsubscribe) {\n this._unsubscribe();\n }\n\n const { containerId } = this._getDigitalRiverInitializeOptions();\n const container = document.getElementById(containerId);\n\n if (container) {\n container.innerHTML = '';\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n orderRequest: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment || !payment.paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const { paymentData, methodId } = payment;\n const { shouldSetAsDefaultInstrument = false } = paymentData as HostedInstrument;\n const { isStoreCreditApplied: useStoreCredit } = this._store\n .getState()\n .checkout.getCheckoutOrThrow();\n\n if (useStoreCredit !== undefined) {\n await this._store.dispatch(\n this._storeCreditActionCreator.applyStoreCredit(useStoreCredit),\n );\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n if (!this._digitalRiverCheckoutData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (isVaultedInstrument(paymentData)) {\n try {\n return await this._submitVaultedInstrument(\n methodId,\n paymentData.instrumentId,\n this._digitalRiverCheckoutData.checkoutData.checkoutId,\n shouldSetAsDefaultInstrument,\n false,\n );\n } catch (error) {\n if (!this._isAuthenticateSourceAction(error)) {\n throw error;\n }\n\n const confirm = await this._authenticateSource(error.body.provider_data);\n\n return await this._submitVaultedInstrument(\n methodId,\n paymentData.instrumentId,\n this._digitalRiverCheckoutData.checkoutData.checkoutId,\n shouldSetAsDefaultInstrument,\n confirm,\n );\n }\n } else {\n if (!this._loadSuccessResponse) {\n throw new PaymentArgumentInvalidError(['this._loadSuccessResponse']);\n }\n\n const paymentPayload = {\n methodId: payment.methodId,\n paymentData: {\n formattedPayload: {\n credit_card_token: {\n token: JSON.stringify({\n checkoutId: this._digitalRiverCheckoutData.checkoutData.checkoutId,\n source: this._loadSuccessResponse,\n sessionId: this._digitalRiverCheckoutData.sessionId,\n }),\n },\n vault_payment_instrument: this._loadSuccessResponse.readyForStorage,\n set_as_default_stored_instrument: false,\n },\n },\n };\n\n return this._store.dispatch(this._paymentActionCreator.submitPayment(paymentPayload));\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private _getDigitalRiverJs(): DigitalRiverJS {\n if (!this._digitalRiverJS) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._digitalRiverJS;\n }\n\n private _getErrorMessage(error: OnCancelOrErrorResponse): string {\n const { errors } = error;\n\n return errors.map((e) => `code: ${e.code} message: ${e.message}`).join('\\n');\n }\n\n private async _onSuccessResponse(data?: OnSuccessResponse): Promise {\n const error = new InvalidArgumentError(\n 'Unable to initialize payment because success argument is not provided.',\n );\n\n if (data && this._submitFormEvent) {\n const { browserInfo, owner } = data.source;\n\n this._loadSuccessResponse = browserInfo\n ? {\n source: {\n id: data.source.id,\n reusable: data.source.reusable,\n ...browserInfo,\n },\n readyForStorage: data.readyForStorage,\n }\n : {\n source: {\n id: data.source.id,\n reusable: data.source.reusable,\n },\n readyForStorage: data.readyForStorage,\n };\n\n if (owner) {\n const billingAddressPayPal = {\n firstName: owner.firstName,\n lastName: owner.lastName,\n city: owner.address.city,\n company: '',\n address1: owner.address.line1,\n address2: '',\n postalCode: owner.address.postalCode,\n countryCode: owner.address.country,\n phone: owner.phoneNumber,\n stateOrProvince: owner.address.state,\n stateOrProvinceCode: owner.address.country,\n customFields: [],\n email: owner.email || owner.email,\n };\n\n this._loadSuccessResponse.source.owner = data.source.owner;\n await this._store.dispatch(\n this._billingAddressActionCreator.updateAddress(billingAddressPayPal),\n );\n }\n\n return this._submitFormEvent();\n }\n\n return this._getDigitalRiverInitializeOptions().onError?.(error);\n }\n\n private _onReadyResponse(data?: OnReadyResponse): void {\n if (data) {\n this._getDigitalRiverInitializeOptions().onRenderButton?.();\n }\n }\n\n private _getDigitalRiverInitializeOptions(): DigitalRiverPaymentInitializeOptions {\n if (!this._digitalRiverInitializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._digitalRiverInitializeOptions;\n }\n\n private async _loadWidget(\n options: PaymentInitializeOptions,\n ): Promise {\n try {\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(options.methodId),\n );\n const billing = state.billingAddress.getBillingAddressOrThrow();\n const customer = state.customer.getCustomerOrThrow();\n const { features } = state.config.getStoreConfigOrThrow().checkoutSettings;\n const { paymentMethodConfiguration } =\n this._getDigitalRiverInitializeOptions().configuration;\n const { containerId, configuration } = this._getDigitalRiverInitializeOptions();\n const { clientToken } = state.paymentMethods.getPaymentMethodOrThrow(options.methodId);\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._digitalRiverCheckoutData = JSON.parse(clientToken);\n\n if (!this._digitalRiverCheckoutData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._mountComplianceSection(this._digitalRiverCheckoutData.checkoutData.sellingEntity);\n\n this._submitFormEvent = this._getDigitalRiverInitializeOptions().onSubmitForm;\n\n const disabledPaymentMethods = features['PROJECT-4802.digital_river_paypal_support']\n ? []\n : ['payPal'];\n\n const digitalRiverConfiguration = {\n sessionId: this._digitalRiverCheckoutData.sessionId,\n options: {\n ...configuration,\n showSavePaymentAgreement:\n Boolean(customer.email) && configuration.showSavePaymentAgreement,\n },\n billingAddress: {\n firstName: billing.firstName,\n lastName: billing.lastName,\n email: billing.email || customer.email,\n phoneNumber: billing.phone,\n address: {\n line1: billing.address1,\n line2: billing.address2,\n city: billing.city,\n state: billing.stateOrProvinceCode,\n postalCode: billing.postalCode,\n country: billing.countryCode,\n },\n },\n paymentMethodConfiguration: {\n ...paymentMethodConfiguration,\n disabledPaymentMethods,\n },\n onSuccess: (data?: OnSuccessResponse) => {\n this._onSuccessResponse(data);\n },\n onReady: (data?: OnReadyResponse) => {\n this._onReadyResponse(data);\n },\n onError: (error: OnCancelOrErrorResponse) => {\n const descriptiveError = new Error(this._getErrorMessage(error));\n\n this._getDigitalRiverInitializeOptions().onError?.(descriptiveError);\n },\n };\n\n this._digitalRiverDropComponent = await this._getDigitalRiverJs().createDropin(\n digitalRiverConfiguration,\n );\n this._digitalRiverDropComponent.mount(containerId);\n\n return state;\n } catch {\n throw new DigitalRiverError(\n 'payment.digitalriver_checkout_error',\n 'digitalRiverCheckoutError',\n );\n }\n }\n\n private _isAuthenticateSourceAction(error: unknown): boolean {\n return !(\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'additional_action_required' })\n );\n }\n\n private async _authenticateSource(\n additionalAction: DigitalRiverAdditionalProviderData,\n ): Promise {\n if (!this._digitalRiverCheckoutData) {\n throw new InvalidArgumentError(\n 'Unable to proceed because payload payment argument is not provided.',\n );\n }\n\n const authenticateSourceResponse: DigitalRiverAuthenticateSourceResponse =\n await this._getDigitalRiverJs().authenticateSource({\n sessionId: this._digitalRiverCheckoutData.sessionId,\n sourceId: additionalAction.source_id,\n sourceClientSecret: additionalAction.source_client_secret,\n });\n\n if (authenticateSourceResponse.status === AuthenticationSourceStatus.failed) {\n throw new Error('Source authentication failed, please try again');\n }\n\n return (\n authenticateSourceResponse.status === AuthenticationSourceStatus.complete ||\n authenticateSourceResponse.status ===\n AuthenticationSourceStatus.authentication_not_required\n );\n }\n\n private async _submitVaultedInstrument(\n methodId: string,\n instrumentId: string,\n checkoutId: string,\n shouldSetAsDefaultInstrument: boolean,\n confirm: boolean,\n ): Promise {\n const paymentPayload = {\n methodId,\n paymentData: {\n formattedPayload: {\n bigpay_token: {\n token: instrumentId,\n },\n credit_card_token: {\n token: JSON.stringify({\n checkoutId,\n }),\n },\n confirm,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n },\n },\n };\n\n return this._store.dispatch(this._paymentActionCreator.submitPayment(paymentPayload));\n }\n\n private _mountComplianceSection(sellingEntity: string) {\n const complianceDiv = document.getElementById('compliance');\n\n const complianceOptions: DigitalRiverElementOptions = {\n classes: {\n base: 'DRElement',\n },\n compliance: {\n entity: sellingEntity,\n },\n };\n\n if (complianceDiv) {\n complianceDiv.innerHTML = '';\n\n const complianceElement = this._getDigitalRiverJs().createElement(\n 'compliance',\n complianceOptions,\n );\n\n complianceElement.mount('compliance');\n } else {\n const drfooter = document.createElement('div');\n\n drfooter.setAttribute('id', 'compliance');\n drfooter.style.cssText = 'min-height: 45px;';\n drfooter.classList.add('layout');\n document.body.appendChild(drfooter);\n\n const complianceElement = this._getDigitalRiverJs().createElement(\n 'compliance',\n complianceOptions,\n );\n\n complianceElement.mount('compliance');\n }\n }\n}\n","import { ScriptLoader, StylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport DigitalRiverJS, { DigitalRiverWindow } from './digitalriver';\n\nexport default class DigitalRiverScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _stylesheetLoader: StylesheetLoader,\n private _window: DigitalRiverWindow = window,\n ) {}\n\n async load(publicKey: string, locale: string): Promise {\n await Promise.all([\n this._stylesheetLoader.loadStylesheet(\n `https://js.digitalriverws.com/v1/css/DigitalRiver.css`,\n ),\n this._scriptLoader.loadScript(`https://js.digitalriverws.com/v1/DigitalRiver.js`),\n ]);\n\n if (!this._window.DigitalRiver) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return Promise.resolve(new this._window.DigitalRiver(publicKey, { locale }));\n }\n}\n","import BrowserInfo from './browser-info';\n\nexport default function getBrowserInfo(): BrowserInfo {\n return {\n color_depth: screen.colorDepth || 24,\n java_enabled: typeof navigator.javaEnabled === 'function' ? navigator.javaEnabled() : false,\n language: navigator.language || (navigator as any).userLanguage,\n screen_height: screen.height,\n screen_width: screen.width,\n time_zone_offset: new Date().getTimezoneOffset().toString(),\n };\n}\n","import { noop } from 'lodash';\n\nimport { CancellablePromise } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { getBrowserInfo } from '../../../common/browser-info';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport { PaymentStrategyType } from '../../index';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategyActionCreator from '../../payment-strategy-action-creator';\nimport {\n BraintreeGooglePayThreeDSecure,\n BraintreeSDKCreator,\n BraintreeVerifyPayload,\n} from '../braintree';\nimport PaymentStrategy from '../payment-strategy';\n\nimport {\n GooglePaymentData,\n GooglePayProviderProcessor,\n GooglePayVerifyPayload,\n PaymentMethodData,\n} from './googlepay';\nimport GooglePayPaymentInitializeOptions from './googlepay-initialize-options';\nimport GooglePayPaymentProcessor from './googlepay-payment-processor';\n\nexport default class GooglePayPaymentStrategy implements PaymentStrategy {\n private _googlePayOptions?: GooglePayPaymentInitializeOptions;\n private _walletButton?: HTMLElement;\n private _paymentMethod?: PaymentMethod;\n private _is3dsEnabled?: boolean;\n private _buttonClickEventHandler?: (event: Event) => Promise;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentStrategyActionCreator: PaymentStrategyActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _orderActionCreator: OrderActionCreator,\n private _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n private _googlePayProviderProcessor?: GooglePayProviderProcessor,\n private _braintreeSDKCreator?: BraintreeSDKCreator,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const { methodId } = options;\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n\n this._paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n this._is3dsEnabled =\n state.paymentMethods.getPaymentMethodOrThrow(\n methodId,\n ).initializationData.isThreeDSecureEnabled;\n\n this._googlePayOptions = this._getGooglePayOptions(options);\n\n this._buttonClickEventHandler = this._handleButtonClickedEvent(methodId);\n\n if (this._paymentMethod.clientToken) {\n this._braintreeSDKCreator?.initialize(this._paymentMethod.clientToken);\n }\n\n await this._googlePayPaymentProcessor.initialize(methodId);\n\n if (!this._googlePayOptions.walletButton) {\n throw new InvalidArgumentError('walletButton argument is missing');\n }\n\n const walletButton = document.getElementById(this._googlePayOptions.walletButton);\n\n if (!walletButton) {\n throw new InvalidArgumentError(\n 'Unable to create wallet, walletButton ID could not be found',\n );\n }\n\n this._walletButton = walletButton;\n this._walletButton.addEventListener('click', this._buttonClickEventHandler);\n\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n if (this._walletButton && this._buttonClickEventHandler) {\n this._walletButton.removeEventListener('click', this._buttonClickEventHandler);\n }\n\n this._buttonClickEventHandler = undefined;\n this._walletButton = undefined;\n\n return this._googlePayPaymentProcessor.deinitialize().then(() => this._store.getState());\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n if (!this._googlePayOptions) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.googlepay\" argument is not provided.',\n );\n }\n\n if (!payload.payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId } = payload.payment;\n\n if (this._paymentMethod?.initializationData.nonce !== '') {\n const state = this._store.getState();\n\n this._paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n }\n\n let payment = await this._getPayment(methodId);\n\n if (!payment.paymentData.nonce || !payment.paymentData.cardInformation) {\n const { onError, onPaymentSelect } = this._googlePayOptions;\n\n await this._displayWallet(methodId, onPaymentSelect, onError);\n payment = await this._getPayment(methodId, true);\n }\n\n if (!payment.paymentData.nonce) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n try {\n const state = await this._store.dispatch(\n this._orderActionCreator.submitOrder(\n { useStoreCredit: payload.useStoreCredit },\n options,\n ),\n );\n let verification;\n\n if (this._is3dsEnabled) {\n const {\n order: { getOrderOrThrow },\n } = state;\n\n verification = await this._verifyCard(\n methodId,\n getOrderOrThrow().orderAmount,\n payment,\n );\n }\n\n const newPayment = {\n ...payment,\n paymentData: {\n ...payment.paymentData,\n nonce: verification?.nonce || payment.paymentData.nonce,\n },\n };\n\n return await this._store.dispatch(this._paymentActionCreator.submitPayment(newPayment));\n } catch (error) {\n return this._processAdditionalAction(error);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private _processAdditionalAction(error: unknown): Promise {\n if (!this._googlePayProviderProcessor) {\n return Promise.reject(error);\n }\n\n return this._googlePayProviderProcessor.processAdditionalAction(error);\n }\n\n private async _verifyCard(\n methodId: string,\n amount: number,\n payment: PaymentMethodData,\n ): Promise {\n if (methodId === PaymentStrategyType.BRAINTREE_GOOGLE_PAY) {\n const { nonce } = payment.paymentData;\n const threeDSecure = await this._braintreeSDKCreator?.get3DS();\n\n if (!nonce || !threeDSecure) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._braintreePresent3DSChallenge(threeDSecure, amount, nonce);\n }\n }\n\n private _braintreePresent3DSChallenge(\n threeDSecure: BraintreeGooglePayThreeDSecure,\n amount: number,\n nonce: string,\n ): Promise {\n const verification = new CancellablePromise(\n threeDSecure.verifyCard({\n amount,\n nonce,\n onLookupComplete: (_data, next) => {\n next();\n },\n }),\n );\n\n return verification.promise;\n }\n\n /* tslint:disable:cyclomatic-complexity */\n private _getGooglePayOptions(\n options: PaymentInitializeOptions,\n ): GooglePayPaymentInitializeOptions {\n if (\n options.methodId === PaymentStrategyType.ADYENV2_GOOGLEPAY &&\n options.googlepayadyenv2\n ) {\n if (!this._googlePayProviderProcessor) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._googlePayProviderProcessor.initialize(options);\n\n return options.googlepayadyenv2;\n }\n\n if (\n options.methodId === PaymentStrategyType.ADYENV3_GOOGLEPAY &&\n options.googlepayadyenv3\n ) {\n if (!this._googlePayProviderProcessor) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._googlePayProviderProcessor.initialize(options);\n\n return options.googlepayadyenv3;\n }\n\n if (\n options.methodId === PaymentStrategyType.AUTHORIZENET_GOOGLE_PAY &&\n options.googlepayauthorizenet\n ) {\n return options.googlepayauthorizenet;\n }\n\n if (options.methodId === PaymentStrategyType.BNZ_GOOGLEPAY && options.googlepaybnz) {\n return options.googlepaybnz;\n }\n\n if (\n options.methodId === PaymentStrategyType.CHECKOUTCOM_GOOGLE_PAY &&\n options.googlepaycheckoutcom\n ) {\n return options.googlepaycheckoutcom;\n }\n\n if (\n options.methodId === PaymentStrategyType.CYBERSOURCEV2_GOOGLE_PAY &&\n options.googlepaycybersourcev2\n ) {\n return options.googlepaycybersourcev2;\n }\n\n if (\n options.methodId === PaymentStrategyType.ORBITAL_GOOGLE_PAY &&\n options.googlepayorbital\n ) {\n return options.googlepayorbital;\n }\n\n if (\n options.methodId === PaymentStrategyType.BRAINTREE_GOOGLE_PAY &&\n options.googlepaybraintree\n ) {\n return options.googlepaybraintree;\n }\n\n if (options.methodId === PaymentStrategyType.STRIPE_GOOGLE_PAY && options.googlepaystripe) {\n return options.googlepaystripe;\n }\n\n if (\n options.methodId === PaymentStrategyType.STRIPE_UPE_GOOGLE_PAY &&\n options.googlepaystripeupe\n ) {\n return options.googlepaystripeupe;\n }\n\n if (\n options.methodId === PaymentStrategyType.WORLDPAYACCESS_GOOGLE_PAY &&\n options.googlepayworldpayaccess\n ) {\n return options.googlepayworldpayaccess;\n }\n\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.googlepay\" argument is not provided.',\n );\n }\n /* tslint:enable:cyclomatic-complexity */\n\n private async _getPayment(\n methodId: string,\n requireRenewNonce = false,\n ): Promise {\n if (!methodId || !this._paymentMethod) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const card_information = this._paymentMethod.initializationData.card_information;\n let nonce = this._paymentMethod.initializationData.nonce;\n\n if (nonce) {\n this._paymentMethod = { ...this._paymentMethod, initializationData: { nonce: '' } };\n }\n\n if (requireRenewNonce) {\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n\n this._paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n nonce = this._paymentMethod.initializationData.nonce;\n }\n\n return {\n methodId,\n paymentData: {\n method: methodId,\n cardInformation: card_information,\n nonce: await this._encodeNonce(methodId, nonce),\n },\n };\n }\n\n private async _encodeNonce(methodId: string, nonce: string) {\n if (methodId === PaymentStrategyType.ADYENV2_GOOGLEPAY) {\n return JSON.stringify({\n type: this._paymentMethod?.method,\n googlePayToken: nonce,\n browser_info: getBrowserInfo(),\n });\n }\n\n if (methodId === PaymentStrategyType.ADYENV3_GOOGLEPAY) {\n return JSON.stringify({\n type: this._paymentMethod?.method,\n googlePayToken: nonce,\n browser_info: getBrowserInfo(),\n });\n }\n\n return nonce;\n }\n\n private async _paymentInstrumentSelected(paymentData: GooglePaymentData, methodId: string) {\n if (!methodId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n // TODO: Revisit how we deal with GooglePaymentData after receiving it from Google\n await this._googlePayPaymentProcessor.handleSuccess(paymentData);\n\n const state = this._store.getState();\n\n this._paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n return Promise.all([\n this._store.dispatch(this._checkoutActionCreator.loadCurrentCheckout()),\n this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId)),\n ]);\n }\n\n private _handleButtonClickedEvent(\n methodId: string,\n ): (event?: Event) => Promise {\n return (event?: Event) => {\n event?.preventDefault();\n\n const cart = this._store.getState().cart.getCartOrThrow();\n\n const payloadToUpdate = {\n transactionInfo: {\n currencyCode: cart.currency.code,\n totalPrice: String(cart.cartAmount),\n },\n };\n\n this._googlePayPaymentProcessor.updatePaymentDataRequest(payloadToUpdate);\n\n if (!methodId || !this._googlePayOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { onError, onPaymentSelect } = this._googlePayOptions;\n\n return this._store.dispatch(\n this._paymentStrategyActionCreator.widgetInteraction(\n async () => this._displayWallet(methodId, onPaymentSelect, onError),\n { methodId },\n ),\n { queueId: 'widgetInteraction' },\n );\n };\n }\n\n private async _displayWallet(\n methodId: string,\n onPaymentSelect = noop,\n onError = noop,\n ): Promise {\n try {\n const paymentData = await this._googlePayPaymentProcessor.displayWallet();\n\n await this._paymentInstrumentSelected(paymentData, methodId);\n\n return onPaymentSelect();\n } catch (error) {\n if (error.statusCode === 'CANCELED') {\n throw new Error('CANCELED');\n }\n\n onError(error);\n }\n }\n}\n","import { some } from 'lodash';\n\nimport { Payment, PaymentActionCreator, PaymentInitializeOptions } from '../..';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { PaymentMethodCancelledError } from '../../errors';\nimport {\n AdyenAction,\n AdyenAdditionalAction,\n AdyenAdditionalActionState,\n AdyenClient,\n AdyenError,\n AdyenV2ScriptLoader,\n} from '../adyenv2';\n\nimport { GooglePayProviderProcessor } from './googlepay';\n\nexport default class GooglePayAdyenV2PaymentProcessor implements GooglePayProviderProcessor {\n private _adyenClient?: AdyenClient;\n\n constructor(\n private _store: CheckoutStore,\n private _paymentActionCreator: PaymentActionCreator,\n private _scriptLoader: AdyenV2ScriptLoader,\n ) {}\n\n async initialize(options: PaymentInitializeOptions) {\n const state = this._store.getState();\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(options.methodId);\n const storeConfig = state.config.getStoreConfig();\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const clientSideAuthentication = {\n key: '',\n value: '',\n };\n\n if (paymentMethod.initializationData.originKey) {\n clientSideAuthentication.key = 'originKey';\n clientSideAuthentication.value = paymentMethod.initializationData.originKey;\n } else {\n clientSideAuthentication.key = 'clientKey';\n clientSideAuthentication.value = paymentMethod.initializationData.clientKey;\n }\n\n this._adyenClient = await this._scriptLoader.load({\n environment: paymentMethod.config.testMode ? 'test' : 'live',\n locale: storeConfig.storeProfile.storeLanguage,\n [clientSideAuthentication.key]: clientSideAuthentication.value,\n paymentMethodsResponse: paymentMethod.initializationData.paymentMethodsResponse,\n });\n }\n\n async processAdditionalAction(error: unknown): Promise {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'additional_action_required' })\n ) {\n return Promise.reject(error);\n }\n\n const payment = await this._handleAction(error.body.provider_data);\n\n try {\n return await this._store.dispatch(this._paymentActionCreator.submitPayment(payment));\n } catch (error) {\n return this.processAdditionalAction(error);\n }\n }\n\n private _handleAction(additionalAction: AdyenAdditionalAction): Promise {\n return new Promise((resolve, reject) => {\n const adyenAction: AdyenAction = JSON.parse(additionalAction.action);\n\n const additionalActionComponent = this._getAdyenClient().createFromAction(adyenAction, {\n onAdditionalDetails: (additionalActionState: AdyenAdditionalActionState) => {\n const paymentPayload = {\n methodId: adyenAction.paymentMethodType,\n paymentData: {\n nonce: JSON.stringify(additionalActionState.data),\n },\n };\n\n resolve(paymentPayload);\n },\n size: '05',\n onError: (error: AdyenError) => reject(error),\n });\n\n additionalActionComponent.mount('body');\n\n reject(new PaymentMethodCancelledError());\n });\n }\n\n private _getAdyenClient(): AdyenClient {\n if (!this._adyenClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._adyenClient;\n }\n}\n","import { some } from 'lodash';\n\nimport { Payment, PaymentActionCreator, PaymentInitializeOptions } from '../..';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { PaymentMethodCancelledError } from '../../errors';\nimport {\n AdyenAction,\n AdyenAdditionalAction,\n AdyenAdditionalActionState,\n AdyenClient,\n AdyenError,\n AdyenV3ScriptLoader,\n} from '../adyenv3';\n\nimport { GooglePayProviderProcessor } from './googlepay';\n\nexport default class GooglePayAdyenV3PaymentProcessor implements GooglePayProviderProcessor {\n private _adyenClient?: AdyenClient;\n\n constructor(\n private _store: CheckoutStore,\n private _paymentActionCreator: PaymentActionCreator,\n private _scriptLoader: AdyenV3ScriptLoader,\n ) {}\n\n async initialize(options: PaymentInitializeOptions) {\n const state = this._store.getState();\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(options.methodId);\n const storeConfig = state.config.getStoreConfig();\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n this._adyenClient = await this._scriptLoader.load({\n environment: paymentMethod.config.testMode ? 'test' : 'live',\n locale: storeConfig.storeProfile.storeLanguage,\n clientKey: paymentMethod.initializationData.clientKey,\n paymentMethodsResponse: paymentMethod.initializationData.paymentMethodsResponse,\n });\n }\n\n async processAdditionalAction(error: unknown): Promise {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'additional_action_required' })\n ) {\n return Promise.reject(error);\n }\n\n const payment = await this._handleAction(error.body.provider_data);\n\n try {\n return await this._store.dispatch(this._paymentActionCreator.submitPayment(payment));\n } catch (error) {\n return this.processAdditionalAction(error);\n }\n }\n\n private _handleAction(additionalAction: AdyenAdditionalAction): Promise {\n return new Promise((resolve, reject) => {\n const adyenAction: AdyenAction = JSON.parse(additionalAction.action);\n\n const additionalActionComponent = this._getAdyenClient().createFromAction(adyenAction, {\n onAdditionalDetails: (additionalActionState: AdyenAdditionalActionState) => {\n const paymentPayload = {\n methodId: adyenAction.paymentMethodType,\n paymentData: {\n nonce: JSON.stringify(additionalActionState.data),\n },\n };\n\n resolve(paymentPayload);\n },\n challengeWindowSize: '05',\n onError: (error: AdyenError) => reject(error),\n });\n\n additionalActionComponent.mount('body');\n\n reject(new PaymentMethodCancelledError());\n });\n }\n\n private _getAdyenClient(): AdyenClient {\n if (!this._adyenClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._adyenClient;\n }\n}\n","import { some } from 'lodash';\n\nimport { InternalCheckoutSelectors } from '../../../checkout';\nimport { RequestError } from '../../../common/error/errors';\nimport { PaymentInitializeOptions } from '../../payment-request-options';\n\nimport { GooglePayProviderProcessor } from './googlepay';\n\nexport default class GooglePayCheckoutcomPaymentProcessor implements GooglePayProviderProcessor {\n initialize(_options: PaymentInitializeOptions): Promise {\n return Promise.resolve();\n }\n\n async processAdditionalAction(error: unknown): Promise {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return Promise.reject(error);\n }\n\n const redirectUrl = error.body.three_ds_result.acs_url;\n\n return this._performRedirect(redirectUrl);\n }\n\n private _performRedirect(redirectUrl: string): Promise {\n return new Promise(() => {\n window.location.assign(redirectUrl);\n });\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { PaymentExecuteError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { PaymentStrategy } from '..';\nimport { PaymentActionCreator } from '../..';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentRequestOptions } from '../../payment-request-options';\n\nexport default class HummPaymentStrategy implements PaymentStrategy {\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _formPoster: FormPoster,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n ) {}\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n\n if (!payment?.methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(payment.methodId, options),\n );\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(payment.methodId);\n\n if (!paymentMethod.initializationData?.processable) {\n throw new PaymentExecuteError(\n 'payment.humm_not_processable_error',\n 'hummNotProcessableError',\n );\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({ methodId: payment.methodId }),\n );\n } catch (error) {\n if (this._isOffsiteRedirectResponse(error)) {\n return this._handleOffsiteRedirectResponse(error);\n }\n\n return Promise.reject(error);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n private _handleOffsiteRedirectResponse(response: OffsiteRedirectResponse): Promise {\n const url = response.body.additional_action_required.data.redirect_url;\n const data = response.body.provider_data;\n\n return new Promise(() => {\n this._formPoster.postForm(url, JSON.parse(data));\n });\n }\n\n private _isOffsiteRedirectResponse(response: unknown): response is OffsiteRedirectResponse {\n if (typeof response !== 'object' || response === null) {\n return false;\n }\n\n const partialResponse: Partial = response;\n\n if (!partialResponse.body) {\n return false;\n }\n\n const partialBody: Partial = partialResponse.body;\n\n return (\n partialBody.status === 'additional_action_required' &&\n !!partialBody.additional_action_required &&\n partialBody.additional_action_required.type === 'offsite_redirect' &&\n typeof partialBody.provider_data === 'string'\n );\n }\n}\n\ninterface OffsiteRedirectResponse {\n body: {\n additional_action_required: {\n type: 'offsite_redirect';\n data: {\n redirect_url: string;\n };\n };\n status: string;\n provider_data: string;\n };\n}\n","export const supportedCountries = [\n 'AT',\n 'BE',\n 'CA',\n 'CH',\n 'CZ',\n 'DE',\n 'DK',\n 'ES',\n 'FI',\n 'FR',\n 'GB',\n 'GR',\n 'IE',\n 'IT',\n 'NL',\n 'NO',\n 'NZ',\n 'PL',\n 'PT',\n 'SE',\n];\nexport const supportedCountriesRequiringStates = ['AU'];\n","import { includes } from 'lodash';\n\nimport { PaymentMethodInvalidError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Address } from '../../../address';\nimport { BillingAddress } from '../../../billing';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport { PaymentMethodCancelledError } from '../../errors';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { supportedCountries, supportedCountriesRequiringStates } from '../klarnav2';\nimport PaymentStrategy from '../payment-strategy';\n\nimport KlarnaCredit, {\n KlarnaAddress,\n KlarnaLoadResponse,\n KlarnaUpdateSessionParams,\n} from './klarna-credit';\nimport KlarnaScriptLoader from './klarna-script-loader';\n\nexport default class KlarnaPaymentStrategy implements PaymentStrategy {\n private _klarnaCredit?: KlarnaCredit;\n private _unsubscribe?: () => void;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n private _klarnaScriptLoader: KlarnaScriptLoader,\n ) {}\n\n initialize(options: PaymentInitializeOptions): Promise {\n return this._klarnaScriptLoader\n .load()\n .then((klarnaCredit) => {\n this._klarnaCredit = klarnaCredit;\n })\n .then(() => {\n this._unsubscribe = this._store.subscribe(\n (state) => {\n if (\n state.paymentStrategies.isInitialized({\n methodId: options.methodId,\n gatewayId: options.gatewayId,\n })\n ) {\n this._loadWidget(options);\n }\n },\n (state) => {\n const checkout = state.checkout.getCheckout();\n\n return checkout && checkout.outstandingBalance;\n },\n (state) => {\n const checkout = state.checkout.getCheckout();\n\n return checkout && checkout.coupons;\n },\n );\n\n return this._loadWidget(options);\n })\n .then(() => this._store.getState());\n }\n\n deinitialize(): Promise {\n if (this._unsubscribe) {\n this._unsubscribe();\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n if (!payload.payment) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"payload.payment\" argument is not provided.',\n );\n }\n\n const {\n payment: { paymentData, ...paymentPayload },\n } = payload;\n\n return this._authorize()\n .then(({ authorization_token: authorizationToken }) =>\n this._store.dispatch(\n this._remoteCheckoutActionCreator.initializePayment(paymentPayload.methodId, {\n authorizationToken,\n }),\n ),\n )\n .then(() =>\n this._store.dispatch(\n this._orderActionCreator.submitOrder(\n {\n ...payload,\n payment: paymentPayload,\n useStoreCredit: payload.useStoreCredit,\n },\n options,\n ),\n ),\n );\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private _loadWidget(options: PaymentInitializeOptions): Promise {\n if (!options.klarna) {\n throw new InvalidArgumentError(\n 'Unable to load widget because \"options.klarna\" argument is not provided.',\n );\n }\n\n const {\n methodId,\n klarna: { container, onLoad },\n } = options;\n\n return this._store\n .dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId))\n .then(\n (state) =>\n new Promise((resolve) => {\n const paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (!this._klarnaCredit || !paymentMethod.clientToken) {\n throw new NotInitializedError(\n NotInitializedErrorType.PaymentNotInitialized,\n );\n }\n\n this._klarnaCredit.init({ client_token: paymentMethod.clientToken });\n\n this._klarnaCredit.load({ container }, (response) => {\n if (onLoad) {\n onLoad(response);\n }\n\n resolve(response);\n });\n }),\n );\n }\n\n private _getUpdateSessionData(\n billingAddress: BillingAddress,\n shippingAddress?: Address,\n ): KlarnaUpdateSessionParams {\n if (\n !includes(\n [...supportedCountries, ...supportedCountriesRequiringStates],\n billingAddress.countryCode,\n )\n ) {\n return {};\n }\n\n const data: KlarnaUpdateSessionParams = {\n billing_address: this._mapToKlarnaAddress(billingAddress, billingAddress.email),\n };\n\n if (shippingAddress) {\n data.shipping_address = this._mapToKlarnaAddress(shippingAddress, billingAddress.email);\n }\n\n return data;\n }\n\n private _needsStateCode(countryCode: string) {\n return includes(supportedCountriesRequiringStates, countryCode);\n }\n\n private _mapToKlarnaAddress(address: Address, email?: string): KlarnaAddress {\n const klarnaAddress: KlarnaAddress = {\n street_address: address.address1,\n city: address.city,\n country: address.countryCode,\n given_name: address.firstName,\n family_name: address.lastName,\n postal_code: address.postalCode,\n region: this._needsStateCode(address.countryCode)\n ? address.stateOrProvinceCode\n : address.stateOrProvince,\n email,\n };\n\n if (address.address2) {\n klarnaAddress.street_address2 = address.address2;\n }\n\n if (address.phone) {\n klarnaAddress.phone = address.phone;\n }\n\n return klarnaAddress;\n }\n\n private _authorize(): Promise {\n return new Promise((resolve, reject) => {\n const billingAddress = this._store.getState().billingAddress.getBillingAddress();\n const shippingAddress = this._store.getState().shippingAddress.getShippingAddress();\n\n if (!billingAddress) {\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n\n if (!this._klarnaCredit) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const updateSessionData = this._getUpdateSessionData(billingAddress, shippingAddress);\n\n this._klarnaCredit.authorize(updateSessionData, (res) => {\n if (res.approved) {\n return resolve(res);\n }\n\n if (res.show_form) {\n return reject(new PaymentMethodCancelledError());\n }\n\n reject(new PaymentMethodInvalidError());\n });\n });\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport KlarnaCredit from './klarna-credit';\nimport KlarnaWindow from './klarna-window';\n\nconst SDK_URL = '//credit.klarnacdn.net/lib/v1/api.js';\n\nexport default class KlarnaScriptLoader {\n constructor(private _scriptLoader: ScriptLoader) {}\n\n load(): Promise {\n return this._scriptLoader\n .loadScript(SDK_URL)\n .then(() => (window as unknown as KlarnaWindow).Klarna.Credit);\n }\n}\n","import { includes } from 'lodash';\n\nimport { PaymentMethodInvalidError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Address } from '../../../address';\nimport { BillingAddress } from '../../../billing';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport { PaymentMethodCancelledError } from '../../errors';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport KlarnaPayments, {\n KlarnaAddress,\n KlarnaAuthorizationResponse,\n KlarnaLoadResponse,\n KlarnaUpdateSessionParams,\n} from './klarna-payments';\nimport {\n supportedCountries,\n supportedCountriesRequiringStates,\n} from './klarna-supported-countries';\nimport KlarnaV2ScriptLoader from './klarnav2-script-loader';\nimport KlarnaV2TokenUpdater from './klarnav2-token-updater';\n\nexport default class KlarnaV2PaymentStrategy implements PaymentStrategy {\n private _klarnaPayments?: KlarnaPayments;\n private _unsubscribe?: () => void;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n private _klarnav2ScriptLoader: KlarnaV2ScriptLoader,\n private _klarnav2TokenUpdater: KlarnaV2TokenUpdater,\n ) {}\n\n initialize(options: PaymentInitializeOptions): Promise {\n return this._klarnav2ScriptLoader\n .load()\n .then((klarnaPayments) => {\n this._klarnaPayments = klarnaPayments;\n })\n .then(() => {\n this._unsubscribe = this._store.subscribe(\n (state) => {\n if (\n state.paymentStrategies.isInitialized({\n methodId: options.methodId,\n gatewayId: options.gatewayId,\n })\n ) {\n this._loadPaymentsWidget(options);\n }\n },\n (state) => {\n const checkout = state.checkout.getCheckout();\n\n return checkout && checkout.outstandingBalance;\n },\n (state) => {\n const checkout = state.checkout.getCheckout();\n\n return checkout && checkout.coupons;\n },\n );\n\n return this._loadPaymentsWidget(options);\n })\n .then(() => this._store.getState());\n }\n\n deinitialize(): Promise {\n if (this._unsubscribe) {\n this._unsubscribe();\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n if (!payload.payment) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"payload.payment\" argument is not provided.',\n );\n }\n\n const {\n payment: { paymentData, ...paymentPayload },\n } = payload;\n const { gatewayId } = paymentPayload;\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"payload.payment.gatewayId\" argument is not provided.',\n );\n }\n\n return this._authorize(paymentPayload.methodId)\n .then(({ authorization_token: authorizationToken }) =>\n this._store.dispatch(\n this._remoteCheckoutActionCreator.initializePayment(gatewayId, {\n authorizationToken,\n }),\n ),\n )\n .then(() =>\n this._store.dispatch(\n this._orderActionCreator.submitOrder(\n {\n ...payload,\n payment: paymentPayload,\n useStoreCredit: payload.useStoreCredit,\n },\n options,\n ),\n ),\n );\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private async _loadPaymentsWidget(\n options: PaymentInitializeOptions,\n ): Promise {\n if (!options.klarnav2) {\n throw new InvalidArgumentError(\n 'Unable to load widget because \"options.klarnav2\" argument is not provided.',\n );\n }\n\n const {\n methodId,\n gatewayId,\n klarnav2: { container, onLoad },\n } = options;\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"payload.payment.gatewayId\" argument is not provided.',\n );\n }\n\n const state = this._store.getState();\n const cartId = state.cart.getCartOrThrow().id;\n const params = { params: cartId };\n\n await this._klarnav2TokenUpdater.updateClientToken(gatewayId, { params }).catch(() => {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n });\n\n return new Promise((resolve) => {\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n if (!this._klarnaPayments || !paymentMethod.clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._klarnaPayments.init({ client_token: paymentMethod.clientToken });\n this._klarnaPayments.load(\n { container, payment_method_category: paymentMethod.id },\n (response) => {\n if (onLoad) {\n onLoad(response);\n }\n\n resolve(response);\n },\n );\n });\n }\n\n private _getUpdateSessionData(\n billingAddress: BillingAddress,\n shippingAddress?: Address,\n ): KlarnaUpdateSessionParams {\n if (\n !includes(\n [...supportedCountries, ...supportedCountriesRequiringStates],\n billingAddress.countryCode,\n )\n ) {\n return {};\n }\n\n const data: KlarnaUpdateSessionParams = {\n billing_address: this._mapToKlarnaAddress(billingAddress, billingAddress.email),\n };\n\n if (shippingAddress) {\n data.shipping_address = this._mapToKlarnaAddress(shippingAddress, billingAddress.email);\n }\n\n return data;\n }\n\n private _needsStateCode(countryCode: string) {\n return includes(supportedCountriesRequiringStates, countryCode);\n }\n\n private _mapToKlarnaAddress(address: Address, email?: string): KlarnaAddress {\n const klarnaAddress: KlarnaAddress = {\n street_address: address.address1,\n city: address.city,\n country: address.countryCode,\n given_name: address.firstName,\n family_name: address.lastName,\n postal_code: address.postalCode,\n region: this._needsStateCode(address.countryCode)\n ? address.stateOrProvinceCode\n : address.stateOrProvince,\n email,\n };\n\n if (address.address2) {\n klarnaAddress.street_address2 = address.address2;\n }\n\n if (address.phone) {\n klarnaAddress.phone = address.phone;\n }\n\n return klarnaAddress;\n }\n\n private _authorize(methodId: string): Promise {\n return new Promise((resolve, reject) => {\n const billingAddress = this._store.getState().billingAddress.getBillingAddress();\n const shippingAddress = this._store.getState().shippingAddress.getShippingAddress();\n\n if (!billingAddress) {\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n\n const updateSessionData = this._getUpdateSessionData(billingAddress, shippingAddress);\n\n if (!this._klarnaPayments) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._klarnaPayments.authorize(\n { payment_method_category: methodId },\n updateSessionData,\n (res) => {\n if (res.approved) {\n return resolve(res);\n }\n\n if (res.show_form) {\n return reject(new PaymentMethodCancelledError());\n }\n\n reject(new PaymentMethodInvalidError());\n },\n );\n });\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport KlarnaPayments from './klarna-payments';\nimport KlarnaV2Window from './klarnav2-window';\n\nconst SDK_URL = 'https://x.klarnacdn.net/kp/lib/v1/api.js';\n\nexport default class KlarnaV2ScriptLoader {\n constructor(private _scriptLoader: ScriptLoader) {}\n\n load(): Promise {\n return this._scriptLoader\n .loadScript(SDK_URL)\n .then(() => (window as unknown as KlarnaV2Window).Klarna.Payments);\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../../../common/http-request';\nimport PaymentMethod from '../../payment-method';\n\nexport default class KlarnaV2TokenUpdater {\n constructor(private _requestSender: RequestSender) {}\n\n updateClientToken(\n gatewayId: string,\n { timeout, params }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/payments/${gatewayId}`;\n\n return this._requestSender.get(url, {\n timeout,\n headers: {\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n params,\n });\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../../../common/error/errors';\nimport { bindDecorator as bind } from '../../../common/utility';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport formatLocale from './format-locale';\nimport getCallbackUrl from './get-callback-url';\nimport { Masterpass, MasterpassCheckoutOptions } from './masterpass';\nimport MasterpassScriptLoader from './masterpass-script-loader';\n\nexport default class MasterpassPaymentStrategy implements PaymentStrategy {\n private _masterpassClient?: Masterpass;\n private _paymentMethod?: PaymentMethod;\n private _walletButton?: HTMLElement;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _masterpassScriptLoader: MasterpassScriptLoader,\n private _locale: string,\n ) {}\n\n initialize(options: PaymentInitializeOptions): Promise {\n const { methodId } = options;\n\n this._paymentMethod = this._store.getState().paymentMethods.getPaymentMethod(methodId);\n\n if (!this._paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const masterpassScriptLoaderParams = {\n useMasterpassSrc: this._paymentMethod.initializationData.isMasterpassSrcEnabled,\n language: formatLocale(this._locale),\n testMode: this._paymentMethod.config.testMode,\n checkoutId: this._paymentMethod.initializationData.checkoutId,\n };\n\n return this._masterpassScriptLoader\n .load(masterpassScriptLoaderParams)\n .then((masterpass) => {\n this._masterpassClient = masterpass;\n\n if (!options.masterpass) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.masterpass\" argument is not provided.',\n );\n }\n\n const walletButton =\n options.masterpass.walletButton &&\n document.getElementById(options.masterpass.walletButton);\n\n if (walletButton) {\n this._walletButton = walletButton;\n this._walletButton.addEventListener('click', this._handleWalletButtonClick);\n }\n\n return this._store.getState();\n });\n }\n\n deinitialize(): Promise {\n this._paymentMethod = undefined;\n\n if (this._walletButton) {\n this._walletButton.removeEventListener('click', this._handleWalletButtonClick);\n }\n\n this._walletButton = undefined;\n this._masterpassClient = undefined;\n\n return Promise.resolve(this._store.getState());\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment } = payload;\n const order = { useStoreCredit: payload.useStoreCredit };\n\n if (!payment) {\n throw new InvalidArgumentError(\n 'Unable to submit payment because \"payload.payment\" argument is not provided.',\n );\n }\n\n if (\n !this._paymentMethod ||\n !this._paymentMethod.initializationData ||\n !this._paymentMethod.initializationData.gateway\n ) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n // TODO: Refactor the API endpoint to return nonce in the right place.\n const paymentData = this._paymentMethod.initializationData.paymentData;\n\n // TODO: Redirect to Masterpass if nonce has not been generated yet. And then finalise the order when the shopper is redirected back to the checkout page.\n if (!paymentData) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"paymentMethod.initializationData.paymentData\" argument is not provided.',\n );\n }\n\n return this._store\n .dispatch(this._orderActionCreator.submitOrder(order, options))\n .then(() =>\n this._store.dispatch(\n this._paymentActionCreator.submitPayment({ ...payment, paymentData }),\n ),\n );\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private _createMasterpassPayload(): MasterpassCheckoutOptions {\n const state = this._store.getState();\n const checkout = state.checkout.getCheckout();\n const storeConfig = state.config.getStoreConfig();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n if (!this._paymentMethod || !this._paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n return {\n checkoutId: this._paymentMethod.initializationData.checkoutId,\n allowedCardTypes: this._paymentMethod.initializationData.allowedCardTypes,\n amount: checkout.subtotal.toFixed(2),\n currency: storeConfig.currency.code,\n cartId: checkout.cart.id,\n callbackUrl: getCallbackUrl('checkout'),\n };\n }\n\n @bind\n private _handleWalletButtonClick(event: Event) {\n event.preventDefault();\n\n if (!this._masterpassClient) {\n return;\n }\n\n const payload = this._createMasterpassPayload();\n\n this._masterpassClient.checkout(payload);\n }\n}\n","import { each, some } from 'lodash';\n\nimport { PaymentActionCreator } from '../..';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { getBrowserInfo } from '../../../common/browser-info';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { HostedForm, HostedFormFactory, HostedFormOptions } from '../../../hosted-form';\nimport { OrderActionCreator, OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport isVaultedInstrument from '../../is-vaulted-instrument';\nimport { HostedInstrument } from '../../payment';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { MollieClient, MollieElement } from './mollie';\nimport MolliePaymentInitializeOptions from './mollie-initialize-options';\nimport MollieScriptLoader from './mollie-script-loader';\n\nexport enum MolliePaymentMethodType {\n creditcard = 'credit_card',\n}\n\nconst methodsNotAllowedWhenDigitalOrder = ['klarnapaylater', 'klarnasliceit'];\n\nexport default class MolliePaymentStrategy implements PaymentStrategy {\n private _initializeOptions?: MolliePaymentInitializeOptions;\n private _mollieClient?: MollieClient;\n private _cardHolderElement?: MollieElement;\n private _cardNumberElement?: MollieElement;\n private _verificationCodeElement?: MollieElement;\n private _expiryDateElement?: MollieElement;\n private _locale?: string;\n\n private _hostedForm?: HostedForm;\n\n private _unsubscribe?: () => void;\n\n constructor(\n private _hostedFormFactory: HostedFormFactory,\n private _store: CheckoutStore,\n private _mollieScriptLoader: MollieScriptLoader,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const { mollie, methodId, gatewayId } = options;\n\n if (!mollie) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.mollie\" argument is not provided.',\n );\n }\n\n if (!methodId || !gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"methodId\" and/or \"gatewayId\" argument is not provided.',\n );\n }\n\n const controllers = document.querySelectorAll('.mollie-components-controller');\n\n each(controllers, (controller) => controller.remove());\n\n const state = this._store.getState();\n const storeConfig = state.config.getStoreConfig();\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n this._initializeOptions = mollie;\n\n const paymentMethods = state.paymentMethods;\n const paymentMethod = paymentMethods.getPaymentMethodOrThrow(methodId, gatewayId);\n const {\n config: { merchantId, testMode },\n } = paymentMethod;\n const { locale } = paymentMethod.initializationData;\n\n this._locale = locale;\n\n if (!merchantId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"merchantId\" argument is not provided.',\n );\n }\n\n if (\n this.isCreditCard(methodId) &&\n mollie.form &&\n this.shouldShowTSVHostedForm(methodId, gatewayId)\n ) {\n this._hostedForm = await this._mountCardVerificationfields(mollie.form);\n } else if (this.isCreditCard(methodId)) {\n this._mollieClient = await this._loadMollieJs(\n merchantId,\n storeConfig.storeProfile.storeLanguage,\n testMode,\n );\n this._mountElements();\n }\n\n this._unsubscribe = this._store.subscribe(\n async (state) => {\n if (\n state.paymentStrategies.isInitialized({\n methodId: options.methodId,\n gatewayId: options.gatewayId,\n })\n ) {\n const element = document.getElementById(`${gatewayId}-${methodId}-paragraph`);\n\n if (element) {\n element.remove();\n }\n\n mollie.disableButton(false);\n\n this._loadPaymentMethodsAllowed(mollie, methodId, gatewayId, state);\n }\n },\n (state) => {\n const checkout = state.checkout.getCheckout();\n\n return checkout && checkout.outstandingBalance;\n },\n (state) => {\n const checkout = state.checkout.getCheckout();\n\n return checkout && checkout.coupons;\n },\n );\n\n this._loadPaymentMethodsAllowed(mollie, methodId, gatewayId, state);\n\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment?.paymentData;\n\n if (!payment || !payment.gatewayId || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment', 'gatewayId', 'paymentData']);\n }\n\n try {\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n if (isVaultedInstrument(paymentData)) {\n return await this.executeWithVaulted(payment);\n }\n\n if (this.isCreditCard(payment.methodId)) {\n return await this.executeWithCC(payment);\n }\n\n return await this.executeWithAPM(payment);\n } catch (error) {\n return this._processAdditionalAction(error);\n }\n }\n\n finalize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(options?: PaymentRequestOptions): Promise {\n if (this._unsubscribe) {\n this._unsubscribe();\n }\n\n if (this._hostedForm) {\n this._hostedForm.detach();\n }\n\n if (options && options.methodId && options.gatewayId && !this._hostedForm) {\n const element = document.getElementById(`${options.gatewayId}-${options.methodId}`);\n\n if (element) {\n element.remove();\n }\n } else if (options && options.methodId && this.isCreditCard(options.methodId)) {\n if (\n this._cardHolderElement &&\n this._cardNumberElement &&\n this._verificationCodeElement &&\n this._expiryDateElement\n ) {\n this._cardHolderElement.unmount();\n this._cardHolderElement = undefined;\n\n this._cardNumberElement.unmount();\n this._cardNumberElement = undefined;\n\n this._verificationCodeElement.unmount();\n this._verificationCodeElement = undefined;\n\n this._expiryDateElement.unmount();\n this._expiryDateElement = undefined;\n }\n }\n\n this._mollieClient = undefined;\n\n return Promise.resolve(this._store.getState());\n }\n\n protected async executeWithCC(\n payment: OrderPaymentRequestBody,\n ): Promise {\n const paymentData = payment.paymentData;\n const shouldSaveInstrument = (paymentData as HostedInstrument).shouldSaveInstrument;\n const shouldSetAsDefaultInstrument = (paymentData as HostedInstrument)\n .shouldSetAsDefaultInstrument;\n\n const { token, error } = await this._getMollieClient().createToken();\n\n if (error) {\n return Promise.reject(error);\n }\n\n const formattedPayload = {\n credit_card_token: {\n token,\n },\n vault_payment_instrument: shouldSaveInstrument,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n browser_info: getBrowserInfo(),\n shopper_locale: this._getShopperLocale(),\n };\n\n return this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n ...payment,\n paymentData: {\n formattedPayload,\n },\n }),\n );\n }\n\n protected async executeWithVaulted(\n payment: OrderPaymentRequestBody,\n ): Promise {\n if (this._isHostedPaymentFormEnabled(payment.methodId, payment.gatewayId)) {\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n await form.validate();\n await form.submit(payment);\n\n return this._store.dispatch(this._orderActionCreator.loadCurrentOrder());\n }\n\n return this._store.dispatch(this._paymentActionCreator.submitPayment(payment));\n }\n\n protected async executeWithAPM(\n payment: OrderPaymentRequestBody,\n ): Promise {\n const paymentData = payment.paymentData;\n const issuer = paymentData && 'issuer' in paymentData ? paymentData.issuer : '';\n\n return this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n ...payment,\n paymentData: {\n ...paymentData,\n formattedPayload: {\n issuer,\n shopper_locale: this._getShopperLocale(),\n },\n },\n }),\n );\n }\n\n private isCreditCard(methodId: string): boolean {\n return methodId === MolliePaymentMethodType.creditcard;\n }\n\n private shouldShowTSVHostedForm(methodId: string, gatewayId: string): boolean {\n return (\n this._isHostedPaymentFormEnabled(methodId, gatewayId) && this._isHostedFieldAvailable()\n );\n }\n\n private _mountCardVerificationfields(formOptions: HostedFormOptions): Promise {\n /* eslint-disable */\n return new Promise(async (resolve , reject) => {\n try {\n const { config } = this._store.getState();\n const bigpayBaseUrl = config.getStoreConfig()?.paymentSettings.bigpayBaseUrl;\n\n if (!bigpayBaseUrl) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const form = this._hostedFormFactory.create(bigpayBaseUrl, formOptions);\n\n await form.attach();\n\n resolve(form);\n } catch (error) {\n reject(error);\n }\n });\n }\n\n private _isHostedPaymentFormEnabled(methodId: string, gatewayId?: string): boolean {\n const { paymentMethods: { getPaymentMethodOrThrow } } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(methodId, gatewayId);\n\n return paymentMethod.config.isHostedFormEnabled === true;\n }\n\n private _isHostedFieldAvailable(): boolean {\n const options = this._getInitializeOptions();\n\n return !!options.form?.fields;\n }\n\n private _processAdditionalAction(error: any): Promise {\n if (!(error instanceof RequestError) || !some(error.body.errors, {code: 'additional_action_required'})) {\n return Promise.reject(error);\n }\n const { additional_action_required: { data : { redirect_url } } } = error.body;\n\n return new Promise(() => window.location.replace(redirect_url));\n }\n\n private _getInitializeOptions(): MolliePaymentInitializeOptions {\n if (!this._initializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._initializeOptions;\n }\n\n private _loadMollieJs(merchantId: string, locale: string, testmode = false): Promise {\n if (this._mollieClient) {\n return Promise.resolve(this._mollieClient);\n }\n\n return this._mollieScriptLoader\n .load(merchantId, locale, testmode);\n }\n\n private _getMollieClient(): MollieClient {\n if (!this._mollieClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._mollieClient;\n }\n\n private _getShopperLocale(): string {\n if (!this._locale) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._locale;\n }\n\n /**\n * ContainerId is use in Mollie for determined either its showing or not the\n * container, because when Mollie has Vaulted Instruments it gets hide,\n * and shows an error because can't mount Provider Components\n *\n * We had to add a settimeout because Mollie sets de tab index after mounting\n * each component, but without a setTimeOut Mollie is not able to find the\n * components as they are hidden so we need to wait until they are shown\n */\n private _mountElements() {\n const { containerId, cardNumberId, cardCvcId, cardExpiryId, cardHolderId, styles } = this._getInitializeOptions();\n let container: HTMLElement | null;\n\n if (containerId) {\n container = document.getElementById(containerId);\n }\n\n setTimeout(() => {\n if (!containerId || container?.style.display !== 'none') {\n const mollieClient = this._getMollieClient();\n\n this._cardHolderElement = mollieClient.createComponent('cardHolder', { styles });\n this._cardHolderElement.mount(`#${cardHolderId}`);\n\n this._cardNumberElement = mollieClient.createComponent('cardNumber', { styles });\n this._cardNumberElement.mount(`#${cardNumberId}`);\n\n this._verificationCodeElement = mollieClient.createComponent('verificationCode', { styles });\n this._verificationCodeElement.mount(`#${cardCvcId}`);\n\n this._expiryDateElement = mollieClient.createComponent('expiryDate', { styles });\n this._expiryDateElement.mount(`#${cardExpiryId}`);\n }\n }, 0);\n }\n\n private _loadPaymentMethodsAllowed(mollie: MolliePaymentInitializeOptions, methodId: string, gatewayId: string, state: InternalCheckoutSelectors){\n if (methodsNotAllowedWhenDigitalOrder.includes(methodId)) {\n const cart = state.cart.getCartOrThrow();\n const cartDigitalItems = cart.lineItems.digitalItems;\n\n if (cartDigitalItems && cartDigitalItems.length > 0) {\n const { containerId } = this._getInitializeOptions();\n\n if (containerId) {\n const container = document.getElementById(containerId);\n\n if (container) {\n const paragraph = document.createElement('p') ;\n paragraph.setAttribute(\"id\",`${gatewayId}-${methodId}-paragraph`)\n\n if (mollie.unsupportedMethodMessage) {\n paragraph.innerText = mollie.unsupportedMethodMessage;\n container.appendChild(paragraph);\n mollie.disableButton(true);\n }\n }\n }\n }\n }\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { MollieClient, MollieHostWindow } from './mollie';\n\nexport default class MollieScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, private _window: Window = window) {}\n\n _isMollieWindow(window: Window): window is MollieHostWindow {\n const mollieWindow: MollieHostWindow = window as MollieHostWindow;\n\n return !!mollieWindow.Mollie;\n }\n\n async load(merchantId: string, locale: string, testmode: boolean): Promise {\n await this._scriptLoader.loadScript('https://js.mollie.com/v1/mollie.js');\n\n if (!this._isMollieWindow(this._window)) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.Mollie(merchantId, {\n locale,\n testmode,\n });\n }\n}\n","import { isEmpty, map, omitBy } from 'lodash';\n\nimport { isHostedInstrumentLike } from '../../';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { HostedForm, HostedFormFactory, HostedFormOptions } from '../../../hosted-form';\nimport { OrderActionCreator, OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { StoreCreditActionCreator } from '../../../store-credit';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport isVaultedInstrument from '../../is-vaulted-instrument';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport MonerisStylingProps, {\n MoneriesHostedFieldsQueryParams,\n MonerisInitializationData,\n MonerisResponseData,\n} from './moneris';\nimport MonerisPaymentInitializeOptions from './moneris-payment-initialize-options';\n\nconst IFRAME_NAME = 'moneris-payment-iframe';\nconst RESPONSE_SUCCESS_CODE = '001';\n\nexport default class MonerisPaymentStrategy implements PaymentStrategy {\n private _iframe?: HTMLIFrameElement;\n private _initializeOptions?: MonerisPaymentInitializeOptions;\n private _windowEventListener?: (response: MessageEvent) => void;\n\n private _hostedForm?: HostedForm;\n\n constructor(\n private _hostedFormFactory: HostedFormFactory,\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _storeCreditActionCreator: StoreCreditActionCreator,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const state = this._store.getState();\n\n const { moneris: monerisOptions, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"methodId\" argument is not provided.',\n );\n }\n\n if (!monerisOptions) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.moneris\" argument is not provided.',\n );\n }\n\n this._initializeOptions = monerisOptions;\n\n const { config, initializationData } =\n state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n if (!initializationData?.profileId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (monerisOptions.form && this._shouldShowTSVHostedForm(methodId)) {\n this._hostedForm = await this._mountCardVerificationfields(monerisOptions.form);\n }\n\n if (!this._iframe) {\n this._iframe = this._createIframe(\n monerisOptions.containerId,\n initializationData,\n !!config.testMode,\n );\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentInitializeOptions,\n ): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { isStoreCreditApplied: useStoreCredit } = this._store\n .getState()\n .checkout.getCheckoutOrThrow();\n\n if (useStoreCredit !== undefined) {\n await this._store.dispatch(\n this._storeCreditActionCreator.applyStoreCredit(useStoreCredit),\n );\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n if (payment.paymentData && isVaultedInstrument(payment.paymentData)) {\n return this._executeWithVaulted(payment);\n }\n\n return this._executeWithCC(payment);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n if (this._hostedForm) {\n this._hostedForm.detach();\n }\n\n if (this._windowEventListener) {\n window.removeEventListener('message', this._windowEventListener);\n this._windowEventListener = undefined;\n }\n\n if (this._iframe && this._iframe.parentNode) {\n this._iframe.parentNode.removeChild(this._iframe);\n this._iframe = undefined;\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n private async _executeWithCC(\n payment: OrderPaymentRequestBody,\n ): Promise {\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(payment.methodId);\n\n const testMode = paymentMethod.config.testMode;\n const paymentData = payment.paymentData || {};\n const instrumentSettings = isHostedInstrumentLike(paymentData)\n ? paymentData\n : { shouldSaveInstrument: false, shouldSetAsDefaultInstrument: false };\n\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = instrumentSettings;\n\n const nonce = await new Promise((resolve, reject) => {\n if (!this._iframe) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const frameref = this._iframe.contentWindow;\n\n frameref?.postMessage('tokenize', this._monerisURL(!!testMode));\n\n this._windowEventListener = (response: MessageEvent) => {\n if (typeof response.data !== 'string') {\n return;\n }\n\n try {\n resolve(this._handleMonerisResponse(response));\n } catch (error) {\n reject(error);\n }\n };\n\n window.addEventListener('message', this._windowEventListener);\n });\n\n if (nonce !== undefined) {\n return this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n methodId: payment.methodId,\n paymentData: { nonce, shouldSaveInstrument, shouldSetAsDefaultInstrument },\n }),\n );\n }\n\n return this._store.getState();\n }\n\n private async _executeWithVaulted(\n payment: OrderPaymentRequestBody,\n ): Promise {\n if (this._hostedForm) {\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n await form.validate();\n await form.submit(payment);\n\n return this._store.dispatch(this._orderActionCreator.loadCurrentOrder());\n }\n\n return this._store.dispatch(this._paymentActionCreator.submitPayment(payment));\n }\n\n private _shouldShowTSVHostedForm(methodId: string): boolean {\n return this._isHostedPaymentFormEnabled(methodId) && this._isHostedFieldAvailable();\n }\n\n private _isHostedPaymentFormEnabled(methodId: string): boolean {\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(methodId);\n\n return Boolean(paymentMethod.config.isHostedFormEnabled);\n }\n\n private _isHostedFieldAvailable(): boolean {\n const options = this._getInitializeOptions();\n const definedFields = omitBy(options.form?.fields, isEmpty);\n\n return !isEmpty(definedFields);\n }\n\n private _getInitializeOptions(): MonerisPaymentInitializeOptions {\n if (!this._initializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._initializeOptions;\n }\n\n private async _mountCardVerificationfields(\n formOptions: HostedFormOptions,\n ): Promise {\n const { config } = this._store.getState();\n const bigpayBaseUrl = config.getStoreConfig()?.paymentSettings.bigpayBaseUrl;\n\n if (!bigpayBaseUrl) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const form = this._hostedFormFactory.create(bigpayBaseUrl, formOptions);\n\n await form.attach();\n\n return form;\n }\n\n private _createIframe(\n containerId: string,\n initializationData: MonerisInitializationData,\n testMode: boolean,\n style?: MonerisStylingProps,\n ): HTMLIFrameElement {\n const container = document.getElementById(containerId);\n\n if (!container) {\n throw new InvalidArgumentError('Unable to create iframe without valid container ID.');\n }\n\n const iframe = document.createElement('iframe');\n const monerisQueryParams: MoneriesHostedFieldsQueryParams = {\n id: initializationData.profileId,\n pmmsg: true,\n display_labels: 1,\n enable_exp: 1,\n enable_cvd: 1,\n css_body:\n style?.cssBody ||\n 'font-family: Arial, Helvetica,sans-serif;background: transparent;',\n css_textbox:\n style?.cssTextbox ||\n 'border-radius:4px;border: 2px solid rgb(00,00,00);width: 100%;font-weight: 600;padding: 8px 8px;outline: 0;',\n css_textbox_pan: style?.cssTextboxCardNumber || 'width: 240px;',\n css_textbox_exp:\n style?.cssTextboxExpiryDate || 'margin-bottom: 0;width: calc(30% - 12px);',\n css_textbox_cvd: style?.cssTextboxCVV || 'margin-bottom: 0;width: calc(30% - 12px);',\n css_input_label:\n style?.cssInputLabel ||\n '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;',\n pan_label: initializationData.creditCardLabel || 'Credit Card Number',\n exp_label: initializationData.expiryDateLabel || 'Expiration',\n cvd_label: initializationData.cvdLabel || 'CVD',\n };\n\n const queryString = map(monerisQueryParams, (value, key) => `${key}=${value}`).join('&');\n\n iframe.width = '100%';\n iframe.height = '100%';\n iframe.name = IFRAME_NAME;\n iframe.id = IFRAME_NAME;\n iframe.style.border = 'none';\n iframe.src = `${this._monerisURL(testMode)}?${queryString}`;\n\n container.appendChild(iframe);\n\n return iframe;\n }\n\n private _handleMonerisResponse(response: MessageEvent): string {\n const monerisResponse: MonerisResponseData = JSON.parse(response.data);\n\n if (monerisResponse.responseCode[0] !== RESPONSE_SUCCESS_CODE) {\n throw new Error(monerisResponse.errorMessage);\n }\n\n return monerisResponse.dataKey;\n }\n\n private _monerisURL(testMode: boolean): string {\n return `https://${testMode ? 'esqa' : 'www3'}.moneris.com/HPPtoken/index.php`;\n }\n}\n","import PaymentMethod from '../../payment-method';\n\nimport { OpyWidgetConfig } from './opy-library';\n\nexport enum ActionTypes {\n FORM_POST = 'FormPost',\n WAIT_FOR_CUSTOMER = 'WaitForCustomer',\n}\n\ninterface FormPost {\n type: ActionTypes.FORM_POST;\n formPost: {\n formPostUrl: string;\n formFields: [\n {\n fieldName: string;\n fieldValue: string;\n },\n ];\n };\n}\n\ninterface WaitForCustomer {\n type: ActionTypes.WAIT_FOR_CUSTOMER;\n}\n\nexport interface OpyPaymentMethod extends PaymentMethod {\n initializationData: {\n nextAction?: FormPost | WaitForCustomer;\n widgetConfig: OpyWidgetConfig;\n };\n}\n\nexport function isOpyPaymentMethod(\n paymentMethod: PaymentMethod,\n): paymentMethod is OpyPaymentMethod {\n return !!paymentMethod.initializationData?.widgetConfig;\n}\n","import { StandardError } from '../../../common/error/errors';\n\nexport enum OpyErrorType {\n InvalidCart = 'invalid_cart',\n}\nexport default class OpyError extends StandardError {\n subtype: string;\n\n constructor(subtype: OpyErrorType, displayName: string) {\n super(getErrorMessage(subtype, displayName));\n\n this.name = 'OpyError';\n this.type = 'opy_error';\n this.subtype = subtype;\n }\n}\n\nfunction getErrorMessage(type: OpyErrorType, displayName: string): string {\n switch (type) {\n case OpyErrorType.InvalidCart:\n return `Cart price is different to ${displayName} plan amount.`;\n\n default:\n return 'There was an error while processing your payment. Please try again or contact us.';\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotImplementedError,\n RequestError,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport StorefrontPaymentRequestSender from '../../storefront-payment-request-sender';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { ActionTypes, isOpyPaymentMethod } from './opy';\nimport { OpyWidgetConfig } from './opy-library';\nimport OpyError, { OpyErrorType } from './opy-payment-error';\nimport OpyScriptLoader from './opy-script-loader';\n\nexport default class OpyPaymentStrategy implements PaymentStrategy {\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _storefrontPaymentRequestSender: StorefrontPaymentRequestSender,\n private _paymentActionCreator: PaymentActionCreator,\n private _scriptLoader: OpyScriptLoader,\n ) {}\n\n async initialize(options?: PaymentInitializeOptions): Promise {\n if (options?.opy?.containerId) {\n const {\n methodId,\n opy: { containerId },\n } = options;\n\n const paymentMethod = this._store.getState().paymentMethods.getPaymentMethod(methodId);\n\n if (paymentMethod && isOpyPaymentMethod(paymentMethod)) {\n const {\n initializationData: { widgetConfig },\n } = paymentMethod;\n\n await this._installWidget(containerId, widgetConfig);\n }\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId } = payment;\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId, options),\n );\n const paymentMethod = getPaymentMethodOrThrow(methodId);\n\n if (!isOpyPaymentMethod(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n clientToken: nonce,\n initializationData: { nextAction },\n } = paymentMethod;\n\n if (!nextAction) {\n const { displayName = 'Openpay' } = paymentMethod.config;\n\n throw new OpyError(OpyErrorType.InvalidCart, displayName);\n }\n\n if (!nonce) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n await this._storefrontPaymentRequestSender.saveExternalId(methodId, nonce);\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({ methodId, paymentData: { nonce } }),\n );\n } catch (error) {\n if (\n error instanceof RequestError &&\n error.body.status === 'additional_action_required'\n ) {\n if (nextAction.type === ActionTypes.FORM_POST) {\n const { formPostUrl, formFields } = nextAction.formPost;\n\n const url = new URL(formPostUrl.replace(/\\/$/, ''));\n\n formFields.forEach(({ fieldName, fieldValue }) => {\n url.searchParams.append(fieldName, fieldValue);\n });\n\n return new Promise(() => window.location.assign(decodeURI(url.href)));\n }\n\n throw new NotImplementedError(`Unsupported action type: ${nextAction.type}`);\n }\n\n throw error;\n }\n }\n\n finalize(_options?: PaymentRequestOptions): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(_options?: PaymentRequestOptions): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n private async _installWidget(containerId: string, config: OpyWidgetConfig): Promise {\n const widgetContainer = document.getElementById(containerId);\n\n if (widgetContainer) {\n try {\n const widget = await this._scriptLoader.loadOpyWidget(config.region);\n\n widget.Config(config);\n } catch (error) {\n return;\n }\n\n widgetContainer.appendChild(document.createElement('opy-learn-more-button'));\n }\n }\n}\n","export enum OpyRegion {\n AU = 'AU',\n UK = 'UK',\n US = 'US',\n}\n\n/**\n * https://widgets.openpay.com.au/config\n */\nexport interface OpyWidgetConfig {\n /**\n * The region your store is located in.\n */\n region: OpyRegion;\n /**\n * The currency symbol used in the widgets.\n */\n currency: '$' | '£';\n /**\n * An array of available plan tiers you have available in months.\n */\n planTiers: number[];\n /**\n * The minimum eligible amount required before Opy is eligible.\n */\n minEligibleAmount: number;\n /**\n * The maximum eligible amount required before Opy is eligible.\n */\n maxEligibleAmount: number;\n /**\n * Type of your store.\n */\n type: 'Online';\n}\n\nexport interface OpyWidget {\n /**\n * Initialize the library.\n *\n * @param config Properties with the correct purchase limits, plan tiers, etc.\n */\n Config(config: OpyWidgetConfig): void;\n}\n\nexport interface OpyHostWindow extends Window {\n /**\n * The Opy widgets library.\n */\n OpenpayWidgets?: OpyWidget;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { OpyHostWindow, OpyRegion, OpyWidget } from './opy-library';\n\nconst AU_REGION_URL = 'https://widgets.openpay.com.au/lib/openpay-widgets.min.js';\n\nconst SOURCES = {\n AU: AU_REGION_URL,\n UK: AU_REGION_URL,\n US: 'https://widgets.opy.com/lib/openpay-widgets.min.js',\n};\n\nexport default class OpyScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, private _window: OpyHostWindow = window) {}\n\n async loadOpyWidget(region = OpyRegion.AU): Promise {\n await this._scriptLoader.loadScript(SOURCES[region]);\n\n if (!this._window.OpenpayWidgets) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.OpenpayWidgets;\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { ACKNOWLEDGE } from '../../payment-status-types';\nimport { CardinalThreeDSecureFlow } from '../cardinal';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class PaypalProPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _threeDSecureFlow: CardinalThreeDSecureFlow,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(options.methodId);\n\n if (paymentMethod.config.is3dsEnabled) {\n await this._threeDSecureFlow.prepare(paymentMethod);\n }\n\n return this._store.getState();\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment: { methodId = '' } = {} } = payload;\n const {\n payment: { getPaymentStatus },\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n\n if (getPaymentStatus() === ACKNOWLEDGE) {\n return this._store.dispatch(\n this._orderActionCreator.submitOrder(\n {\n ...payload,\n payment: { methodId },\n },\n options,\n ),\n );\n }\n\n if (getPaymentMethodOrThrow(methodId).config.is3dsEnabled) {\n return this._threeDSecureFlow.start(\n super.execute.bind(this),\n payload,\n options,\n this._hostedForm,\n );\n }\n\n return super.execute(payload, options);\n }\n}\n","import { noop } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport PaymentMethod from '../../payment-method';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport PaymentStrategy from '../payment-strategy';\n\nimport PaypalScriptLoader from './paypal-script-loader';\nimport { PaypalHostWindow, PaypalSDK } from './paypal-sdk';\n\nexport default class PaypalExpressPaymentStrategy implements PaymentStrategy {\n private _paypalSdk?: PaypalSDK;\n private _paymentMethod?: PaymentMethod;\n private _useRedirectFlow = false;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _scriptLoader: PaypalScriptLoader,\n private _window: PaypalHostWindow = window,\n ) {}\n\n initialize(options: PaymentInitializeOptions): Promise {\n const state = this._store.getState();\n\n this._paymentMethod = state.paymentMethods.getPaymentMethod(options.methodId);\n this._useRedirectFlow =\n (options.paypalexpress && options.paypalexpress.useRedirectFlow) === true;\n\n if (!this._isInContextEnabled()) {\n return Promise.resolve(this._store.getState());\n }\n\n return this._scriptLoader\n .loadPaypal()\n .then((paypal) => {\n this._paypalSdk = paypal;\n\n if (!this._paymentMethod || !this._paymentMethod.config.merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._paypalSdk.checkout.setup(this._paymentMethod.config.merchantId, {\n button: 'paypal-button',\n environment: this._paymentMethod.config.testMode ? 'sandbox' : 'production',\n });\n })\n .then(() => this._store.getState());\n }\n\n deinitialize(): Promise {\n if (this._isInContextEnabled() && this._paypalSdk) {\n this._paypalSdk.checkout.closeFlow();\n this._paypalSdk = undefined;\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const paypal = this._paypalSdk;\n\n if (this._isAcknowledgedOrFinalized()) {\n return this._store.dispatch(this._orderActionCreator.submitOrder(payload, options));\n }\n\n if (!this._isInContextEnabled() || this._useRedirectFlow) {\n return this._store\n .dispatch(this._orderActionCreator.submitOrder(payload, options))\n .then((state) => {\n const redirectUrl = state.payment.getPaymentRedirectUrl();\n\n if (redirectUrl) {\n this._window.top.location.href = redirectUrl;\n }\n\n // We need to hold execution so the consumer does not redirect us somewhere else\n return new Promise(noop);\n });\n }\n\n if (!paypal) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n paypal.checkout.initXO();\n\n return this._store\n .dispatch(this._orderActionCreator.submitOrder(payload, options))\n .then((state) => {\n const redirectUrl = state.payment.getPaymentRedirectUrl();\n\n if (redirectUrl) {\n paypal.checkout.startFlow(redirectUrl);\n }\n\n // We need to hold execution so the consumer does not redirect us somewhere else\n return new Promise(noop);\n })\n .catch((error) => {\n paypal.checkout.closeFlow();\n\n return Promise.reject(error);\n });\n }\n\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this._store.getState();\n const order = state.order.getOrder();\n\n if (order && this._isAcknowledgedOrFinalized()) {\n return this._store.dispatch(\n this._orderActionCreator.finalizeOrder(order.orderId, options),\n );\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private _isAcknowledgedOrFinalized(): boolean {\n const state = this._store.getState();\n\n return (\n state.payment.getPaymentStatus() === paymentStatusTypes.ACKNOWLEDGE ||\n state.payment.getPaymentStatus() === paymentStatusTypes.FINALIZE\n );\n }\n\n private _isInContextEnabled(): boolean {\n return !!(this._paymentMethod && this._paymentMethod.config.merchantId);\n }\n}\n","import { LoadScriptOptions, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { PaypalHostWindow, PaypalSDK } from './paypal-sdk';\n\nexport default class PaypalScriptLoader {\n private _window: PaypalHostWindow;\n\n constructor(private _scriptLoader: ScriptLoader) {\n this._window = window;\n }\n\n async loadPaypal(merchantId = ''): Promise {\n const scriptSrc = '//www.paypalobjects.com/api/checkout.min.js';\n const options: LoadScriptOptions = {\n async: true,\n attributes: { 'data-merchant-id': merchantId },\n };\n\n merchantId\n ? await this._scriptLoader.loadScript(scriptSrc, options)\n : await this._scriptLoader.loadScript(scriptSrc);\n\n if (!this._window.paypal) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.paypal;\n }\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"query-string\");","import { exclude, ParsedUrl, parseUrl, stringifyUrl } from 'query-string';\n\nexport const PENDING_REDIRECT_PARAM = 'redirecting';\n\nexport class RedirectionState {\n private _isRedirecting: boolean;\n\n constructor() {\n this._isRedirecting = this.currentUrlHasRedirectingParam();\n }\n\n isRedirecting() {\n return this._isRedirecting;\n }\n\n setRedirecting(value: boolean) {\n if (value) {\n this.setRedirectingParamOnUrl();\n } else {\n this.removeRedirectingParamFromUrl();\n }\n\n this._isRedirecting = value;\n }\n\n private currentUrlHasRedirectingParam(): boolean {\n return PENDING_REDIRECT_PARAM in this.getCurrentUrl().query;\n }\n\n private getCurrentUrl(): ParsedUrl {\n return parseUrl(window.location.href);\n }\n\n private replaceCurrentUrl(url: string) {\n window.history.replaceState(null, '', url);\n }\n\n private setRedirectingParamOnUrl() {\n if (this.currentUrlHasRedirectingParam()) {\n return;\n }\n\n const currentUrl = this.getCurrentUrl();\n const updatedUrl = {\n ...currentUrl,\n query: {\n ...currentUrl.query,\n [PENDING_REDIRECT_PARAM]: 'true',\n },\n };\n\n this.replaceCurrentUrl(stringifyUrl(updatedUrl));\n }\n\n private removeRedirectingParamFromUrl() {\n if (!this.currentUrlHasRedirectingParam()) {\n return;\n }\n\n this.replaceCurrentUrl(exclude(window.location.href, [PENDING_REDIRECT_PARAM]));\n }\n}\n","export enum SubStrategyType {\n CARD = 'card_ui',\n NONE = 'none',\n UNSUPPORTED = 'unsupported',\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { overSome } from 'lodash';\n\nimport { PaymentHumanVerificationHandler } from '../../../../../spam-protection';\nimport PaymentAdditionalAction from '../../../../payment-additional-action';\nimport { PaymentsAPIResponse } from '../../ppsdk-payments-api-response';\n\nimport {\n handleHumanVerification,\n HumanVerification,\n isHumanVerification,\n} from './human-verification';\nimport { handleRedirect, isRedirect, Redirect } from './redirect';\n\nexport type Continue = Redirect | HumanVerification;\n\nconst isAnyContinue = overSome([isRedirect, isHumanVerification]);\n\nexport const isContinue = (body: PaymentsAPIResponse['body']): body is Continue =>\n isAnyContinue(body);\n\nexport interface ContinueCallbacks {\n humanVerification?(additionalAction: PaymentAdditionalAction): Promise;\n}\n\nexport class ContinueHandler {\n constructor(\n private _formPoster: FormPoster,\n private _humanVerificationHandler: PaymentHumanVerificationHandler,\n ) {}\n\n handle(body: Continue, callbacks?: ContinueCallbacks): Promise {\n switch (body.code) {\n case 'redirect':\n return handleRedirect(body.parameters, this._formPoster);\n\n case 'resubmit_with_human_verification':\n return handleHumanVerification(\n body.parameters,\n this._humanVerificationHandler,\n callbacks?.humanVerification,\n );\n }\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { get, isObject, isString, isUndefined, noop } from 'lodash';\n\nimport { PaymentMethodCancelledError } from '../../../../../errors';\nimport { PaymentsAPIResponse } from '../../../ppsdk-payments-api-response';\n\nimport { RedirectionState } from './RedirectionState';\n\ninterface Parameters {\n url: string;\n form_fields?: Record;\n}\n\nexport interface Redirect {\n type: 'continue';\n code: 'redirect';\n parameters: Parameters;\n}\n\nconst isParameters = (x: unknown): x is Parameters => {\n const formFields = get(x, 'form_fields');\n\n return isString(get(x, 'url')) && (isUndefined(formFields) || isObject(formFields));\n};\n\nexport const isRedirect = (body: PaymentsAPIResponse['body']): body is Redirect =>\n get(body, 'type') === 'continue' &&\n get(body, 'code') === 'redirect' &&\n isParameters(get(body, 'parameters'));\n\nexport const handleRedirect = (\n { url, form_fields }: Parameters,\n formPoster: FormPoster,\n): Promise => {\n const redirectionState = new RedirectionState();\n\n if (redirectionState.isRedirecting()) {\n redirectionState.setRedirecting(false);\n\n return Promise.reject(new PaymentMethodCancelledError());\n }\n\n redirectionState.setRedirecting(true);\n\n if (form_fields) {\n formPoster.postForm(url, form_fields);\n } else {\n window.location.assign(url);\n }\n\n return new Promise(noop);\n};\n","import { get, isArray } from 'lodash';\n\nimport { PaymentHumanVerificationHandler } from '../../../../../../spam-protection';\nimport PaymentAdditionalAction from '../../../../../payment-additional-action';\nimport { PaymentsAPIResponse } from '../../../ppsdk-payments-api-response';\n\ninterface VerificationMethod {\n id: string;\n parameters: Record;\n}\n\ninterface Parameters {\n available_methods: VerificationMethod[];\n}\n\nexport interface HumanVerification {\n type: 'continue';\n code: 'resubmit_with_human_verification';\n parameters: Parameters;\n}\n\nconst isParameters = (x: unknown): x is Parameters => {\n const availableMethods = get(x, 'available_methods');\n\n return isArray(availableMethods);\n};\n\nexport const isHumanVerification = (body: PaymentsAPIResponse['body']): body is HumanVerification =>\n get(body, 'type') === 'continue' &&\n get(body, 'code') === 'resubmit_with_human_verification' &&\n isParameters(get(body, 'parameters'));\n\nexport const handleHumanVerification = async (\n { available_methods }: Parameters,\n humanVerificationHandler?: PaymentHumanVerificationHandler,\n callback?: (additionalAction: PaymentAdditionalAction) => Promise,\n): Promise => {\n if (!callback) {\n throw new Error('PPSDK human verification callback function is missing.');\n }\n\n if (!humanVerificationHandler) {\n throw new Error('PPSDK human verification handler is missing.');\n }\n\n if (available_methods.length === 0) {\n throw Error('Human verification method is missing.');\n }\n\n // Only one method is expected because google recaptcha only is supported\n const { id, parameters } = available_methods[0];\n\n const additionalAction: PaymentAdditionalAction = await humanVerificationHandler.handle(\n id,\n parameters.key,\n );\n\n return callback(additionalAction);\n};\n","import { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\n\nimport { ContinueCallbacks, ContinueHandler, isContinue } from './continue-handler';\nimport { handleError, isError } from './error';\nimport { handleFailure, isFailure } from './failure';\nimport { handleSuccess, isSuccess } from './success';\nimport { handleUnsupported } from './unsupported';\n\ninterface StepHandlerCallbacks {\n continue?: ContinueCallbacks;\n}\n\nexport class StepHandler {\n constructor(private _continueHandler: ContinueHandler) {}\n\n handle(response: PaymentsAPIResponse, callbacks?: StepHandlerCallbacks): Promise {\n const { body } = response;\n\n if (isSuccess(body)) {\n return handleSuccess();\n }\n\n if (isContinue(body)) {\n return this._continueHandler.handle(body, callbacks?.continue);\n }\n\n if (isFailure(response)) {\n return handleFailure(response);\n }\n\n if (isError(response)) {\n return handleError(response);\n }\n\n return handleUnsupported(response);\n }\n}\n","import { get } from 'lodash';\n\nimport { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\n\nexport interface Success {\n type: 'success';\n}\n\nexport const isSuccess = (body: PaymentsAPIResponse['body']): body is Success =>\n get(body, 'type') === 'success';\n\nexport const handleSuccess = () => Promise.resolve();\n","import { get, isString } from 'lodash';\n\nimport { RequestError } from '../../../../common/error/errors';\nimport { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\n\nexport interface FailureResponse extends PaymentsAPIResponse {\n body: {\n type: 'failure';\n code: string;\n };\n}\n\nexport const isFailure = (response: PaymentsAPIResponse): response is FailureResponse =>\n get(response.body, 'type') === 'failure' && isString(get(response.body, 'code'));\n\nconst toRequestErrorFormat = (failureResponse: FailureResponse) => ({\n ...failureResponse,\n body: {\n errors: [{ code: failureResponse.body.code }],\n },\n});\n\nexport const handleFailure = (response: FailureResponse): Promise =>\n Promise.reject(new RequestError(toRequestErrorFormat(response)));\n","import { get } from 'lodash';\n\nimport { RequestError } from '../../../../common/error/errors';\nimport { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\n\nexport interface ErrorResponse extends PaymentsAPIResponse {\n body: {\n type: 'error';\n };\n}\n\nexport const isError = (response: PaymentsAPIResponse): response is ErrorResponse =>\n get(response.body, 'type') === 'error';\n\nexport const handleError = (response: ErrorResponse) => Promise.reject(new RequestError(response));\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { PaymentHumanVerificationHandler } from '../../../../spam-protection';\n\nimport { ContinueHandler } from './continue-handler';\nimport { StepHandler } from './step-handler';\n\nexport const createStepHandler = (\n formPoster: FormPoster,\n humanVerificationHandler: PaymentHumanVerificationHandler,\n) => new StepHandler(new ContinueHandler(formPoster, humanVerificationHandler));\n","import { BrowserStorage } from '../../../common/storage';\n\ntype CompletedPayments = string[];\n\nconst COMPLETED_PAYMENTS_KEY = 'completed-payments';\n\nexport class PPSDKCompletedPayments {\n constructor(private _browserStorage: BrowserStorage) {}\n\n isCompleted(paymentId: string): boolean {\n return this.getCompletedPayments().indexOf(paymentId) >= 0;\n }\n\n setCompleted(paymentId: string): void {\n const completedPayments = this.getCompletedPayments();\n\n completedPayments.push(paymentId);\n\n this.setCompletedPayments(completedPayments);\n }\n\n private getCompletedPayments(): CompletedPayments {\n return this._browserStorage.getItem(COMPLETED_PAYMENTS_KEY) || [];\n }\n\n private setCompletedPayments(completedPayments: CompletedPayments): void {\n this._browserStorage.setItem(COMPLETED_PAYMENTS_KEY, completedPayments);\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { BrowserStorage } from '../../../common/storage';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { getPPSDKMethod } from './get-ppsdk-payment-method';\nimport { PPSDKCompletedPayments } from './ppsdk-completed-payments';\nimport { PaymentResumer } from './ppsdk-payment-resumer';\nimport { SubStrategy } from './ppsdk-sub-strategy';\nimport { SubStrategyRegistry } from './ppsdk-sub-strategy-registry';\n\nexport class PPSDKStrategy implements PaymentStrategy {\n private _subStrategy?: SubStrategy;\n private _completedPayments: PPSDKCompletedPayments;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _subStrategyRegistry: SubStrategyRegistry,\n private _paymentResumer: PaymentResumer,\n browserStorage: BrowserStorage,\n ) {\n this._completedPayments = new PPSDKCompletedPayments(browserStorage);\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { bigpayBaseUrl } = this._store\n .getState()\n .config.getStoreConfigOrThrow().paymentSettings;\n\n if (!options?.methodId) {\n throw new InvalidArgumentError(\n 'Unable to submit payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n const { methodId } = options;\n const { payment, ...order } = payload;\n const { _subStrategy: subStrategy } = this;\n\n if (!subStrategy) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n const token = this._store.getState().order.getOrderMeta()?.token;\n\n if (!token) {\n throw new MissingDataError(MissingDataErrorType.MissingOrder);\n }\n\n await subStrategy.execute({ methodId, payment, bigpayBaseUrl, token });\n\n return this._store.getState();\n }\n\n async finalize(options?: PaymentRequestOptions): Promise {\n const order = this._store.getState().order.getOrderOrThrow();\n\n if (order.isComplete) {\n return this._store.getState();\n }\n\n const { bigpayBaseUrl } = this._store\n .getState()\n .config.getStoreConfigOrThrow().paymentSettings;\n\n if (!options?.methodId) {\n throw new InvalidArgumentError(\n 'Unable to submit payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n const paymentId = this._store.getState().order.getPaymentId(options.methodId);\n\n if (!paymentId || !order || this._completedPayments.isCompleted(paymentId)) {\n throw new OrderFinalizationNotRequiredError();\n }\n\n const { orderId } = order;\n\n await this._paymentResumer.resume({ paymentId, bigpayBaseUrl, orderId }).catch((error) => {\n this._completedPayments.setCompleted(paymentId);\n throw error;\n });\n\n return this._store.getState();\n }\n\n async initialize(options?: PaymentInitializeOptions): Promise {\n if (!options?.methodId) {\n throw new InvalidArgumentError(\n 'Unable to submit payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n const paymentMethod = getPPSDKMethod(this._store, options.methodId);\n\n if (!paymentMethod) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._subStrategy = this._subStrategyRegistry.getByMethod(paymentMethod);\n\n if (!this._subStrategy) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n await this._subStrategy.initialize(options);\n\n return this._store.getState();\n }\n\n async deinitialize(_options?: PaymentRequestOptions): Promise {\n this._subStrategy?.deinitialize();\n\n return this._store.getState();\n }\n}\n","import { CheckoutStore } from '../../../checkout';\nimport { isPPSDKPaymentMethod, PPSDKPaymentMethod } from '../../ppsdk-payment-method';\n\ntype GetPPSDKMethod = (store: CheckoutStore, methodId: string) => PPSDKPaymentMethod | undefined;\n\nexport const getPPSDKMethod: GetPPSDKMethod = (store, methodId) => {\n const paymentMethod = store.getState().paymentMethods.getPaymentMethod(methodId);\n\n if (!paymentMethod || !isPPSDKPaymentMethod(paymentMethod)) {\n return;\n }\n\n return paymentMethod;\n};\n","import { cond, constant, stubTrue } from 'lodash';\n\nimport { Registry } from '../../../common/registry';\nimport { PPSDKPaymentMethod } from '../../ppsdk-payment-method';\n\nimport { isCard, isNone } from './initialization-strategies';\nimport { SubStrategy } from './ppsdk-sub-strategy';\nimport { SubStrategyType } from './ppsdk-sub-strategy-type';\n\nconst getToken = cond([\n [isCard, constant(SubStrategyType.CARD)],\n [isNone, constant(SubStrategyType.NONE)],\n [stubTrue, constant(SubStrategyType.UNSUPPORTED)],\n]);\n\nexport class SubStrategyRegistry extends Registry {\n getByMethod(paymentMethod: PPSDKPaymentMethod): SubStrategy | undefined {\n const token = getToken(paymentMethod.initializationStrategy);\n\n return this.get(token);\n }\n}\n","import { InitializationStrategy } from '../../../';\n\ninterface Card {\n type: 'card_ui';\n}\n\nexport const isCard = (strategy: Pick): strategy is Card =>\n strategy.type === 'card_ui';\n","import { InitializationStrategy } from '../../../';\n\ninterface None {\n type: 'none';\n}\n\nexport const isNone = (strategy: Pick): strategy is None =>\n strategy.type === 'none';\n","import { CheckoutStore } from '../../../../checkout';\nimport {\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../../common/error/errors';\nimport { HostedForm, HostedFormFactory } from '../../../../hosted-form';\nimport { OrderActionCreator } from '../../../../order';\nimport { PaymentArgumentInvalidError } from '../../../errors';\nimport PaymentAdditionalAction from '../../../payment-additional-action';\nimport { PaymentInitializeOptions } from '../../../payment-request-options';\nimport { SubStrategy, SubStrategySettings } from '../ppsdk-sub-strategy';\nimport { StepHandler } from '../step-handler';\n\nexport class CardSubStrategy implements SubStrategy {\n protected _hostedForm?: HostedForm;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _hostedFormFactory: HostedFormFactory,\n private _ppsdkStepHandler: StepHandler,\n ) {}\n\n async execute(settings: SubStrategySettings): Promise {\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { additionalAction, payment } = settings;\n\n if (!payment || !payment.methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n await form.validate();\n\n const { payload } = await form.submit(payment, additionalAction);\n\n const { response } = payload;\n\n const humanVerificationCallback = async (\n additionalAction: PaymentAdditionalAction,\n ): Promise => this.execute({ additionalAction, ...settings });\n\n await this._ppsdkStepHandler.handle(response, {\n continue: {\n humanVerification: humanVerificationCallback,\n },\n });\n\n await this._store.dispatch(this._orderActionCreator.loadCurrentOrder());\n }\n\n async initialize(options?: PaymentInitializeOptions): Promise {\n const formOptions = options && options.creditCard && options.creditCard.form;\n const { config } = this._store.getState();\n const { paymentSettings: { bigpayBaseUrl: host = '' } = {} } =\n config.getStoreConfig() || {};\n\n if (!formOptions) {\n throw new InvalidArgumentError();\n }\n\n const form = formOptions && this._hostedFormFactory.create(host, formOptions);\n\n await form.attach();\n\n this._hostedForm = form;\n }\n\n deinitialize(): void {\n if (this._hostedForm) {\n this._hostedForm.detach();\n }\n }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\nimport { SubStrategy, SubStrategySettings } from '../ppsdk-sub-strategy';\nimport { StepHandler } from '../step-handler';\n\nexport class NoneSubStrategy implements SubStrategy {\n constructor(private _requestSender: RequestSender, private _stepHandler: StepHandler) {}\n\n execute({ methodId, bigpayBaseUrl, token }: SubStrategySettings): Promise {\n const body = { payment_method_id: methodId };\n const options = {\n credentials: false,\n body,\n headers: {\n authorization: token,\n 'X-XSRF-TOKEN': null,\n },\n };\n\n return this._requestSender\n .post(`${bigpayBaseUrl}/payments`, options)\n .then((response) => this._stepHandler.handle(response));\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): void {}\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { CheckoutStore } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator } from '../../../order';\n\nimport { SubStrategyRegistry } from './ppsdk-sub-strategy-registry';\nimport { SubStrategyType } from './ppsdk-sub-strategy-type';\nimport { StepHandler } from './step-handler';\nimport { CardSubStrategy, NoneSubStrategy } from './sub-strategies';\n\nexport const createSubStrategyRegistry = (\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n requestSender: RequestSender,\n stepHandler: StepHandler,\n hostedFormFactory: HostedFormFactory,\n) => {\n const registry = new SubStrategyRegistry();\n\n registry.register(\n SubStrategyType.CARD,\n () => new CardSubStrategy(store, orderActionCreator, hostedFormFactory, stepHandler),\n );\n\n registry.register(SubStrategyType.NONE, () => new NoneSubStrategy(requestSender, stepHandler));\n\n registry.register(SubStrategyType.UNSUPPORTED, () => undefined);\n\n return registry;\n};\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\n\nimport { PaymentsAPIResponse } from './ppsdk-payments-api-response';\nimport { StepHandler } from './step-handler';\n\ninterface ResumeSettings {\n orderId: number;\n paymentId: string;\n bigpayBaseUrl: string;\n}\n\nexport class PaymentResumer {\n constructor(private _requestSender: RequestSender, private _stepHandler: StepHandler) {}\n\n async resume({ paymentId, bigpayBaseUrl, orderId }: ResumeSettings): Promise {\n const token = await this._getToken(orderId).catch(() => {\n throw new OrderFinalizationNotRequiredError();\n });\n\n const options = {\n credentials: false,\n headers: {\n authorization: token,\n 'X-XSRF-TOKEN': null,\n },\n };\n\n return this._requestSender\n .get(`${bigpayBaseUrl}/payments/${paymentId}`, options)\n .then((response) => this._stepHandler.handle(response));\n }\n\n private async _getToken(orderId: number): Promise {\n const url = `/api/storefront/payments/auth-token`;\n const options = {\n params: {\n order_id: orderId,\n },\n };\n\n return this._requestSender\n .get<{ auth_token: string }>(url, options)\n .then(({ body }) => body.auth_token);\n }\n}\n","import { noop } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { MissingDataError, MissingDataErrorType, RequestError } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport { StoreCreditActionCreator } from '../../../store-credit';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport StorefrontPaymentRequestSender from '../../storefront-payment-request-sender';\nimport PaymentStrategy from '../payment-strategy';\n\nexport default class QuadpayPaymentStrategy implements PaymentStrategy {\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _storeCreditActionCreator: StoreCreditActionCreator,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n private _storefrontPaymentRequestSender: StorefrontPaymentRequestSender,\n ) {}\n\n initialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId } = payment;\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId, options),\n );\n const { clientToken, initializationData: { redirectUrl } = {} } =\n getPaymentMethodOrThrow(methodId);\n\n if (!clientToken || !redirectUrl) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { id: nonce } = JSON.parse(clientToken);\n\n if (!nonce) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n const paymentPayload = {\n methodId,\n paymentData: { nonce },\n };\n\n const { isStoreCreditApplied: useStoreCredit } = this._store\n .getState()\n .checkout.getCheckoutOrThrow();\n\n await this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(useStoreCredit));\n await this._store.dispatch(\n this._remoteCheckoutActionCreator.initializePayment(methodId, { useStoreCredit }),\n );\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n await this._prepareForReferredRegistration(methodId, nonce);\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentPayload),\n );\n } catch (error) {\n if (\n error instanceof RequestError &&\n error.body.status === 'additional_action_required'\n ) {\n window.location.replace(redirectUrl);\n\n return new Promise(noop);\n }\n\n throw error;\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n private _prepareForReferredRegistration(methodId: string, externalId: string): Promise {\n return this._storefrontPaymentRequestSender.saveExternalId(methodId, externalId);\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { some } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { getBrowserInfo } from '../../../common/browser-info';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class SagePayPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _formPoster: FormPoster,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment } = payload;\n\n if (!payment) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { paymentData } = payment;\n\n if (!paymentData) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n if (this._isThreeDSTwoExperimentOn()) {\n const newPaymentData = {\n ...paymentData,\n browser_info: getBrowserInfo(),\n };\n\n if (payload.payment) {\n payload.payment.paymentData = newPaymentData;\n }\n }\n\n return super.execute(payload, options).catch((error: Error) => {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return Promise.reject(error);\n }\n\n return new Promise(() => {\n let payload;\n\n if (this._isThreeDSTwoExperimentOn() && !error.body.three_ds_result.merchant_data) {\n payload = {\n creq: error.body.three_ds_result.payer_auth_request,\n };\n } else {\n payload = {\n PaReq: error.body.three_ds_result.payer_auth_request,\n TermUrl: error.body.three_ds_result.callback_url,\n MD: error.body.three_ds_result.merchant_data,\n };\n }\n\n this._formPoster.postForm(\n error.body.three_ds_result.acs_url,\n payload,\n undefined,\n '_top',\n );\n });\n });\n }\n\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this._store.getState();\n const order = state.order.getOrder();\n\n if (order && state.payment.getPaymentStatus() === paymentStatusTypes.FINALIZE) {\n return this._store.dispatch(\n this._orderActionCreator.finalizeOrder(order.orderId, options),\n );\n }\n\n return super.finalize(options);\n }\n\n private _isThreeDSTwoExperimentOn(): boolean {\n return (\n this._store.getState().config.getStoreConfigOrThrow().checkoutSettings.features[\n 'INT-4994.Opayo_3DS2'\n ] === true\n );\n }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport RequestError from './request-error';\n\n/**\n * Throw this error if a request fails to complete within its required timeframe\n * because of a network issue.\n */\nexport default class TimeoutError extends RequestError {\n constructor(response?: Response) {\n super(response, {\n message: 'The request has timed out or aborted.',\n });\n\n this.name = 'TimeoutError';\n this.type = 'timeout';\n }\n}\n","import { NonceInstrument } from '../../payment';\n\nexport default interface SquarePaymentForm {\n build(): void;\n requestCardNonce(): void;\n setPostalCode(postalCode: string): void;\n verifyBuyer(\n source?: string,\n verificationDetails?: VerificationDetails,\n callback?: VerifyBuyerResponse,\n ): void;\n}\n\nexport type VerifyBuyerResponse = (\n errors: SquareVerificationError,\n verificationResult: SquareVerificationResult,\n) => void;\n\nexport interface SquareVerificationError {\n type: string;\n message: string;\n}\n\nexport interface SquareVerificationResult {\n token: string;\n userChallenged: boolean;\n}\n\nexport enum SquareIntent {\n CHARGE = 'CHARGE',\n STORE = 'STORE',\n}\n\nexport interface VerificationDetails {\n intent: string;\n amount?: string;\n currencyCode?: string;\n billingContact?: Contact;\n}\n\nexport type SquarePaymentFormConstructor = new (options: SquareFormOptions) => SquarePaymentForm;\n\nexport type SquareScriptCallBack = (options: SquareFormOptions) => SquarePaymentForm;\n\nexport interface SquareFormOptions {\n applicationId: string;\n env: string;\n locationId: string;\n inputClass?: string;\n inputStyles?: string[];\n callbacks?: SquareFormCallbacks;\n cardNumber: SquareFormElement;\n cvv: SquareFormElement;\n expirationDate: SquareFormElement;\n postalCode: SquareFormElement;\n}\nexport interface LineItem {\n label: string;\n amount: string;\n pending: boolean;\n}\n\nexport interface SquarePaymentRequest {\n requestShippingAddress: boolean;\n requestBillingInfo: boolean;\n shippingContact?: Contact;\n countryCode: string;\n currencyCode: string;\n lineItems?: LineItem[];\n total: LineItem;\n}\n\nexport interface NonceGenerationError {\n type: string;\n message: string;\n field: string;\n}\n\nexport interface CardData {\n card_brand: CardBrand;\n last_4: number;\n exp_month: number;\n exp_year: number;\n billing_postal_code: string;\n digital_wallet_type: DigitalWalletType;\n}\n\nexport interface Contact {\n familyName: string;\n givenName: string;\n email: string;\n country: string;\n countryName: string;\n region: string;\n city: string;\n addressLines: string[];\n postalCode: string;\n phone: string;\n}\n\nexport enum CardBrand {\n americanExpress = 'AMERICAN_EXPRESS',\n discover = 'DISCOVER',\n discoverDiners = 'DISCOVER_DINERS',\n JCB = 'JCB',\n masterCard = 'MASTERCARD',\n unionPay = 'CHINA_UNIONPAY',\n unknown = 'OTHER_BRAND',\n visa = 'VISA',\n squareGift = 'SQUARE_GIFT_CARD',\n}\n\nexport enum DigitalWalletType {\n applePay = 'APPLEPAY',\n none = 'NONE',\n}\n\n/**\n * Configures any form element provided by Square payment.\n */\nexport interface SquareFormElement {\n /**\n * The ID of the container which the form element should insert into.\n */\n elementId: string;\n\n /**\n * The placeholder text to use for the form element, if provided.\n */\n placeholder?: string;\n}\n\nexport interface SquareFormCallbacks {\n paymentFormLoaded?(form: SquarePaymentForm): void;\n unsupportedBrowserDetected?(): void;\n cardNonceResponseReceived?(\n errors?: NonceGenerationError[],\n nonce?: string,\n cardData?: CardData,\n billingContact?: Contact,\n shippingContact?: Contact,\n ): void;\n methodsSupported?(methods: { [key: string]: boolean }): void;\n createPaymentRequest?(): void;\n}\n\nexport type SquareFormFactory = (options: SquareFormOptions) => SquarePaymentForm;\n\nexport interface DeferredPromise {\n resolve(resolution?: SquareNonceInstrument): void;\n reject(reason?: any): void;\n}\n\nexport interface SquareNonceInstrument extends NonceInstrument {\n token?: string;\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\nimport { get, isEmpty, noop, omit } from 'lodash';\n\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n TimeoutError,\n UnsupportedBrowserError,\n} from '../../../common/error/errors';\nimport { SDK_VERSION_HEADERS } from '../../../common/http-request';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentMethodClientUnavailableError } from '../../errors';\nimport { NonceInstrument } from '../../payment';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategyActionCreator from '../../payment-strategy-action-creator';\nimport PaymentStrategy from '../payment-strategy';\n\nimport SquarePaymentForm, {\n CardData,\n Contact,\n DeferredPromise,\n DigitalWalletType,\n SquareFormOptions,\n SquareIntent,\n SquarePaymentRequest,\n SquareVerificationError,\n SquareVerificationResult,\n VerificationDetails,\n} from './square-form';\nimport SquarePaymentInitializeOptions from './square-payment-initialize-options';\nimport SquareScriptLoader from './square-script-loader';\n\nexport default class SquarePaymentStrategy implements PaymentStrategy {\n private _deferredRequestNonce?: DeferredPromise;\n private _paymentForm?: SquarePaymentForm;\n private _paymentMethod?: PaymentMethod;\n private _squareOptions?: SquarePaymentInitializeOptions;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentStrategyActionCreator: PaymentStrategyActionCreator,\n private _requestSender: RequestSender,\n private _scriptLoader: SquareScriptLoader,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const { methodId, gatewayId, square: squareOptions } = options;\n\n if (!squareOptions) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"options.square\" argument is not provided.',\n );\n }\n\n this._squareOptions = squareOptions;\n\n this._syncPaymentMethod(methodId);\n\n /* eslint-disable */\n return new Promise(async (resolve, reject) => {\n const state = this._store.getState();\n const { config: { testMode } } = state.paymentMethods.getPaymentMethodOrThrow(methodId, gatewayId);\n try {\n const createSquareForm = await this._scriptLoader.load(testMode);\n\n this._paymentForm = createSquareForm(\n this._getFormOptions({ resolve, reject })\n );\n\n this._getPaymentForm().build();\n } catch (e: unknown) {\n reject(new PaymentMethodClientUnavailableError());\n }\n }).then(() => this._store.getState());\n }\n\n async execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment } = orderRequest;\n if (!payment || !payment.methodId) {\n throw new InvalidArgumentError('Unable to submit payment because \"payload.payment.methodId\" argument is not provided.');\n }\n\n this._syncPaymentMethod(payment.methodId);\n\n const paymentData = await this._getNonceInstrument(payment.methodId);\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(omit(orderRequest, 'payment'), options));\n await this._store.dispatch(this._paymentActionCreator.submitPayment({ ...payment, paymentData}));\n\n return this._store.getState();\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n private _syncPaymentMethod(methodId: string): void {\n const state = this._store.getState();\n this._paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n if (!this._paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n }\n\n private _getCountryCode(countryName: string) {\n switch (countryName.toUpperCase()) {\n case 'NEW ZELAND':\n return 'NZ';\n case 'AUSTRALIA':\n return 'AU';\n default:\n return 'US';\n }\n }\n\n private _getNonceInstrument(methodId: string): Promise {\n const state = this._store.getState();\n const paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n if (paymentMethod) {\n const { initializationData } = paymentMethod;\n if (initializationData && initializationData.paymentData.nonce) {\n return Promise.resolve({ nonce: paymentMethod.initializationData.paymentData.nonce });\n }\n }\n\n return new Promise((resolve, reject?) => {\n if (this._deferredRequestNonce) {\n this._deferredRequestNonce.reject(new TimeoutError());\n }\n\n this._deferredRequestNonce = { resolve, reject };\n this._getPaymentForm().requestCardNonce();\n });\n }\n\n private _getFormOptions(deferred: DeferredPromise): SquareFormOptions {\n return {\n ...this._getInitializeOptions(),\n ...this._paymentMethod?.initializationData,\n callbacks: {\n cardNonceResponseReceived: (errors, nonce, cardData, billingContact, shippingContact) => {\n const deferredRequest = this._getDeferredRequestNonce();\n const { onError = noop } = this._getInitializeOptions();\n\n if (!nonce) {\n onError(errors);\n\n return deferredRequest.reject(get(errors, '0', {}));\n }\n\n if (cardData && cardData.digital_wallet_type !== DigitalWalletType.none && nonce) {\n this._handleWalletNonceResponse(nonce, cardData, billingContact, shippingContact);\n } else {\n if (this._is3DSExperimentOn()) {\n this._getPaymentForm().verifyBuyer(\n nonce,\n this._getVerificationDetails(),\n (error: SquareVerificationError, verificationResults: SquareVerificationResult) => {\n\n if (!isEmpty(error)) {\n onError(error);\n\n return deferredRequest.reject(get(error, '0', {}));\n }\n\n deferredRequest.resolve({ nonce: JSON.stringify({ nonce, token: verificationResults.token }) });\n }\n );\n } else {\n deferredRequest.resolve({ nonce });\n }\n }\n },\n createPaymentRequest: this._paymentRequestPayload.bind(this),\n paymentFormLoaded: () => {\n deferred.resolve();\n this._setPostalCode();\n },\n unsupportedBrowserDetected: () => deferred.reject(new UnsupportedBrowserError()),\n },\n };\n }\n\n private _getInitializeOptions(): SquarePaymentInitializeOptions {\n if (!this._squareOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._squareOptions;\n }\n\n private _handleWalletNonceResponse(\n nonce?: string,\n cardData?: CardData,\n billingContact?: Contact,\n shippingContact?: Contact\n ): void {\n const { onError = noop, onPaymentSelect = noop } = this._getInitializeOptions();\n\n if (nonce && this._paymentMethod) {\n this._paymentInstrumentSelected(\n this._paymentMethod.id,\n nonce,\n cardData,\n billingContact,\n shippingContact\n )\n .then(onPaymentSelect)\n .catch(onError);\n }\n }\n\n private _paymentInstrumentSelected(\n methodId: string,\n nonce?: string,\n cardData?: CardData,\n billingContact?: Contact,\n shippingContact?: Contact): Promise {\n\n return this._store.dispatch(this._paymentStrategyActionCreator.widgetInteraction(() => {\n return this._setExternalCheckoutData(nonce, cardData, billingContact, shippingContact)\n .then(() =>\n Promise.all([\n this._store.dispatch(this._checkoutActionCreator.loadCurrentCheckout()),\n this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId)),\n ]));\n }, { methodId }), { queueId: 'widgetInteraction' });\n }\n\n private _paymentRequestPayload(): SquarePaymentRequest {\n const state = this._store.getState();\n const checkout = state.checkout.getCheckout();\n const storeConfig = state.config.getStoreConfigOrThrow();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n return {\n requestShippingAddress: true,\n requestBillingInfo: true,\n currencyCode: storeConfig.currency.code,\n countryCode: this._getCountryCode(storeConfig.storeProfile.storeCountry),\n total: {\n label: storeConfig.storeProfile.storeName,\n amount: String(checkout.subtotal),\n pending: false,\n },\n };\n }\n\n private _setExternalCheckoutData(nonce?: string, cardData?: CardData, billingContact?: Contact, shippingContact?: Contact): Promise> {\n return this._requestSender.post('/checkout.php', {\n headers: {\n Accept: 'text/html',\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...SDK_VERSION_HEADERS,\n },\n body: {\n nonce,\n provider: 'squarev2',\n action: 'set_external_checkout',\n cardData: JSON.stringify(cardData),\n billingContact: JSON.stringify(billingContact),\n shippingContact: JSON.stringify(shippingContact),\n },\n });\n }\n\n private _setPostalCode(): void {\n const state = this._store.getState();\n const billingAddress = state.billingAddress.getBillingAddress();\n\n if (billingAddress && billingAddress.postalCode) {\n this._getPaymentForm().setPostalCode(billingAddress.postalCode);\n }\n }\n\n private _getBillingContact(): Contact {\n const state = this._store.getState();\n const billingAddress = state.billingAddress.getBillingAddressOrThrow();\n\n return {\n givenName: billingAddress.firstName,\n familyName: billingAddress.lastName,\n email: billingAddress.email || '',\n country: billingAddress.countryCode,\n countryName: billingAddress.country,\n region: '',\n city: billingAddress.city,\n postalCode: billingAddress.postalCode,\n addressLines: [ billingAddress.address1, billingAddress.address2],\n phone: billingAddress.phone,\n };\n }\n\n private _getAmountAndCurrencyCode(): string[] {\n const state = this._store.getState();\n const cart = state.cart.getCartOrThrow();\n const checkout = state.checkout.getCheckoutOrThrow();\n\n return [String(checkout.grandTotal), cart.currency.code];\n }\n\n private _getVerificationDetails(): VerificationDetails {\n const billingContact = this._getBillingContact();\n const [ amount, currencyCode ] = this._getAmountAndCurrencyCode();\n\n return {\n intent: SquareIntent.CHARGE,\n currencyCode,\n amount,\n billingContact,\n };\n }\n\n private _getDeferredRequestNonce(): DeferredPromise {\n if (!this._deferredRequestNonce) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._deferredRequestNonce;\n }\n\n private _getPaymentForm(): SquarePaymentForm {\n if (!this._paymentForm) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._paymentForm;\n }\n\n private _is3DSExperimentOn(): boolean {\n const state = this._store.getState();\n const storeConfig = state.config.getStoreConfigOrThrow();\n\n return storeConfig.checkoutSettings.features['PROJECT-3828.add_3ds_support_on_squarev2'] === true;\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport SquarePaymentForm, { SquareFormOptions, SquareScriptCallBack } from './square-form';\nimport SquareWindow from './square-window';\n\nexport default class SquareScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, private _window: Window = window) {}\n\n _isSquareWindow(window: Window): window is SquareWindow {\n const squareWindow: SquareWindow = window as SquareWindow;\n\n return !!squareWindow.SqPaymentForm;\n }\n\n async load(testmode?: boolean): Promise {\n await this._scriptLoader.loadScript(\n testmode\n ? '//js.squareupsandbox.com/v2/paymentform'\n : '//js.squareup.com/v2/paymentform',\n );\n\n return (options: SquareFormOptions): SquarePaymentForm => {\n if (!this._isSquareWindow(this._window)) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return new this._window.SqPaymentForm(options);\n };\n }\n}\n","export const supportedLocales: { [language: string]: string[] } = {\n ar: ['ar'],\n bg: ['bg'],\n cs: ['cs'],\n da: ['da'],\n de: ['de'],\n el: ['el'],\n en: ['en', 'en-GB'],\n es: ['es', 'es-419'],\n et: ['et'],\n fi: ['fi'],\n fil: ['fil'],\n fr: ['fr', 'fr-CA'],\n he: ['he'],\n hr: ['hr'],\n hu: ['hu'],\n id: ['id'],\n it: ['it'],\n ja: ['ja'],\n ko: ['ko'],\n lt: ['lt'],\n lv: ['lv'],\n ms: ['ms'],\n mt: ['mt'],\n nb: ['nb'],\n nl: ['nl'],\n pl: ['pl'],\n pt: ['pt', 'pt-BR'],\n ro: ['ro'],\n ru: ['ru'],\n sk: ['sk'],\n sl: ['sl'],\n sv: ['sv'],\n th: ['th'],\n tr: ['tr'],\n vi: ['vi'],\n zh: ['zh', 'zh-HK', 'zh-TW'],\n};\n","import { supportedLocales } from './stripe-upe-supported-locales';\n\nexport default function formatLocale(localeLanguage: string): string {\n const [language, country] = localeLanguage.replace(/_/g, '-').toLowerCase().split('-');\n const countryLocales = supportedLocales[language];\n\n if (!countryLocales) {\n return 'auto';\n }\n\n const formattedLocale = country ? `${language}-${country.toUpperCase()}` : language;\n\n return countryLocales.indexOf(formattedLocale) > -1 ? formattedLocale : countryLocales[0];\n}\n","import { includes, some } from 'lodash';\n\nimport { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { isHostedInstrumentLike } from '../..';\nimport { Address } from '../../../address';\nimport { BillingAddressActionCreator } from '../../../billing';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { StoreCreditActionCreator } from '../../../store-credit';\nimport { PaymentArgumentInvalidError, PaymentMethodCancelledError } from '../../errors';\nimport isVaultedInstrument from '../../is-vaulted-instrument';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport formatLocale from './format-locale';\nimport {\n AddressOptions,\n StripeConfirmPaymentData,\n StripeElement,\n StripeElements,\n StripeElementType,\n StripeError,\n StripePaymentMethodType,\n StripeStringConstants,\n StripeUPEAppearanceOptions,\n StripeUPEClient,\n} from './stripe-upe';\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\n\nimport { StripeUPEPaymentInitializeOptions } from './';\n\nconst APM_REDIRECT = [\n StripePaymentMethodType.SOFORT,\n StripePaymentMethodType.EPS,\n StripePaymentMethodType.GRABPAY,\n StripePaymentMethodType.BANCONTACT,\n StripePaymentMethodType.IDEAL,\n StripePaymentMethodType.GIROPAY,\n StripePaymentMethodType.ALIPAY,\n StripePaymentMethodType.KLARNA,\n];\n\nexport default class StripeUPEPaymentStrategy implements PaymentStrategy {\n private _stripeUPEClient?: StripeUPEClient;\n private _stripeElements?: StripeElements;\n private _isMounted = false;\n private _unsubscribe?: () => void;\n private _isDeinitialize?: boolean;\n\n constructor(\n private _store: CheckoutStore,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _orderActionCreator: OrderActionCreator,\n private _stripeScriptLoader: StripeUPEScriptLoader,\n private _storeCreditActionCreator: StoreCreditActionCreator,\n private _billingAddressActionCreator: BillingAddressActionCreator,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const { stripeupe, methodId, gatewayId } = options;\n\n if (!stripeupe?.containerId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"gatewayId\" argument is not provided.',\n );\n }\n\n this._isDeinitialize = false;\n\n this._loadStripeElement(stripeupe, gatewayId, methodId).catch((error) =>\n stripeupe.onError?.(error),\n );\n\n this._unsubscribe = await this._store.subscribe(\n async (_state) => {\n const payment = this._stripeElements?.getElement(StripeElementType.PAYMENT);\n\n if (payment) {\n let error;\n\n await this._store\n .dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n }),\n )\n .catch((err) => (error = err));\n\n if (error) {\n if (this._isMounted) {\n payment.unmount();\n this._isMounted = false;\n }\n\n stripeupe.onError?.(error);\n } else if (!this._isMounted) {\n await this._stripeElements?.fetchUpdates();\n payment.mount(`#${stripeupe.containerId}`);\n this._isMounted = true;\n }\n }\n },\n (state) => {\n const checkout = state.checkout.getCheckout();\n\n return checkout && checkout.outstandingBalance;\n },\n (state) => {\n const checkout = state.checkout.getCheckout();\n\n return checkout && checkout.coupons;\n },\n );\n\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n orderRequest: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment || !payment.paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n if (!this._stripeUPEClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { paymentData, methodId, gatewayId } = payment;\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n const { isStoreCreditApplied: useStoreCredit } = this._store\n .getState()\n .checkout.getCheckoutOrThrow();\n\n if (useStoreCredit) {\n await this._store.dispatch(\n this._storeCreditActionCreator.applyStoreCredit(useStoreCredit),\n );\n }\n\n if (gatewayId) {\n const {\n customer: { getCustomerOrThrow },\n } = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n }),\n );\n const { email, isStripeLinkAuthenticated } = getCustomerOrThrow();\n\n if (isStripeLinkAuthenticated !== undefined && !email) {\n const billingAddress = this._store\n .getState()\n .billingAddress.getBillingAddressOrThrow();\n\n await this._store.dispatch(\n this._billingAddressActionCreator.updateAddress(billingAddress),\n );\n }\n }\n\n if (isVaultedInstrument(paymentData)) {\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n const { instrumentId } = paymentData;\n\n return this._executeWithVaulted(\n payment.methodId,\n instrumentId,\n shouldSetAsDefaultInstrument,\n );\n }\n\n if (includes(APM_REDIRECT, methodId)) {\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n return this._executeWithAPM(payment.methodId);\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n return this._executeWithoutRedirect(\n payment.methodId,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n if (this._unsubscribe) {\n this._unsubscribe();\n }\n\n this._stripeElements?.getElement(StripeElementType.PAYMENT)?.unmount();\n this._isMounted = false;\n this._isDeinitialize = true;\n\n return Promise.resolve(this._store.getState());\n }\n\n private _isCancellationError(stripeError: StripeError | undefined) {\n return (\n stripeError &&\n stripeError.payment_intent.last_payment_error?.message?.indexOf('canceled') !== -1\n );\n }\n\n private _throwDisplayableStripeError(stripeError: StripeError) {\n if (\n includes(['card_error', 'invalid_request_error', 'validation_error'], stripeError.type)\n ) {\n throw new Error(stripeError.message);\n }\n }\n\n private async _executeWithAPM(methodId: string): Promise {\n const paymentMethod = this._store\n .getState()\n .paymentMethods.getPaymentMethodOrThrow(methodId);\n const paymentPayload = {\n methodId,\n paymentData: {\n formattedPayload: {\n credit_card_token: { token: paymentMethod.clientToken },\n vault_payment_instrument: false,\n confirm: false,\n set_as_default_stored_instrument: false,\n },\n },\n };\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentPayload),\n );\n } catch (error) {\n return await this._processAdditionalAction(error);\n }\n }\n\n private async _executeWithoutRedirect(\n methodId: string,\n shouldSaveInstrument: boolean,\n shouldSetAsDefaultInstrument: boolean,\n ): Promise {\n const paymentMethod = this._store\n .getState()\n .paymentMethods.getPaymentMethodOrThrow(methodId);\n const paymentPayload = {\n methodId,\n paymentData: {\n formattedPayload: {\n credit_card_token: { token: paymentMethod.clientToken },\n vault_payment_instrument: shouldSaveInstrument,\n confirm: false,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n },\n },\n };\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentPayload),\n );\n } catch (error) {\n return await this._processAdditionalAction(\n error,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n methodId,\n );\n }\n }\n\n private async _executeWithVaulted(\n methodId: string,\n token: string,\n shouldSetAsDefaultInstrument: boolean,\n ): Promise {\n const paymentMethod = this._store\n .getState()\n .paymentMethods.getPaymentMethodOrThrow(methodId);\n\n try {\n const paymentPayload = {\n methodId,\n paymentData: {\n formattedPayload: {\n bigpay_token: { token },\n confirm: false,\n client_token: paymentMethod.clientToken,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n },\n },\n };\n\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentPayload),\n );\n } catch (error) {\n return await this._processVaultedAdditionalAction(\n error,\n methodId,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n private async _loadStripeElement(\n stripeupe: StripeUPEPaymentInitializeOptions,\n gatewayId: string,\n methodId: string,\n ) {\n const { containerId, style, render } = stripeupe;\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n }),\n );\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n const {\n initializationData: { stripePublishableKey, stripeConnectedAccount, shopperLanguage },\n } = paymentMethod;\n\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._stripeUPEClient = await this._loadStripeJs(\n stripePublishableKey,\n stripeConnectedAccount,\n );\n\n let appearance: StripeUPEAppearanceOptions | undefined;\n\n if (style) {\n const styles = style;\n\n appearance = {\n variables: {\n colorPrimary: styles.fieldInnerShadow,\n colorBackground: styles.fieldBackground,\n colorText: styles.labelText,\n colorDanger: styles.fieldErrorText,\n colorTextSecondary: styles.labelText,\n colorTextPlaceholder: styles.fieldPlaceholderText,\n colorIcon: styles.fieldPlaceholderText,\n },\n rules: {\n '.Input': {\n borderColor: styles.fieldBorder,\n color: styles.fieldText,\n boxShadow: styles.fieldInnerShadow,\n },\n },\n };\n }\n\n this._stripeElements = this._stripeScriptLoader.getElements(this._stripeUPEClient, {\n clientSecret: paymentMethod.clientToken,\n locale: formatLocale(shopperLanguage),\n appearance,\n });\n\n const {\n billingAddress: { getBillingAddress },\n shippingAddress: { getShippingAddress },\n } = state;\n const { postalCode } = getShippingAddress() || getBillingAddress() || {};\n\n const stripeElement: StripeElement =\n this._stripeElements.getElement(StripeElementType.PAYMENT) ||\n this._stripeElements.create(StripeElementType.PAYMENT, {\n fields: {\n billingDetails: {\n email: StripeStringConstants.NEVER,\n address: {\n country: StripeStringConstants.NEVER,\n city: StripeStringConstants.NEVER,\n postalCode: postalCode\n ? StripeStringConstants.NEVER\n : StripeStringConstants.AUTO,\n },\n },\n },\n wallets: {\n applePay: StripeStringConstants.NEVER,\n googlePay: StripeStringConstants.NEVER,\n },\n });\n\n try {\n stripeElement.mount(`#${containerId}`);\n this._isMounted = true;\n } catch (error) {\n if (!this._isDeinitialize) {\n throw new InvalidArgumentError(\n 'Unable to mount Stripe component without valid container ID.',\n );\n }\n }\n\n stripeElement.on('ready', () => {\n render();\n });\n }\n\n private async _processAdditionalAction(\n error: Error,\n shouldSaveInstrument = false,\n shouldSetAsDefaultInstrument = false,\n methodId?: string,\n ): Promise {\n if (!(error instanceof RequestError)) {\n throw error;\n }\n\n if (!this._stripeUPEClient || !this._stripeElements) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (some(error.body.errors, { code: 'additional_action_required' })) {\n const {\n type,\n data: { token, redirect_url },\n } = error.body.additional_action_required;\n\n if (type === 'redirect_to_url' && redirect_url) {\n const { paymentIntent, error: stripeError } =\n await this._stripeUPEClient.confirmPayment(\n this._mapStripePaymentData(redirect_url),\n );\n\n if (stripeError) {\n this._throwDisplayableStripeError(stripeError);\n throw new PaymentMethodFailedError();\n }\n\n if (!paymentIntent) {\n throw new RequestError();\n }\n } else if (methodId && type === 'additional_action_requires_payment_method' && token) {\n let result;\n let catchedConfirmError = false;\n const stripePaymentData = this._mapStripePaymentData();\n\n try {\n result = await this._stripeUPEClient.confirmPayment(stripePaymentData);\n } catch (error) {\n try {\n result = await this._stripeUPEClient.retrievePaymentIntent(token);\n } catch (error) {\n catchedConfirmError = true;\n }\n }\n\n if (result?.error) {\n this._throwDisplayableStripeError(result.error);\n\n if (this._isCancellationError(result.error)) {\n throw new PaymentMethodCancelledError();\n }\n\n throw new PaymentMethodFailedError();\n }\n\n if (!result?.paymentIntent && !catchedConfirmError) {\n throw new RequestError();\n }\n\n const paymentPayload = {\n methodId,\n paymentData: {\n formattedPayload: {\n credit_card_token: {\n token: catchedConfirmError ? token : result?.paymentIntent?.id,\n },\n confirm: false,\n vault_payment_instrument: shouldSaveInstrument,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n },\n },\n };\n\n return this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentPayload),\n );\n }\n }\n\n throw error;\n }\n\n private async _processVaultedAdditionalAction(\n error: Error,\n methodId?: string,\n shouldSetAsDefaultInstrument = false,\n ): Promise {\n if (!(error instanceof RequestError)) {\n throw error;\n }\n\n if (!this._stripeUPEClient || !this._stripeElements) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (some(error.body.errors, { code: 'three_d_secure_required' }) && methodId) {\n const clientSecret = error.body.three_ds_result.token;\n let result;\n let catchedConfirmError = false;\n\n try {\n result = await this._stripeUPEClient.confirmCardPayment(clientSecret);\n } catch (error) {\n try {\n result = await this._stripeUPEClient.retrievePaymentIntent(clientSecret);\n } catch (error) {\n catchedConfirmError = true;\n }\n }\n\n if (result?.error) {\n this._throwDisplayableStripeError(result.error);\n\n if (this._isCancellationError(result.error)) {\n throw new PaymentMethodCancelledError();\n }\n\n throw new PaymentMethodFailedError();\n }\n\n if (!result?.paymentIntent && !catchedConfirmError) {\n throw new RequestError();\n }\n\n const paymentPayload = {\n methodId,\n paymentData: {\n formattedPayload: {\n credit_card_token: {\n token: catchedConfirmError ? clientSecret : result?.paymentIntent?.id,\n },\n confirm: false,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n },\n },\n };\n\n return this._store.dispatch(this._paymentActionCreator.submitPayment(paymentPayload));\n }\n\n throw error;\n }\n\n private _mapStripeAddress(address?: Address): AddressOptions {\n if (address) {\n const { city, countryCode: country, postalCode } = address;\n\n return { city, country, postal_code: postalCode };\n }\n\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n\n private _mapStripePaymentData(returnUrl?: string): StripeConfirmPaymentData {\n const billingAddress = this._store.getState().billingAddress.getBillingAddress();\n const address = this._mapStripeAddress(billingAddress);\n\n const email = billingAddress?.email;\n\n if (!this._stripeElements) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!email || !address || !address.city || !address.country) {\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n\n return {\n elements: this._stripeElements,\n redirect: StripeStringConstants.IF_REQUIRED,\n confirmParams: {\n payment_method_data: {\n billing_details: {\n email,\n address,\n },\n },\n ...(returnUrl && { return_url: returnUrl }),\n },\n };\n }\n\n private async _loadStripeJs(\n stripePublishableKey: string,\n stripeConnectedAccount: string,\n ): Promise {\n if (this._stripeUPEClient) {\n return this._stripeUPEClient;\n }\n\n return this._stripeScriptLoader.getStripeClient(\n stripePublishableKey,\n stripeConnectedAccount,\n );\n }\n}\n","interface BaseElementOptions {\n /**\n * Customize the appearance of an element using CSS properties passed in a [Style](https://stripe.com/docs/js/appendix/style) object,\n * which consists of CSS properties nested under objects for each variant.\n */\n style?: StripeElementStyle;\n\n /**\n * Set custom class names on the container DOM element when the Stripe element is in a particular state.\n */\n classes?: StripeElementClasses;\n\n /**\n * Applies a disabled state to the Element such that user input is not accepted. Default is false.\n */\n disabled?: boolean;\n}\n\nexport interface CreatePaymentMethodCardData extends PaymentMethodCreateParams {\n card?: StripeElement;\n}\n\nexport interface CreatePaymentMethodIdealData extends PaymentMethodCreateParams {\n ideal?: StripeElement;\n}\n\nexport interface CreatePaymentMethodSepaData extends PaymentMethodCreateParams {\n sepa_debit?: StripeElement;\n}\n\n/**\n * The PaymentIntent object.\n */\nexport interface PaymentIntent {\n /**\n * Unique identifier for the object.\n */\n id: string;\n\n /**\n * Status of this PaymentIntent. Read more about each PaymentIntent [status](https://stripe.com/docs/payments/intents#intent-statuses).\n */\n status: 'succeeded' | string;\n\n /**\n * The payment error encountered in the previous PaymentIntent confirmation. It will be cleared if the PaymentIntent is later updated for any reason.\n */\n last_payment_error: LastPaymentError | null;\n}\n\n/**\n * The payment error encountered in the previous PaymentIntent confirmation. It will be cleared if the PaymentIntent is later updated for any reason.\n */\nexport interface LastPaymentError {\n /**\n * A human-readable message providing more details about the error. For card errors, these messages can be shown to your users.\n */\n message?: string;\n}\n\n/**\n * The PaymentMethod object\n */\nexport interface PaymentMethod {\n /**\n * Unique identifier for the object.\n */\n id: string;\n\n /**\n * The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value.\n * It contains additional information specific to the PaymentMethod type.\n */\n type: string;\n}\n\nexport interface PaymentMethodCreateParams {\n /**\n * Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods.\n */\n billing_details?: StripeBillingDetails;\n}\n\nexport interface StripeError {\n /**\n * A human-readable message providing more details about the error. For card errors, these messages can be shown to your users.\n */\n message?: string;\n\n /**\n * The PaymentIntent object.\n */\n payment_intent: PaymentIntent;\n\n /**\n * A human-readable code for the error obtained\n */\n code?: string;\n}\n\n/**\n * CSS properties supported by Stripe.js.\n */\ninterface StripeElementCSSProperties {\n /**\n * The [background-color](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color) CSS property.\n *\n * This property works best with the `::selection` pseudo-class.\n * In other cases, consider setting the background color on the element's container instaed.\n */\n backgroundColor?: string;\n\n /**\n * The [color](https://developer.mozilla.org/en-US/docs/Web/CSS/color) CSS property.\n */\n color?: string;\n\n /**\n * The [font-family](https://developer.mozilla.org/en-US/docs/Web/CSS/font-family) CSS property.\n */\n fontFamily?: string;\n\n /**\n * The [font-size](https://developer.mozilla.org/en-US/docs/Web/CSS/font-size) CSS property.\n */\n fontSize?: string;\n\n /**\n * The [font-smoothing](https://developer.mozilla.org/en-US/docs/Web/CSS/font-smoothing) CSS property.\n */\n fontSmoothing?: string;\n\n /**\n * The [font-style](https://developer.mozilla.org/en-US/docs/Web/CSS/font-style) CSS property.\n */\n fontStyle?: string;\n\n /**\n * The [font-variant](https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant) CSS property.\n */\n fontVariant?: string;\n\n /**\n * The [font-weight](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight) CSS property.\n */\n fontWeight?: string;\n\n /**\n * A custom property, used to set the color of the icons that are rendered in an element.\n */\n iconColor?: string;\n\n /**\n * The [line-height](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height) CSS property.\n *\n * To avoid cursors being rendered inconsistently across browsers, consider using a padding on the element's container instead.\n */\n lineHeight?: string;\n\n /**\n * The [letter-spacing](https://developer.mozilla.org/en-US/docs/Web/CSS/letter-spacing) CSS property.\n */\n letterSpacing?: string;\n\n /**\n * The [text-align](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) CSS property.\n *\n * Available for the `cardNumber`, `cardExpiry`, and `cardCvc` elements.\n */\n textAlign?: string;\n\n /**\n * The [padding](https://developer.mozilla.org/en-US/docs/Web/CSS/padding) CSS property.\n *\n * Available for the `idealBank` element.\n * Accepts integer `px` values.\n */\n padding?: string;\n\n /**\n * The [text-decoration](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration) CSS property.\n */\n textDecoration?: string;\n\n /**\n * The [text-shadow](https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow) CSS property.\n */\n textShadow?: string;\n\n /**\n * The [text-transform](https://developer.mozilla.org/en-US/docs/Web/CSS/text-transform) CSS property.\n */\n textTransform?: string;\n}\n\ninterface StripeElementStyleVariant extends StripeElementCSSProperties {\n ':hover'?: StripeElementCSSProperties;\n\n ':focus'?: StripeElementCSSProperties;\n\n '::placeholder'?: StripeElementCSSProperties;\n\n '::selection'?: StripeElementCSSProperties;\n\n ':-webkit-autofill'?: StripeElementCSSProperties;\n\n /**\n * Available for all elements except the `paymentRequestButton` element\n */\n ':disabled'?: StripeElementCSSProperties;\n\n /**\n * Available for the `cardNumber`, `cardExpiry`, and `cardCvc` elements.\n */\n '::-ms-clear'?: StripeElementCSSProperties & { display: string };\n}\n\nexport interface CardElementOptions extends BaseElementOptions {\n /**\n * A pre-filled set of values to include in the input (e.g., {postalCode: '94110'}).\n * Note that sensitive card information (card number, CVC, and expiration date)\n * cannot be pre-filled\n */\n value?: string;\n\n /**\n * Hide the postal code field. Default is false. If you are already collecting a\n * full billing address or postal code elsewhere, set this to true.\n */\n hidePostalCode?: boolean;\n\n /**\n * Appearance of the icon in the Element.\n */\n iconStyle?: IconStyle;\n\n /*\n * Hides the icon in the Element, Default is false\n */\n hideIcon?: boolean;\n}\n\ninterface BaseIndividualElementOptions extends BaseElementOptions {\n containerId: string;\n}\n\nexport interface CardNumberElementOptions extends BaseIndividualElementOptions {\n /*\n * Placeholder\n */\n placeholder?: string;\n\n showIcon?: boolean;\n /**\n * Appearance of the icon in the Element. Either `solid` or `default`\n */\n iconStyle?: IconStyle;\n}\n\nexport interface CardExpiryElementOptions extends BaseIndividualElementOptions {\n /*\n * Placeholder\n */\n placeholder?: string;\n}\n\nexport interface CardCvcElementOptions extends BaseIndividualElementOptions {\n /*\n * Placeholder\n */\n placeholder?: string;\n}\n\nexport interface IbanElementOptions extends BaseElementOptions {\n /**\n * Specify the list of countries or country-groups whose IBANs you want to allow.\n * Must be ['SEPA'].\n */\n supportedCountries?: string[];\n\n /**\n * Customize the country and format of the placeholder IBAN. Default is DE.\n */\n placeholderCountry?: string;\n\n /**\n * Appearance of the icon in the Element.\n */\n iconStyle?: IconStyle;\n}\n\nexport interface IdealElementOptions extends BaseElementOptions {\n value?: string;\n\n /**\n * Hides the icon in the Element. Default is false.\n */\n hideIcon?: boolean;\n}\n\nexport interface ZipCodeElementOptions {\n containerId: string;\n}\n\nexport enum IconStyle {\n Solid = 'solid',\n Default = 'default',\n}\n\nexport interface StripeElementStyle {\n /**\n * Base variant—all other variants inherit from these styles.\n */\n base?: StripeElementStyleVariant;\n\n /**\n * Applied when the element has valid input.\n */\n complete?: StripeElementStyleVariant;\n\n /**\n * Applied when the element has no customer input.\n */\n empty?: StripeElementStyleVariant;\n\n /**\n * Applied when the element has invalid input.\n */\n invalid?: StripeElementStyleVariant;\n}\n\nexport interface StripeElementClasses {\n /**\n * The base class applied to the container. Defaults to StripeElement.\n */\n base?: string;\n\n /**\n * The class name to apply when the Element is complete. Defaults to StripeElement--complete.\n */\n complete?: string;\n\n /**\n * The class name to apply when the Element is empty. Defaults to StripeElement--empty.\n */\n empty?: string;\n\n /**\n * The class name to apply when the Element is focused. Defaults to StripeElement--focus.\n */\n focus?: string;\n\n /**\n * The class name to apply when the Element is invalid. Defaults to StripeElement--invalid.\n */\n invalid?: string;\n\n /**\n * The class name to apply when the Element has its value autofilled by the browser\n * (only on Chrome and Safari). Defaults to StripeElement--webkit-autofill.\n */\n webkitAutoFill?: string;\n}\n\nexport interface StripeAddress {\n /**\n * City, district, suburb, town, or village.\n */\n city?: string;\n\n /**\n * Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)).\n */\n country?: string;\n\n /**\n * Address line 1 (e.g., street, PO Box, or company name).\n */\n line1: string;\n\n /**\n * Address line 2 (e.g., apartment, suite, unit, or building).\n */\n line2?: string;\n\n /**\n * ZIP or postal code.\n */\n postal_code?: string;\n\n /**\n * State, county, province, or region.\n */\n state?: string;\n}\n\nexport interface StripeBillingDetails {\n /**\n * Billing address.\n */\n address?: StripeAddress;\n\n /**\n * Email address.\n */\n email?: string;\n\n /**\n * Full name.\n */\n name?: string;\n\n /**\n * Billing phone number (including extension).\n */\n phone?: string;\n}\n\nexport interface StripeShippingAddress {\n /**\n * Shipping Address\n */\n address: StripeAddress;\n\n /**\n * Recipient name\n */\n name: string;\n\n /**\n * The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc.\n */\n carrier?: string;\n\n /**\n * Recipient phone (including extension).\n */\n phone?: string;\n\n /**\n * The tracking number for a physical product, obtained from the delivery service.\n * If multiple tracking numbers were generated for this purchase, please separate them with commas.\n */\n tracking_number?: string;\n}\n\n/**\n * Data to be sent with a `stripe.confirmAlipayPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.\n */\nexport interface StripeConfirmAlipayPaymentData {\n /**\n * If you are [handling next actions yourself](https://stripe.com/docs/payments/payment-intents/verifying-status#next-actions), pass in a return_url. If the subsequent action\n * is redirect_to_url, this URL will be used on the return path for the redirect.\n *\n * @recommended\n */\n return_url?: string;\n}\n\n/**\n * Data to be sent with a `stripe.confirmCardPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.\n */\nexport interface StripeConfirmCardPaymentData {\n /*\n * Either the id of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a\n * PaymentMethod with. See the use case sections below for details.\n *\n * @recommended\n */\n payment_method?: CreatePaymentMethodCardData;\n\n /**\n * The [shipping details](https://stripe.com/docs/api/payment_intents/confirm#confirm_payment_intent-shipping) for the payment, if collected.\n *\n * @recommended\n */\n shipping?: StripeShippingAddress;\n\n /**\n * If you are [handling next actions yourself](https://stripe.com/docs/payments/payment-intents/verifying-status#next-actions), pass in a return_url. If the subsequent action\n * is redirect_to_url, this URL will be used on the return path for the redirect.\n *\n * @recommended\n */\n return_url?: string;\n\n /**\n * Indicates that you intend to make future payments with this PaymentIntent's payment method.\n *\n * If present, the payment method used with this PaymentIntent can be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer, even after the transaction completes.\n *\n * Use `on_session` if you intend to only reuse the payment method when your customer is present in your checkout flow. Use `off_session` if your customer may or may not be in your checkout flow.\n */\n setup_future_usage?: 'off_session' | 'on_session' | null;\n}\n\n/**\n * Data to be sent with a `stripe.confirmIdealPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.\n */\nexport interface StripeConfirmIdealPaymentData {\n /*\n * Either the id of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a\n * PaymentMethod with. See the use case sections below for details.\n *\n * @recommended\n */\n payment_method?: CreatePaymentMethodIdealData;\n\n /**\n * If you are [handling next actions yourself](https://stripe.com/docs/payments/payment-intents/verifying-status#next-actions), pass in a return_url. If the subsequent action\n * is redirect_to_url, this URL will be used on the return path for the redirect.\n *\n * @recommended\n */\n return_url?: string;\n}\n\n/**\n * Data to be sent with a `stripe.confirmSEPAPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.\n */\nexport interface StripeConfirmSepaPaymentData {\n /*\n * Either the id of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a\n * PaymentMethod with. See the use case sections below for details.\n *\n * @recommended\n */\n payment_method?: CreatePaymentMethodSepaData;\n}\n\nexport type StripeConfirmPaymentData =\n | StripeConfirmAlipayPaymentData\n | StripeConfirmCardPaymentData\n | StripeConfirmIdealPaymentData\n | StripeConfirmSepaPaymentData\n | undefined;\n\nexport type StripeElementOptions =\n | CardElementOptions\n | CardExpiryElementOptions\n | CardNumberElementOptions\n | CardCvcElementOptions\n | IdealElementOptions\n | IbanElementOptions\n | ZipCodeElementOptions;\n\nexport interface StripeElement {\n /**\n * The `element.mount` method attaches your element to the DOM.\n */\n mount(domElement: string | HTMLElement): void;\n\n /**\n * Removes the element from the DOM and destroys it.\n * A destroyed element can not be re-activated or re-mounted to the DOM.\n */\n destroy(): void;\n\n /**\n * Unmounts the element from the DOM.\n * Call `element.mount` to re-attach it to the DOM.\n */\n unmount(): void;\n}\n\nexport interface StripeElements {\n /**\n * Creates a `AlipayElement` | `CardElement` | `CardCvcElement` |`CardExpiryElement` | `CardExpiryElement` | `CardNumberElement` | `IdealBankElement` | `IbanElement`.\n */\n create(elementType: StripeElementType, options?: StripeElementOptions): StripeElement;\n\n /**\n * Looks up a previously created `Element` by its type.\n */\n getElement(elementType: StripeElementType): StripeElement | null;\n}\n\n/**\n * This object is used to pass custom fonts when creating an [Elements](https://stripe.com/docs/js/elements_object/create) object.\n */\nexport interface CssFontSource {\n /**\n * A relative or absolute URL pointing to a CSS file with [@font-face](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face) definitions, for example:\n * `https://fonts.googleapis.com/css?family=Open+Sans`\n * Note that if you are using a [content security policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) (CSP),\n * [additional directives](https://stripe.com/docs/security#content-security-policy) may be necessary.\n */\n cssSrc: string;\n}\n\n/**\n * This object is used to pass custom fonts when creating an [Elements](https://stripe.com/docs/js/elements_object/create) object.\n */\nexport interface CustomFontSource {\n /**\n * The name to give the font.\n */\n family: string;\n\n /**\n * A valid [src](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/src) value pointing to your\n * custom font file. This is usually (though not always) a link to a file with a .woff , .otf, or .svg suffix.\n */\n src: string;\n\n /**\n * A valid [font-display](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display) value.\n */\n display?: string;\n\n /**\n * One of normal, italic, oblique. Defaults to normal.\n */\n style?: string;\n\n /**\n * A valid [unicode-range](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/unicode-range) value.\n */\n unicodeRange?: string;\n\n /**\n * A valid [font-weight](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight). Note that this is a string, not a number.\n */\n weight?: string;\n}\n\nexport type CustomFont = CssFontSource | CustomFontSource;\n\nexport interface StripeElementsOptions {\n /**\n * An array of custom fonts, which elements created from the Elements object can use.\n * Fonts can be specified as [CssFontSource](https://stripe.com/docs/js/appendix/css_font_source_object)\n * or [CustomFontSource](https://stripe.com/docs/js/appendix/custom_font_source_object) objects.\n */\n fonts?: CustomFont[];\n\n /**\n * A [locale](https://stripe.com/docs/js/appendix/supported_locales) to display placeholders and\n * error strings in. Default is auto (Stripe detects the locale of the browser).\n * Setting the locale does not affect the behavior of postal code validation—a valid postal code\n * for the billing country of the card is still required.\n */\n locale?: string;\n}\n\nexport interface StripeConfirmPaymentOptions {\n /**\n * Set this to false if you want to [manually handle the authorization redirect](https://stripe.com/docs/payments/ideal#handle-redirect). Default is true.\n */\n handleActions?: boolean;\n}\n\nexport interface StripeV3Client {\n /**\n * Create an `Elements` instance, which manages a group of elements.\n */\n elements(options?: StripeElementsOptions): StripeElements;\n\n /**\n * @docs https://stripe.com/docs/js/payment_intents/confirm_alipay_payment\n *\n * Use `stripe.confirmAlipayPayment` in the Alipay payment method creation flow when the customer submits your payment form.\n * When called, it will confirm the [PaymentIntent](https://stripe.com/docs/api/payment_intents) with data you provide, and it will automatically\n * redirect the customer to the authorize the transaction. Once authorization is complete, the customer will be redirected\n * back to your specified `return_url`. When you confirm a `PaymentIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods).\n * In addition to confirming the `PaymentIntent`, this method can automatically create and attach a new `PaymentMethod` for you.\n * If you have already attached a `PaymentMethod` you can call this method without needing to provide any additional data.\n * These use cases are detailed in the sections that follow.\n *\n * @returns\n * `stripe.confirmAlipayPayment` by default, will trigger a redirect when successful. If there is an error, or when handling\n * `next_actions` manually by using the `handleActions: false` option, it will return a `Promise` which resolves with a `result` object.\n * This object has either:\n *\n * - result.paymentIntent: the successful PaymentIntent.\n * - result.error: an error. Refer to the API reference for all possible errors.\n *\n * Note that `stripe.confirmAlipayPayment` may take several seconds to complete. During that time, you should disable your\n * form from being resubmitted and show a waiting indicator like a spinner. If you receive an error result, you should\n * be sure to show that error to the customer, re-enable the form, and hide the waiting indicator.\n */\n confirmAlipayPayment(\n /**\n * The [client secret](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-client_secret) of the PaymentIntent.\n */\n clientSecret: string,\n\n /**\n * Data to be sent with the request. Refer to the Payment Intents API for a full list of parameters.\n */\n data?: StripeConfirmAlipayPaymentData,\n\n /**\n * An options object to control the behavior of this method.\n */\n options?: StripeConfirmPaymentOptions,\n ): Promise<{ paymentIntent?: PaymentIntent; error?: StripeError }>;\n\n /**\n * @docs https://stripe.com/docs/js/payment_intents/confirm_card_payment\n *\n * Use `stripe.confirmCardPayment` when the customer submits your payment form.\n * When called, it will confirm the [PaymentIntent](https://stripe.com/docs/api/payment_intents)\n * with `data` you provide and carry out 3DS or other next actions if they are required.\n *\n * If you are using [Dynamic 3D Secure](https://stripe.com/docs/payments/3d-secure#three-ds-radar), `stripe.confirmCardPayment` will\n * trigger your Radar rules to execute and may open a dialog for your customer to authenticate their payment.\n *\n * When you confirm a `PaymentIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods).\n * In addition to confirming the `PaymentIntent`, this method can automatically create and attach a new `PaymentMethod` for you.\n * It can also be called with an existing `PaymentMethod`, or if you have already attached a PaymentMethod you can call this\n * method without needing to provide any additional data. These use cases are detailed in the sections that follow.\n *\n * @returns\n * `stripe.confirmCardPayment` will return a Promise which resolves with a result object.\n * This object has either:\n *\n * - result.paymentIntent: the successful PaymentIntent.\n * - result.error: an error. Refer to the API reference for all possible errors.\n *\n * Note that stripe.confirmCardPayment may take several seconds to complete. During that time, you should disable\n * your form from being resubmitted and show a waiting indicator like a spinner. If you receive an error result,\n * you should be sure to show that error to the customer, re-enable the form, and hide the waiting indicator.\n *\n * Additionally, `stripe.confirmCardPayment may trigger` a [3D Secure](https://stripe.com/docs/payments/3d-secure) authentication\n * challenge. This will be shown in a modal dialog and may be confusing for customers using assistive technologies like\n * screen readers. You should make your form accessible by ensuring that success or error messages are clearly read out\n * after this method completes.\n *\n */\n confirmCardPayment(\n /**\n * The [client secret](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-client_secret) of the PaymentIntent.\n */\n clientSecret: string,\n\n /**\n * Data to be sent with the request. Refer to the Payment Intents API for a full list of parameters.\n */\n data?: StripeConfirmCardPaymentData,\n\n /**\n * An options object to control the behavior of this method.\n */\n options?: StripeConfirmPaymentOptions,\n ): Promise<{ paymentIntent?: PaymentIntent; error?: StripeError }>;\n\n /**\n * @docs https://stripe.com/docs/js/payment_intents/confirm_ideal_payment\n *\n * Use `stripe.confirmIdealPayment` in the [iDEAL Payments with Payment Methods](https://stripe.com/docs/payments/ideal)\n * flow when the customer submits your payment form. When called, it will confirm the `PaymentIntent` with `data` you\n * provide, and it will automatically redirect the customer to the authorize the transaction.\n * Once authorization is complete, the customer will be redirected back to your specified `return_url`.\n *\n * When you confirm a `PaymentIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods).\n * In addition to confirming the `PaymentIntent`, this method can automatically create and attach a new `PaymentMethod` for you.\n * It can also be called with an existing `PaymentMethod`, or if you have already attached a PaymentMethod you can call this\n * method without needing to provide any additional data. These use cases are detailed in the sections that follow.\n *\n * @returns\n * By default, `stripe.confirmIdealPayment` will trigger a redirect when successful. If there is an error, or when handling\n * next actions manually by using the `handleActions: false` option, it will return a `Promise` which resolves with a `result`\n * object. This object has either:\n *\n * - result.paymentIntent: the successful PaymentIntent.\n * - result.error: an error. Refer to the API reference for all possible errors.\n *\n * Note that `stripe.confirmIdealPayment` may take several seconds to complete. During that time, you should disable\n * your form from being resubmitted and show a waiting indicator like a spinner. If you receive an error result,\n * you should be sure to show that error to the customer, re-enable the form, and hide the waiting indicator.\n */\n confirmIdealPayment(\n /**\n * The [client secret](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-client_secret) of the PaymentIntent.\n */\n clientSecret: string,\n\n /**\n * Data to be sent with the request. Refer to the Payment Intents API for a full list of parameters.\n */\n data?: StripeConfirmIdealPaymentData,\n\n /**\n * An options object to control the behavior of this method.\n */\n options?: StripeConfirmPaymentOptions,\n ): Promise<{ paymentIntent?: PaymentIntent; error?: StripeError }>;\n\n /**\n *\n * Use `stripe.confirmSepaDebitPayment` in the [SEPA Direct Debit Payments](https://stripe.com/docs/payments/sepa-debit)\n * with Payment Methods flow when the customer submits your payment form. When called, it will confirm the\n * [PaymentIntent](https://stripe.com/docs/api/payment_intents) with `data` you provide. Note that there are some additional\n * requirements to this flow that are not covered in this reference. Refer to our [integration guide](https://stripe.com/docs/payments/sepa-debit\n * for more details.\n *\n * When you confirm a PaymentIntent, it needs to have an attached PaymentMethod. In addition to confirming the PaymentIntent,\n * this method can automatically create and attach a new PaymentMethod for you. If you have already attached a\n * [PaymentMethod](https://stripe.com/docs/api/payment_methods) you can call this method without needing to provide any additional data.\n * These use cases are detailed in the sections that follow.\n *\n * @docs https://stripe.com/docs/js/payment_intents/confirm_sepa_debit_payment\n */\n confirmSepaDebitPayment(\n /**\n * The [client secret](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-client_secret) of the PaymentIntent.\n */\n clientSecret: string,\n\n /**\n * Data to be sent with the request. Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.\n */\n data?: StripeConfirmSepaPaymentData,\n ): Promise<{ paymentIntent?: PaymentIntent; error?: StripeError }>;\n\n /**\n * Use stripe.createPaymentMethod to convert payment information collected by elements into a PaymentMethod\n * object that you safely pass to your server to use in an API call.\n *\n * @docs https://stripe.com/docs/js/payment_methods/create_payment_method\n *\n * @param type: String, The type of the PaymentMethod to create. Refer to the PaymentMethod API for all possible values.\n * @param card: StripeElement, A card or cardNumber Element.\n * @param billing_details: StripeBillingDetails, Billing information associated with the PaymentMethod that\n * may be used or required by particular types of payment methods.\n */\n createPaymentMethod(\n params: CreatePaymentMethodParams,\n ): Promise<{ paymentMethod?: PaymentMethod; error?: StripeError }>;\n\n /**\n * Use stripe.handleCardAction in the Payment Intents API manual confirmation flow to handle a PaymentIntent\n * with the requires_action status. It will throw an error if the PaymentIntent has a different status.\n *\n * @docs https://stripe.com/docs/js/payment_intents/handle_card_action\n *\n * @param paymentIntentClientSecret: String, The client secret of the PaymentIntent to handle.\n */\n handleCardAction(\n paymentIntentClientSecret: string,\n ): Promise<{ paymentIntent?: PaymentIntent; error?: StripeError }>;\n}\n\nexport interface CreatePaymentMethodParams {\n type: StripePaymentMethodType;\n card: StripeElement;\n billing_details?: StripeBillingDetails;\n}\n\nexport interface StripeHostWindow extends Window {\n Stripe?(stripePublishableKey: string, options?: StripeConfigurationOptions): StripeV3Client;\n}\n\nexport enum StripeElementType {\n Alipay = 'alipay',\n CardCvc = 'cardCvc',\n CardExpiry = 'cardExpiry',\n CardNumber = 'cardNumber',\n CreditCard = 'card',\n IDEAL = 'idealBank',\n Sepa = 'iban',\n}\n\nexport enum StripePaymentMethodType {\n Alipay = 'alipay',\n CreditCard = 'card',\n IDEAL = 'ideal',\n Sepa = 'sepa_debit',\n}\n\n/**\n * Initialization options.\n */\nexport interface StripeConfigurationOptions {\n /**\n * For usage with [Connect](https://stripe.com/docs/connect) only.\n * Specifying a connected account ID (e.g., acct_24BFMpJ1svR5A89k) allows you to perform actions on behalf of that account.\n */\n stripeAccount: string;\n\n /**\n * Override your account's [API version](https://stripe.com/docs/api/versioning)\n */\n apiVersion?: string;\n\n /**\n * A locale used to globally configure localization in Stripe. Setting the locale here will localize error strings for all Stripe.js methods. It will also configure the locale for Elements and Checkout. Default is auto (Stripe detects the locale of the browser).\n * Note that Checkout supports a slightly different set of locales than Stripe.js.\n */\n locale?: string;\n\n betas?: string[];\n}\n\nexport interface StripeAdditionalActionData {\n redirect_url?: string;\n intent?: string;\n}\n\nexport interface StripeAdditionalAction {\n type: string;\n data: StripeAdditionalActionData;\n}\n\nexport interface StripeCardElements {\n [index: number]: StripeElement;\n}\n\nexport interface IndividualCardElementOptions {\n cardCvcElementOptions: CardCvcElementOptions;\n cardExpiryElementOptions: CardExpiryElementOptions;\n cardNumberElementOptions: CardNumberElementOptions;\n zipCodeElementOptions?: ZipCodeElementOptions;\n}\n\nexport default function isIndividualCardElementOptions(\n individualCardElementOptions: unknown,\n): individualCardElementOptions is IndividualCardElementOptions {\n return (\n Boolean(\n (individualCardElementOptions as IndividualCardElementOptions).cardNumberElementOptions,\n ) &&\n Boolean(\n (individualCardElementOptions as IndividualCardElementOptions).cardCvcElementOptions,\n ) &&\n Boolean(\n (individualCardElementOptions as IndividualCardElementOptions).cardExpiryElementOptions,\n )\n );\n}\n","import { StandardError } from '../../../common/error/errors';\n\nexport enum StripeV3ErrorType {\n AuthFailure = 'auth_failure',\n}\n\nexport default class StripeV3Error extends StandardError {\n subtype: string;\n\n constructor(subtype: StripeV3ErrorType) {\n super(getErrorMessage(subtype));\n\n this.type = 'stripev3_error';\n this.subtype = subtype;\n }\n}\n\nfunction getErrorMessage(type: StripeV3ErrorType) {\n switch (type) {\n case StripeV3ErrorType.AuthFailure:\n return `User did not authenticate`;\n\n default:\n return 'There was an error while processing your payment. Please try again or contact us.';\n }\n}\n","import { includes, isEmpty, omitBy, some } from 'lodash';\n\nimport { isHostedInstrumentLike, Payment } from '../..';\nimport { Address } from '../../../address';\nimport { BillingAddress, isBillingAddressLike } from '../../../billing';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { Customer } from '../../../customer';\nimport { HostedForm, HostedFormFactory, HostedFormOptions } from '../../../hosted-form';\nimport { OrderActionCreator, OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { StoreCreditActionCreator } from '../../../store-credit';\nimport { PaymentArgumentInvalidError, PaymentMethodCancelledError } from '../../errors';\nimport isVaultedInstrument from '../../is-vaulted-instrument';\nimport { StripeV3FormattedPayload } from '../../payment';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport isIndividualCardElementOptions, {\n PaymentIntent,\n StripeAdditionalAction,\n StripeAddress,\n StripeBillingDetails,\n StripeCardElements,\n StripeConfirmIdealPaymentData,\n StripeConfirmPaymentData,\n StripeConfirmSepaPaymentData,\n StripeElement,\n StripeElementOptions,\n StripeElements,\n StripeElementType,\n StripeError,\n PaymentMethod as StripePaymentMethod,\n StripePaymentMethodType,\n StripeV3Client,\n} from './stripev3';\nimport StripeV3Error, { StripeV3ErrorType } from './stripev3-error';\nimport StripeV3PaymentInitializeOptions from './stripev3-initialize-options';\nimport StripeV3ScriptLoader from './stripev3-script-loader';\n\nconst APM_REDIRECT = [StripeElementType.Alipay, StripeElementType.IDEAL];\n\nexport default class StripeV3PaymentStrategy implements PaymentStrategy {\n private _initializeOptions?: StripeV3PaymentInitializeOptions;\n private _stripeV3Client?: StripeV3Client;\n private _stripeElements?: StripeElements;\n private _stripeElement?: StripeElement;\n private _stripeCardElements?: StripeCardElements;\n private _useIndividualCardFields?: boolean;\n private _hostedForm?: HostedForm;\n private _isDeinitialize?: boolean;\n\n constructor(\n private _store: CheckoutStore,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _orderActionCreator: OrderActionCreator,\n private _stripeScriptLoader: StripeV3ScriptLoader,\n private _storeCreditActionCreator: StoreCreditActionCreator,\n private _hostedFormFactory: HostedFormFactory,\n private _locale: string,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const { stripev3, methodId, gatewayId } = options;\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"gatewayId\" argument is not provided.',\n );\n }\n\n this._initializeOptions = stripev3;\n this._isDeinitialize = false;\n\n const paymentMethod = this._store\n .getState()\n .paymentMethods.getPaymentMethodOrThrow(methodId);\n const {\n initializationData: {\n stripePublishableKey,\n stripeConnectedAccount,\n useIndividualCardFields,\n },\n } = paymentMethod;\n const form = this._getInitializeOptions().form;\n\n this._useIndividualCardFields = useIndividualCardFields;\n this._stripeV3Client = await this._loadStripeJs(\n stripePublishableKey,\n stripeConnectedAccount,\n );\n\n if (\n this._isCreditCard(methodId) &&\n this._shouldShowTSVHostedForm(methodId, gatewayId) &&\n form\n ) {\n this._hostedForm = await this._mountCardVerificationFields(form);\n } else {\n this._stripeElement = await this._mountCardFields(methodId);\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n orderRequest: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = orderRequest;\n let formattedPayload: StripeV3FormattedPayload;\n let stripeError: StripeError | undefined;\n\n if (!payment || !payment.paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const { paymentData, gatewayId, methodId } = payment;\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = isHostedInstrumentLike(\n paymentData,\n )\n ? paymentData\n : { shouldSaveInstrument: false, shouldSetAsDefaultInstrument: false };\n const shouldSubmitOrderBeforeLoadingAPM = includes(APM_REDIRECT, methodId);\n\n const { isStoreCreditApplied: useStoreCredit } = this._store\n .getState()\n .checkout.getCheckoutOrThrow();\n\n if (useStoreCredit) {\n await this._store.dispatch(\n this._storeCreditActionCreator.applyStoreCredit(useStoreCredit),\n );\n }\n\n try {\n if (shouldSubmitOrderBeforeLoadingAPM) {\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n }\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(`${gatewayId}`, {\n params: { method: methodId },\n }),\n );\n\n if (isVaultedInstrument(paymentData)) {\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n const { instrumentId } = paymentData;\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(\n payment.methodId,\n );\n const clientToken = paymentMethod.clientToken;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n return await this._executeWithVaulted(\n payment,\n instrumentId,\n shouldSetAsDefaultInstrument,\n clientToken,\n );\n }\n\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n const result = await this._confirmStripePayment(paymentMethod);\n const { clientToken, method } = paymentMethod;\n const { id: token } = result.paymentIntent ?? result.paymentMethod ?? { id: '' };\n\n stripeError = result.error;\n\n formattedPayload = {\n credit_card_token: { token },\n vault_payment_instrument: shouldSaveInstrument,\n confirm: false,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n };\n\n if (method === StripeElementType.CreditCard) {\n formattedPayload.client_token = clientToken;\n }\n\n if (!shouldSubmitOrderBeforeLoadingAPM) {\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n }\n\n const paymentPayload = this._buildPaymentPayload(\n methodId,\n formattedPayload,\n shouldSetAsDefaultInstrument,\n );\n\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentPayload),\n );\n } catch (error) {\n return await this._processAdditionalAction(\n this._handleEmptyPaymentIntentError(error, stripeError),\n methodId,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n if (this._hostedForm) {\n this._hostedForm.detach();\n }\n\n this._isDeinitialize = true;\n this._unmountElement();\n\n return Promise.resolve(this._store.getState());\n }\n\n private _buildPaymentPayload(\n methodId: string,\n formattedPayload: StripeV3FormattedPayload,\n shouldSetAsDefaultInstrument: boolean | undefined,\n ): Payment {\n const paymentData = shouldSetAsDefaultInstrument\n ? {\n formattedPayload: {\n ...formattedPayload,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n },\n }\n : { formattedPayload };\n\n return { methodId, paymentData };\n }\n\n private _isCancellationError(stripeError: StripeError | undefined) {\n return (\n stripeError &&\n stripeError.payment_intent.last_payment_error?.message?.indexOf('canceled') !== -1\n );\n }\n\n private _isAuthError(stripeError: StripeError | undefined) {\n return stripeError?.code === 'payment_intent_authentication_failure';\n }\n\n private _isCreditCard(methodId: string): boolean {\n return methodId === StripePaymentMethodType.CreditCard;\n }\n\n private _isHostedFieldAvailable(): boolean {\n const options = this._getInitializeOptions();\n const definedFields = omitBy(options.form?.fields, isEmpty);\n\n return !isEmpty(definedFields);\n }\n\n private _isHostedPaymentFormEnabled(methodId: string, gatewayId?: string): boolean {\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(methodId, gatewayId);\n\n return Boolean(paymentMethod.config.isHostedFormEnabled);\n }\n\n private async _confirmStripePayment(paymentMethod: PaymentMethod): Promise<{\n paymentIntent?: PaymentIntent | undefined;\n paymentMethod?: StripePaymentMethod | undefined;\n error?: StripeError | undefined;\n }> {\n const { clientToken: clientSecret, method, returnUrl } = paymentMethod;\n\n if (!clientSecret) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n switch (method) {\n case StripeElementType.Alipay:\n return this._getStripeJs().confirmAlipayPayment(\n clientSecret,\n { return_url: returnUrl },\n { handleActions: false },\n );\n\n case StripeElementType.IDEAL: {\n const data = this._mapStripePaymentData(StripePaymentMethodType.IDEAL, returnUrl);\n\n return this._getStripeJs().confirmIdealPayment(clientSecret, data, {\n handleActions: false,\n });\n }\n\n case StripeElementType.Sepa: {\n const data = this._mapStripePaymentData(StripePaymentMethodType.Sepa);\n\n return this._getStripeJs().confirmSepaDebitPayment(clientSecret, data);\n }\n\n default: {\n const card = this._useIndividualCardFields\n ? this._getStripeCardElements()[0]\n : this._getStripeElement();\n const billingDetails = this._mapStripeBillingDetails(\n this._store.getState().billingAddress.getBillingAddress(),\n this._store.getState().customer.getCustomer(),\n );\n\n return this._getStripeJs().createPaymentMethod({\n type: StripePaymentMethodType.CreditCard,\n card,\n billing_details: billingDetails,\n });\n }\n }\n }\n\n private async _executeWithVaulted(\n payment: OrderPaymentRequestBody,\n token: string,\n shouldSetAsDefaultInstrument: boolean | undefined,\n clientToken: string,\n ): Promise {\n const formattedPayload = {\n bigpay_token: { token },\n confirm: true,\n client_token: clientToken,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n };\n\n if (\n this._isHostedPaymentFormEnabled(payment.methodId, payment.gatewayId) &&\n this._hostedForm\n ) {\n const form = this._hostedForm;\n\n if (payment.paymentData && isVaultedInstrument(payment.paymentData)) {\n payment.paymentData = {\n ...payment.paymentData,\n instrumentId: JSON.stringify({\n token: payment.paymentData?.instrumentId || '',\n client_token: clientToken,\n }),\n };\n }\n\n await form.validate();\n await form.submit(payment);\n\n return this._store.dispatch(this._orderActionCreator.loadCurrentOrder());\n }\n\n const paymentPayload = this._buildPaymentPayload(\n payment.methodId,\n formattedPayload,\n shouldSetAsDefaultInstrument,\n );\n\n return this._store.dispatch(this._paymentActionCreator.submitPayment(paymentPayload));\n }\n\n private _getInitializeOptions(): StripeV3PaymentInitializeOptions {\n if (!this._initializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._initializeOptions;\n }\n\n private _getStripeCardElements(): StripeCardElements {\n if (!this._stripeCardElements) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._stripeCardElements;\n }\n\n private _getStripeElement(): StripeElement {\n if (!this._stripeElement) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._stripeElement;\n }\n\n private _getStripeJs(): StripeV3Client {\n if (!this._stripeV3Client) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._stripeV3Client;\n }\n\n private _handleEmptyPaymentIntentError(error: Error, stripeError: StripeError | undefined) {\n if (!(error instanceof RequestError)) {\n return error;\n }\n\n return some(error.body.errors, { code: 'required_field' }) && stripeError\n ? new Error(stripeError.message)\n : error;\n }\n\n private async _loadStripeJs(\n stripePublishableKey: string,\n stripeConnectedAccount: string,\n ): Promise {\n if (this._stripeV3Client) {\n return Promise.resolve(this._stripeV3Client);\n }\n\n return this._stripeScriptLoader.load(\n stripePublishableKey,\n stripeConnectedAccount,\n this._locale,\n );\n }\n\n private _mapStripeAddress(address?: Address): StripeAddress {\n if (address) {\n const {\n city,\n countryCode: country,\n address1: line1,\n address2: line2,\n postalCode,\n stateOrProvinceCode: state,\n } = address;\n\n return { city, country, line1, line2, postal_code: postalCode, state };\n }\n\n return { line1: '' };\n }\n\n private _mapStripeBillingDetails(\n billingAddress?: BillingAddress,\n customer?: Customer,\n ): StripeBillingDetails {\n const { firstName, lastName } = billingAddress ||\n customer || { firstName: 'Guest', lastName: '' };\n const name = `${firstName} ${lastName}`.trim();\n const { options } = this._getInitializeOptions();\n\n if (this._useIndividualCardFields && isIndividualCardElementOptions(options)) {\n const { zipCodeElementOptions } = options;\n\n if (zipCodeElementOptions) {\n const postalCode = document.getElementById(zipCodeElementOptions.containerId)\n ? (\n document.getElementById(\n zipCodeElementOptions.containerId,\n ) as HTMLInputElement\n ).value\n : '';\n\n if (postalCode && billingAddress) {\n billingAddress = { ...billingAddress, postalCode };\n }\n }\n }\n\n const address = {\n address: this._mapStripeAddress(billingAddress),\n };\n\n if (customer && customer.addresses[0] && isBillingAddressLike(customer.addresses[0])) {\n const customerAddress = customer.addresses[0];\n const { email } = customer;\n const { phone } = customerAddress;\n\n return phone ? { ...address, email, name, phone } : { ...address, email, name };\n }\n\n if (billingAddress) {\n const { email, phone } = billingAddress;\n\n return phone ? { ...address, email, name, phone } : { ...address, email, name };\n }\n\n return { ...address, name };\n }\n\n private _mapStripePaymentData(\n stripePaymentMethodType: StripePaymentMethodType.IDEAL,\n returnUrl?: string,\n ): StripeConfirmIdealPaymentData;\n private _mapStripePaymentData(\n stripePaymentMethodType: StripePaymentMethodType.Sepa,\n ): StripeConfirmSepaPaymentData;\n private _mapStripePaymentData(\n stripePaymentMethodType: StripePaymentMethodType,\n returnUrl?: string,\n ): StripeConfirmPaymentData {\n const customer = this._store.getState().customer.getCustomer();\n const billingAddress = this._store.getState().billingAddress.getBillingAddress();\n\n const result: Partial = {\n payment_method: {\n [stripePaymentMethodType]: this._getStripeElement(),\n billing_details: this._mapStripeBillingDetails(billingAddress, customer),\n },\n };\n\n if (stripePaymentMethodType === StripePaymentMethodType.IDEAL) {\n return { ...result, return_url: returnUrl };\n }\n\n return result;\n }\n\n private _mountCardFields(methodId: string): Promise {\n const { options, containerId } = this._getInitializeOptions();\n\n let stripeElement: StripeElement;\n\n return new Promise((resolve, reject) => {\n if (!this._stripeElements) {\n this._stripeElements = this._getStripeJs().elements();\n }\n\n switch (methodId) {\n case StripeElementType.CreditCard:\n if (this._useIndividualCardFields && isIndividualCardElementOptions(options)) {\n const {\n cardNumberElementOptions,\n cardExpiryElementOptions,\n cardCvcElementOptions,\n } = options;\n\n const cardNumberElement =\n this._stripeElements.getElement(StripeElementType.CardNumber) ||\n this._stripeElements.create(\n StripeElementType.CardNumber,\n cardNumberElementOptions,\n );\n const cardExpiryElement =\n this._stripeElements.getElement(StripeElementType.CardExpiry) ||\n this._stripeElements.create(\n StripeElementType.CardExpiry,\n cardExpiryElementOptions,\n );\n const cardCvcElement =\n this._stripeElements.getElement(StripeElementType.CardCvc) ||\n this._stripeElements.create(\n StripeElementType.CardCvc,\n cardCvcElementOptions,\n );\n\n this._stripeCardElements = [\n cardNumberElement,\n cardExpiryElement,\n cardCvcElement,\n ];\n stripeElement = this._stripeCardElements[0];\n\n try {\n cardNumberElement.mount(`#${cardNumberElementOptions.containerId}`);\n cardExpiryElement.mount(`#${cardExpiryElementOptions.containerId}`);\n cardCvcElement.mount(`#${cardCvcElementOptions.containerId}`);\n } catch (error) {\n if (!this._isDeinitialize) {\n reject(\n new InvalidArgumentError(\n 'Unable to mount Stripe component without valid container ID.',\n ),\n );\n }\n }\n } else {\n stripeElement =\n this._stripeElements.getElement(methodId) ||\n this._stripeElements.create(methodId, options as StripeElementOptions);\n\n try {\n stripeElement.mount(`#${containerId}`);\n } catch (error) {\n if (!this._isDeinitialize) {\n reject(\n new InvalidArgumentError(\n 'Unable to mount Stripe component without valid container ID.',\n ),\n );\n }\n }\n }\n\n break;\n\n case StripeElementType.IDEAL:\n case StripeElementType.Sepa:\n stripeElement =\n this._stripeElements.getElement(methodId) ||\n this._stripeElements.create(methodId, options as StripeElementOptions);\n\n try {\n stripeElement.mount(`#${containerId}`);\n } catch (error) {\n if (!this._isDeinitialize) {\n reject(\n new InvalidArgumentError(\n 'Unable to mount Stripe component without valid container ID.',\n ),\n );\n }\n }\n\n break;\n\n case StripeElementType.Alipay:\n break;\n }\n\n resolve(stripeElement);\n });\n }\n\n private async _mountCardVerificationFields(\n formOptions: HostedFormOptions,\n ): Promise {\n const { config } = this._store.getState();\n const storeConfig = config.getStoreConfig();\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const bigpayBaseUrl = storeConfig.paymentSettings.bigpayBaseUrl;\n\n const form = this._hostedFormFactory.create(bigpayBaseUrl, formOptions);\n\n await form.attach();\n\n return form;\n }\n\n private async _processAdditionalAction(\n error: Error,\n methodId: string,\n shouldSaveInstrument = false,\n shouldSetAsDefaultInstrument = false,\n ): Promise {\n if (!(error instanceof RequestError)) {\n throw error;\n }\n\n const isAdditionalActionError = some(error.body.errors, {\n code: 'additional_action_required',\n });\n const isThreeDSecureRequiredError = some(error.body.errors, {\n code: 'three_d_secure_required',\n });\n\n if (isAdditionalActionError) {\n const action: StripeAdditionalAction = error.body.additional_action_required;\n\n if (action && action.type === 'redirect_to_url') {\n return new Promise(() => {\n if (action.data.redirect_url) {\n window.location.replace(action.data.redirect_url);\n }\n });\n }\n }\n\n if (isThreeDSecureRequiredError) {\n const clientSecret = error.body.three_ds_result.token;\n const needsConfirm = false;\n let catchedConfirmError = false;\n let result;\n\n try {\n result = await this._getStripeJs().confirmCardPayment(clientSecret);\n } catch (error) {\n catchedConfirmError = true;\n }\n\n if (result?.error) {\n if (this._isCancellationError(result.error)) {\n throw new PaymentMethodCancelledError();\n }\n\n if (this._isAuthError(result.error)) {\n throw new StripeV3Error(StripeV3ErrorType.AuthFailure);\n }\n\n throw new Error(result.error.message);\n }\n\n const token = this._getPaymentToken(\n result?.paymentIntent,\n clientSecret,\n catchedConfirmError,\n );\n\n const formattedPayload = {\n credit_card_token: { token },\n vault_payment_instrument: shouldSaveInstrument,\n confirm: needsConfirm,\n };\n\n const paymentPayload = this._buildPaymentPayload(\n methodId,\n formattedPayload,\n shouldSetAsDefaultInstrument,\n );\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentPayload),\n );\n } catch (error) {\n throw this._handleEmptyPaymentIntentError(error, result?.error);\n }\n }\n\n throw error;\n }\n\n private _getPaymentToken(\n paymentIntent: PaymentIntent | undefined,\n clientSecret: string,\n catchedConfirmError: boolean,\n ): string {\n if (!paymentIntent || catchedConfirmError) {\n return clientSecret;\n }\n\n return paymentIntent.id;\n }\n\n private _shouldShowTSVHostedForm(methodId: string, gatewayId: string): boolean {\n return (\n this._isHostedFieldAvailable() && this._isHostedPaymentFormEnabled(methodId, gatewayId)\n );\n }\n\n private _unmountElement(): void {\n if (this._stripeElement) {\n this._stripeElement.unmount();\n this._stripeElement = undefined;\n }\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { StripeHostWindow, StripeV3Client } from './stripev3';\n\nexport default class StripeV3ScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, private _window: StripeHostWindow = window) {}\n\n load(\n stripePublishableKey: string,\n stripeAccount: string,\n locale?: string,\n ): Promise {\n return this._scriptLoader.loadScript('https://js.stripe.com/v3/').then(() => {\n if (!this._window.Stripe) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.Stripe(stripePublishableKey, {\n stripeAccount,\n locale,\n betas: ['payment_intent_beta_3', 'alipay_pm_beta_1'],\n apiVersion: '2020-03-02;alipay_beta=v1',\n });\n });\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\n\nimport WepayRisk from './wepay-risk';\nimport WepayWindow from './wepay-window';\n\nconst SCRIPT_SRC = '//static.wepay.com/min/js/risk.1.latest.js';\n\nexport default class WepayRiskClient {\n private _riskClient?: WepayRisk;\n\n constructor(private _scriptLoader: ScriptLoader) {}\n\n initialize(): Promise {\n return this._scriptLoader\n .loadScript(SCRIPT_SRC)\n .then(() => (this._riskClient = (window as unknown as WepayWindow).WePay.risk))\n .then(() => this);\n }\n\n getRiskToken(): string {\n if (!this._riskClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._riskClient.generate_risk_token();\n\n return this._riskClient.get_risk_token();\n }\n}\n","import { merge } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nimport WepayRiskClient from './wepay-risk-client';\n\nexport default class WepayPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _wepayRiskClient: WepayRiskClient,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n initialize(options: PaymentInitializeOptions): Promise {\n void this._wepayRiskClient.initialize();\n\n return super.initialize(options);\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const token = this._wepayRiskClient.getRiskToken();\n const payloadWithToken = merge({}, payload, {\n payment: {\n paymentData: {\n deviceSessionId: token,\n },\n },\n });\n\n return super.execute(payloadWithToken, options);\n }\n}\n","import { merge, some } from 'lodash';\n\nimport { InternalCheckoutSelectors } from '../../../checkout';\nimport {\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport { PaymentInitializeOptions } from '../../payment-request-options';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nimport {\n WorldpayAccess3DSOptions,\n WorldpayAccessAdditionalAction,\n WorldpayAccessPaymentInitializeOptions,\n} from './worldpayaccess-payment-options';\n\nconst IFRAME_NAME = 'worldpay_hosted_payment_page';\nconst IFRAME_HIDDEN_NAME = 'worldpay_hosted_hidden_payment_page';\nconst PAYMENT_CANNOT_CONTINUE = 'Payment cannot continue';\n\nlet submit: (paymentPayload: OrderPaymentRequestBody) => Promise;\n\nexport default class WorldpayaccessPaymetStrategy extends CreditCardPaymentStrategy {\n private _initializeOptions?: WorldpayAccessPaymentInitializeOptions;\n\n async initialize(options?: PaymentInitializeOptions): Promise {\n this._initializeOptions = options && options.worldpay;\n\n if (!this._initializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return super.initialize(options);\n }\n\n async execute(\n orderRequest: OrderRequestBody,\n options?: PaymentInitializeOptions,\n ): Promise {\n const { payment } = orderRequest;\n\n submit = this._submitAdditionalAction();\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n try {\n return await super.execute(orderRequest, options);\n } catch (error) {\n return await this._processAdditionalAction(error, payment);\n }\n }\n\n private async _processAdditionalAction(\n error: unknown,\n payment: OrderPaymentRequestBody,\n ): Promise {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'additional_action_required' })\n ) {\n return Promise.reject(error);\n }\n\n return new Promise((resolve, reject) => {\n const messageEvent = async (event: MessageEvent) => {\n if (typeof event.data !== 'string' || !this._isValidJsonWithSessionId(event.data)) {\n return reject(new Error(PAYMENT_CANNOT_CONTINUE));\n }\n\n window.removeEventListener('message', messageEvent);\n window.removeEventListener('remove_event_message', removeEvent);\n iframeHidden.remove();\n\n const data = JSON.parse(event.data);\n const paymentPayload = merge({}, payment, {\n paymentData: { threeDSecure: { token: data.SessionId } },\n });\n\n try {\n resolve(await submit(paymentPayload));\n } catch (error) {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return reject(error);\n }\n\n if (!this._initializeOptions) {\n return reject(\n new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n const { onLoad } = this._initializeOptions;\n const frame = this._createIframe(error.body.three_ds_result);\n\n try {\n onLoad(frame, () => reject(new Error('Payment was cancelled')));\n } catch (e) {\n reject(new Error(PAYMENT_CANNOT_CONTINUE));\n }\n }\n };\n\n const removeEvent = () => {\n window.removeEventListener('remove_event_message', removeEvent);\n window.removeEventListener('message', messageEvent);\n iframeHidden.remove();\n\n return reject(new Error(PAYMENT_CANNOT_CONTINUE));\n };\n\n window.addEventListener('message', messageEvent);\n window.addEventListener('remove_event_message', removeEvent);\n\n let iframeHidden: HTMLIFrameElement;\n\n try {\n iframeHidden = this._createHiddenIframe(error.body);\n } catch (e) {\n window.removeEventListener('remove_event_message', removeEvent);\n window.removeEventListener('message', messageEvent);\n throw new Error(PAYMENT_CANNOT_CONTINUE);\n }\n });\n }\n\n private _createHiddenIframe(body: WorldpayAccessAdditionalAction): HTMLIFrameElement {\n const iframe = document.createElement('iframe');\n\n if (!iframe) {\n throw new Error();\n }\n\n document.body.appendChild(iframe);\n\n if (!iframe.contentWindow) {\n throw new Error();\n }\n\n iframe.id = IFRAME_HIDDEN_NAME;\n iframe.height = '0px';\n iframe.width = '0px';\n\n const form = document.createElement('form');\n const formId = 'collectionForm';\n\n form.id = formId;\n form.name = 'devicedata';\n form.method = 'post';\n\n const url = body.additional_action_required.data.redirect_url;\n\n form.action = url;\n\n const inputBin = document.createElement('input');\n\n inputBin.name = 'Bin';\n inputBin.type = 'hidden';\n inputBin.value = body.provider_data.source_id;\n form.appendChild(inputBin);\n\n const inputJWT = document.createElement('input');\n\n inputJWT.name = 'JWT';\n inputJWT.type = 'hidden';\n inputJWT.value = body.provider_data.data;\n form.appendChild(inputJWT);\n\n const button = document.createElement('button');\n\n button.type = 'submit';\n button.id = 'btnsubmit';\n form.appendChild(button);\n\n if (navigator.userAgent.match('Firefox')) {\n iframe.srcdoc = form.outerHTML;\n } else {\n iframe.contentWindow.document.body.appendChild(form);\n }\n\n const script = document.createElement('script');\n\n script.innerHTML = `\n const data = new URLSearchParams()\n data.append('Bin', '${body.provider_data.source_id}');\n data.append('JWT', '${body.provider_data.data}');\n\n window.parent.fetch('${url}', {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: data\n })\n .then((response) => {\n if (!response.ok) {\n window.parent.dispatchEvent(new Event('remove_event_message'));\n } else {\n document.getElementById('${formId}').submit();\n }\n })\n .catch((error) => {\n window.parent.dispatchEvent(new Event('remove_event_message'));\n })\n `;\n iframe.contentWindow.document.body.appendChild(script);\n\n return iframe;\n }\n\n private _createIframe(data: WorldpayAccess3DSOptions): HTMLIFrameElement {\n const form = document.createElement('form');\n\n form.id = 'challengeForm';\n form.method = 'POST';\n form.action = data.acs_url;\n\n const inputJWT = document.createElement('input');\n\n inputJWT.name = 'JWT';\n inputJWT.type = 'hidden';\n inputJWT.value = data.payer_auth_request;\n form.appendChild(inputJWT);\n\n const merchant = document.createElement('input');\n\n merchant.name = 'MD';\n merchant.type = 'hidden';\n merchant.value = `merchantSessionId=${data.merchant_data}`;\n form.appendChild(merchant);\n\n const script = document.createElement('script');\n\n script.type = 'text/javascript';\n script.innerHTML =\n \"window.onload = function() { document.getElementById('challengeForm').submit(); }\";\n\n const iframe = document.createElement('iframe');\n\n iframe.name = IFRAME_NAME;\n iframe.height = '400';\n iframe.width = '100%';\n iframe.srcdoc = `${form.outerHTML} ${script.outerHTML}`;\n\n return iframe;\n }\n\n private _submitAdditionalAction() {\n if (this._shouldRenderHostedForm) {\n if (!this._hostedForm || !this._hostedForm.submit) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const hostedForm = this._hostedForm;\n\n return async (paymentPayload: OrderPaymentRequestBody) => {\n await hostedForm.submit(paymentPayload);\n\n return this._store.getState();\n };\n }\n\n return async (paymentPayload: OrderPaymentRequestBody) => {\n return this._store.dispatch(this._paymentActionCreator.submitPayment(paymentPayload));\n };\n }\n\n private _isValidJsonWithSessionId(str: string) {\n try {\n const data = JSON.parse(str);\n\n if (data.SessionId) {\n return true;\n }\n\n return false;\n } catch (e) {\n return false;\n }\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { MissingDataError, MissingDataErrorType, RequestError } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport { StoreCreditActionCreator } from '../../../store-credit';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport StorefrontPaymentRequestSender from '../../storefront-payment-request-sender';\nimport PaymentStrategy from '../payment-strategy';\n\nexport default class ZipPaymentStrategy implements PaymentStrategy {\n constructor(\n private _store: CheckoutStore,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _storeCreditActionCreator: StoreCreditActionCreator,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n private _orderActionCreator: OrderActionCreator,\n private _storefrontPaymentRequestSender: StorefrontPaymentRequestSender,\n private _paymentActionCreator: PaymentActionCreator,\n ) {}\n\n initialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId } = payment;\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId, options),\n );\n const { clientToken, initializationData: { redirectUrl } = {} } =\n getPaymentMethodOrThrow(methodId);\n\n if (!clientToken || !redirectUrl) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { id: nonce } = JSON.parse(clientToken);\n\n if (!nonce) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n const { isStoreCreditApplied: useStoreCredit } = this._store\n .getState()\n .checkout.getCheckoutOrThrow();\n\n await this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(useStoreCredit));\n await this._store.dispatch(\n this._remoteCheckoutActionCreator.initializePayment(methodId, { useStoreCredit }),\n );\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n await this._prepareForReferredRegistration(methodId, nonce);\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({ methodId, paymentData: { nonce } }),\n );\n } catch (error) {\n if (\n error instanceof RequestError &&\n error.body.status === 'additional_action_required'\n ) {\n return new Promise(() => window.location.replace(redirectUrl));\n }\n\n throw error;\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n private _prepareForReferredRegistration(methodId: string, externalId: string): Promise {\n return this._storefrontPaymentRequestSender.saveExternalId(methodId, externalId);\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { VaultAccessToken } from './instrument';\nimport { InstrumentsResponseBody } from './instrument-response-body';\n\nexport enum InstrumentActionType {\n LoadInstrumentsRequested = 'LOAD_INSTRUMENTS_REQUESTED',\n LoadInstrumentsSucceeded = 'LOAD_INSTRUMENTS_SUCCEEDED',\n LoadInstrumentsFailed = 'LOAD_INSTRUMENTS_FAILED',\n\n DeleteInstrumentRequested = 'DELETE_INSTRUMENT_REQUESTED',\n DeleteInstrumentSucceeded = 'DELETE_INSTRUMENT_SUCCEEDED',\n DeleteInstrumentFailed = 'DELETE_INSTRUMENT_FAILED',\n}\n\nexport type InstrumentAction = LoadInstrumentsAction | DeleteInstrumentAction;\n\nexport type LoadInstrumentsAction =\n | LoadInstrumentsRequestedAction\n | LoadInstrumentsSucceededAction\n | LoadInstrumentsFailedAction;\n\nexport type DeleteInstrumentAction =\n | DeleteInstrumentRequestedAction\n | DeleteInstrumentSucceededAction\n | DeleteInstrumentFailedAction;\n\nexport interface LoadInstrumentsRequestedAction extends Action {\n type: InstrumentActionType.LoadInstrumentsRequested;\n}\n\nexport interface LoadInstrumentsSucceededAction\n extends Action {\n type: InstrumentActionType.LoadInstrumentsSucceeded;\n}\n\nexport interface LoadInstrumentsFailedAction extends Action {\n type: InstrumentActionType.LoadInstrumentsFailed;\n}\n\nexport interface DeleteInstrumentRequestedAction extends Action {\n type: InstrumentActionType.DeleteInstrumentRequested;\n}\n\nexport interface DeleteInstrumentSucceededAction\n extends Action {\n type: InstrumentActionType.DeleteInstrumentSucceeded;\n}\n\nexport interface DeleteInstrumentFailedAction extends Action {\n type: InstrumentActionType.DeleteInstrumentFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { Address } from '../../address';\nimport { InternalCheckoutSelectors, ReadableCheckoutStore } from '../../checkout';\nimport { addMinutes, isFuture } from '../../common/date-time';\nimport { MissingDataError, MissingDataErrorType } from '../../common/error/errors';\n\nimport { SessionContext, VaultAccessToken } from './instrument';\nimport {\n DeleteInstrumentAction,\n InstrumentActionType,\n LoadInstrumentsAction,\n} from './instrument-actions';\nimport InstrumentRequestSender from './instrument-request-sender';\n\nexport default class InstrumentActionCreator {\n constructor(private _instrumentRequestSender: InstrumentRequestSender) {}\n\n loadInstruments(): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n observer.next(createAction(InstrumentActionType.LoadInstrumentsRequested));\n\n const session = this._getSessionContext(store);\n const token = this._getCurrentAccessToken(store);\n const shippingAddress = this._getShippingAddress(store);\n\n return this._getValidAccessToken(token)\n .then((currentToken) =>\n this._instrumentRequestSender\n .loadInstruments(\n {\n ...session,\n authToken: currentToken.vaultAccessToken,\n },\n shippingAddress,\n )\n .then(({ body }) => {\n observer.next(\n createAction(\n InstrumentActionType.LoadInstrumentsSucceeded,\n body,\n currentToken,\n ),\n );\n observer.complete();\n }),\n )\n .catch((response) => {\n observer.error(\n createErrorAction(InstrumentActionType.LoadInstrumentsFailed, response),\n );\n });\n });\n }\n\n deleteInstrument(\n instrumentId: string,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n observer.next(\n createAction(InstrumentActionType.DeleteInstrumentRequested, undefined, {\n instrumentId,\n }),\n );\n\n const session = this._getSessionContext(store);\n const token = this._getCurrentAccessToken(store);\n\n return this._getValidAccessToken(token)\n .then((currentToken) =>\n this._instrumentRequestSender\n .deleteInstrument(\n {\n ...session,\n authToken: currentToken.vaultAccessToken,\n },\n instrumentId,\n )\n .then(({ body }) => {\n observer.next(\n createAction(\n InstrumentActionType.DeleteInstrumentSucceeded,\n body,\n {\n instrumentId,\n ...currentToken,\n },\n ),\n );\n observer.complete();\n }),\n )\n .catch((response) => {\n observer.error(\n createErrorAction(\n InstrumentActionType.DeleteInstrumentFailed,\n response,\n { instrumentId },\n ),\n );\n });\n });\n }\n\n private _isValidVaultAccessToken(token: VaultAccessToken): boolean {\n if (!token || !token.vaultAccessToken) {\n return false;\n }\n\n const expiryBuffer = 2;\n const expiry = addMinutes(new Date(token.vaultAccessExpiry), expiryBuffer);\n\n return isFuture(expiry);\n }\n\n private _getCurrentAccessToken(store: ReadableCheckoutStore): VaultAccessToken | undefined {\n const { instruments } = store.getState();\n const meta = instruments.getInstrumentsMeta();\n\n if (!meta) {\n return;\n }\n\n return {\n vaultAccessToken: meta.vaultAccessToken,\n vaultAccessExpiry: meta.vaultAccessExpiry,\n };\n }\n\n private _getValidAccessToken(token?: VaultAccessToken): Promise {\n return token && this._isValidVaultAccessToken(token)\n ? Promise.resolve(token)\n : this._instrumentRequestSender.getVaultAccessToken().then(({ body }) => body);\n }\n\n private _getShippingAddress(store: ReadableCheckoutStore): Address | Address[] | undefined {\n const state = store.getState();\n const addresses = state.shippingAddress.getShippingAddresses();\n\n return addresses.length > 1 ? addresses : state.shippingAddress.getShippingAddress();\n }\n\n private _getSessionContext(store: ReadableCheckoutStore): SessionContext {\n const state = store.getState();\n const config = state.config.getStoreConfig();\n const cart = state.cart.getCart();\n\n if (!config) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n const { customerId } = cart;\n const { storeId } = config.storeProfile;\n const { code } = config.shopperCurrency.isTransactional\n ? config.shopperCurrency\n : config.currency;\n\n return {\n customerId,\n storeId,\n currencyCode: code,\n };\n }\n}\n","export default function isFuture(date: Date): boolean {\n return date.valueOf() > Date.now();\n}\n","export default function addMinutes(date: Date, amount: number): Date {\n const newDate = new Date(date.getTime());\n\n newDate.setMinutes(date.getMinutes() + amount);\n\n return newDate;\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport PaymentResponse from '../payment-response';\n\nimport PaymentInstrument, { VaultAccessToken } from './instrument';\nimport {\n BankInternalInstrument,\n InstrumentErrorResponseBody,\n InstrumentsResponseBody,\n InternalInstrument,\n InternalInstrumentErrorResponseBody,\n InternalInstrumentsResponseBody,\n InternalVaultAccessTokenResponseBody,\n PayPalInternalInstrument,\n} from './instrument-response-body';\nimport { mapToBankInstrument } from './map-to-bank-instrument';\nimport { mapToCardInstrument } from './map-to-card-instrument';\nimport { mapToPayPalInstrument } from './map-to-paypal-instrument';\n\nexport default class InstrumentResponseTransformer {\n transformResponse(\n response: PaymentResponse,\n ): Response {\n const { body, ...payload } = this._transformResponse(response);\n\n return {\n ...payload,\n body: {\n vaultedInstruments: this._transformVaultedInstruments(body.vaulted_instruments),\n },\n };\n }\n\n transformErrorResponse(\n response: PaymentResponse,\n ): Response {\n return this._transformResponse(response);\n }\n\n transformVaultAccessResponse(\n response: Response,\n ): Response {\n return {\n ...response,\n body: {\n vaultAccessToken: response.body.data.token,\n vaultAccessExpiry: response.body.data.expires_at,\n },\n };\n }\n\n private _transformVaultedInstruments(\n vaultedInstruments: InternalInstrument[] = [],\n ): PaymentInstrument[] {\n return vaultedInstruments.map((instrument) => {\n if (this._isPayPalInstrument(instrument)) {\n return mapToPayPalInstrument(instrument);\n }\n\n if (this._isBankInstrument(instrument)) {\n return mapToBankInstrument(instrument);\n }\n\n return mapToCardInstrument(instrument);\n });\n }\n\n private _isPayPalInstrument(\n instrument: InternalInstrument,\n ): instrument is PayPalInternalInstrument {\n return instrument.method_type === 'paypal';\n }\n\n private _isBankInstrument(\n instrument: InternalInstrument,\n ): instrument is BankInternalInstrument {\n return instrument.method_type === 'bank';\n }\n\n private _transformResponse(response: PaymentResponse): Response {\n const { data: body, ...payload } = response;\n\n return {\n ...payload,\n body,\n };\n }\n}\n","import { PayPalInstrument } from './instrument';\nimport { PayPalInternalInstrument } from './instrument-response-body';\n\nexport function mapToPayPalInstrument(instrument: PayPalInternalInstrument): PayPalInstrument {\n return {\n bigpayToken: instrument.bigpay_token,\n defaultInstrument: instrument.default_instrument,\n provider: instrument.provider,\n externalId: instrument.external_id,\n trustedShippingAddress: instrument.trusted_shipping_address,\n method: 'paypal',\n type: 'account',\n };\n}\n","import { BankInstrument } from './instrument';\nimport { BankInternalInstrument } from './instrument-response-body';\n\nexport function mapToBankInstrument(instrument: BankInternalInstrument): BankInstrument {\n return {\n bigpayToken: instrument.bigpay_token,\n defaultInstrument: instrument.default_instrument,\n provider: instrument.provider,\n trustedShippingAddress: instrument.trusted_shipping_address,\n accountNumber: instrument.account_number,\n issuer: instrument.issuer,\n iban: instrument.iban,\n method: instrument.method,\n type: 'bank',\n };\n}\n","import { CardInstrument } from './instrument';\nimport { CardInternalInstrument } from './instrument-response-body';\n\nexport function mapToCardInstrument(instrument: CardInternalInstrument): CardInstrument {\n return {\n bigpayToken: instrument.bigpay_token,\n defaultInstrument: instrument.default_instrument,\n provider: instrument.provider,\n iin: instrument.iin,\n last4: instrument.last_4,\n expiryMonth: instrument.expiry_month,\n expiryYear: instrument.expiry_year,\n brand: instrument.brand,\n trustedShippingAddress: instrument.trusted_shipping_address,\n untrustedShippingCardVerificationMode:\n instrument.untrusted_shipping_address_card_verification_mode,\n method: instrument.method,\n type: 'card',\n };\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Address, mapToInternalAddress } from '../../address';\nimport { RequestOptions } from '../../common/http-request';\nimport PaymentResponse from '../payment-response';\n\nimport { InstrumentRequestContext, VaultAccessToken } from './instrument';\nimport {\n InstrumentsResponseBody,\n InternalInstrumentErrorResponseBody,\n InternalInstrumentsResponseBody,\n InternalVaultAccessTokenResponseBody,\n} from './instrument-response-body';\nimport InstrumentResponseTransformer from './instrument-response-transformer';\n\nexport default class InstrumentRequestSender {\n private _transformer: InstrumentResponseTransformer;\n\n constructor(private _client: any, private _requestSender: RequestSender) {\n this._transformer = new InstrumentResponseTransformer();\n }\n\n getVaultAccessToken({ timeout }: RequestOptions = {}): Promise> {\n const url = '/internalapi/v1/checkout/payments/vault-access-token';\n\n return this._requestSender\n .get(url, { timeout })\n .then((response) => ({\n ...response,\n body: {\n vaultAccessToken: response.body.data.token,\n vaultAccessExpiry: response.body.data.expires_at,\n },\n }));\n }\n\n loadInstruments(\n requestContext: InstrumentRequestContext,\n shippingAddress?: Address | Address[],\n ): Promise> {\n return shippingAddress\n ? this._loadInstrumentsWithAddress(requestContext, shippingAddress)\n : this._loadInstruments(requestContext);\n }\n\n deleteInstrument(\n requestContext: InstrumentRequestContext,\n instrumentId: string,\n ): Promise> {\n const payload = {\n ...requestContext,\n instrumentId,\n };\n\n return new Promise((resolve, reject) => {\n this._client.deleteShopperInstrument(\n payload,\n (\n errorResponse: PaymentResponse,\n response: PaymentResponse,\n ) =>\n errorResponse\n ? reject(this._transformer.transformErrorResponse(errorResponse))\n : resolve(this._transformer.transformResponse(response)),\n );\n });\n }\n\n private _loadInstruments(\n requestContext: InstrumentRequestContext,\n ): Promise> {\n return new Promise((resolve, reject) => {\n this._client.loadInstruments(\n requestContext,\n (\n errorResponse: PaymentResponse,\n response: PaymentResponse,\n ) =>\n errorResponse\n ? reject(this._transformer.transformErrorResponse(errorResponse))\n : resolve(this._transformer.transformResponse(response)),\n );\n });\n }\n\n private _loadInstrumentsWithAddress(\n requestContext: InstrumentRequestContext,\n shippingAddress: Address | Address[],\n ): Promise> {\n const payload = {\n ...requestContext,\n shippingAddress: Array.isArray(shippingAddress)\n ? shippingAddress.map((address) => mapToInternalAddress(address))\n : mapToInternalAddress(shippingAddress),\n };\n\n return new Promise((resolve, reject) => {\n this._client.loadInstrumentsWithAddress(\n payload,\n (\n errorResponse: PaymentResponse,\n response: PaymentResponse,\n ) =>\n errorResponse\n ? reject(this._transformer.transformErrorResponse(errorResponse))\n : resolve(this._transformer.transformResponse(response)),\n );\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { PickupOptionMeta, PickupOptionResult } from './pickup-option';\n\nexport enum PickupOptionActionType {\n LoadPickupOptionsRequested = 'LOAD_PICKUP_OPTIONS_REQUESTED',\n LoadPickupOptionsSucceeded = 'LOAD_PICKUP_OPTIONS_SUCCEEDED',\n LoadPickupOptionsFailed = 'LOAD_PICKUP_OPTIONS_FAILED',\n}\n\nexport type LoadPickupOptionsAction =\n | PickupOptionRequestedAction\n | LoadPickupOptionsSucceededAction\n | LoadPickupOptionsFailedAction;\n\nexport interface PickupOptionRequestedAction extends Action {\n type: PickupOptionActionType.LoadPickupOptionsRequested;\n}\n\nexport interface LoadPickupOptionsSucceededAction\n extends Action {\n type: PickupOptionActionType.LoadPickupOptionsSucceeded;\n}\n\nexport interface LoadPickupOptionsFailedAction extends Action {\n type: PickupOptionActionType.LoadPickupOptionsFailed;\n}\n","import {\n createAction,\n createErrorAction,\n ReadableDataStore,\n ThunkAction,\n} from '@bigcommerce/data-store';\nimport { includes } from 'lodash';\nimport { Observable, Observer } from 'rxjs';\n\nimport { LineItem } from '../cart';\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\n\nimport { PickupOptionAPIRequestBody, PickupOptionRequestBody } from './pickup-option';\nimport { LoadPickupOptionsAction, PickupOptionActionType } from './pickup-option-actions';\nimport PickupOptionRequestSender from './pickup-option-request-sender';\n\nexport default class PickupOptionActionCreator {\n constructor(private _pickupOptionRequestSender: PickupOptionRequestSender) {}\n\n loadPickupOptions(\n query: PickupOptionRequestBody,\n ): ThunkAction {\n return (store) =>\n new Observable((observer: Observer) => {\n const apiQuery = this._hydrateApiQuery(store, query);\n\n observer.next(createAction(PickupOptionActionType.LoadPickupOptionsRequested));\n\n this._pickupOptionRequestSender\n .fetchPickupOptions(apiQuery)\n .then((response) => {\n observer.next(\n createAction(\n PickupOptionActionType.LoadPickupOptionsSucceeded,\n response.body.results,\n query,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n PickupOptionActionType.LoadPickupOptionsFailed,\n response,\n ),\n );\n });\n });\n }\n\n private _hydrateApiQuery(\n store: ReadableDataStore,\n query: PickupOptionRequestBody,\n ): PickupOptionAPIRequestBody {\n const state = store.getState();\n const cart = state.cart.getCartOrThrow();\n\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n const consignment = state.consignments.getConsignmentById(query.consignmentId);\n\n if (!consignment) {\n throw new MissingDataError(MissingDataErrorType.MissingConsignments);\n }\n\n const consignmentLineItems = consignment.lineItemIds;\n const physicalItems = cart.lineItems.physicalItems;\n const cartItems = physicalItems\n .filter((item: LineItem) => includes(consignmentLineItems, item.id))\n .map((item) => ({\n variantId: item.variantId,\n quantity: item.quantity,\n }));\n\n return {\n searchArea: query.searchArea,\n items: cartItems,\n };\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { ContentType, SDK_VERSION_HEADERS } from '../common/http-request';\n\nimport { PickupOptionAPIRequestBody, PickupOptionResponse } from './pickup-option';\n\nconst url = '/api/storefront/pickup-options';\n\nexport default class PickupOptionRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n fetchPickupOptions(query: PickupOptionAPIRequestBody): Promise> {\n return this._requestSender.post(url, {\n headers: { Accept: ContentType.Json, ...SDK_VERSION_HEADERS },\n body: query,\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Country } from '../geography';\n\nexport enum ShippingCountryActionType {\n LoadShippingCountriesRequested = 'LOAD_SHIPPING_COUNTRIES_REQUESTED',\n LoadShippingCountriesSucceeded = 'LOAD_SHIPPING_COUNTRIES_SUCCEEDED',\n LoadShippingCountriesFailed = 'LOAD_SHIPPING_COUNTRIES_FAILED',\n}\n\nexport type LoadShippingCountriesAction =\n | LoadShippingCountriesRequestedAction\n | LoadShippingCountriesSucceededAction\n | LoadShippingCountriesFailedAction;\n\nexport interface LoadShippingCountriesRequestedAction extends Action {\n type: ShippingCountryActionType.LoadShippingCountriesRequested;\n}\n\nexport interface LoadShippingCountriesSucceededAction extends Action {\n type: ShippingCountryActionType.LoadShippingCountriesSucceeded;\n}\n\nexport interface LoadShippingCountriesFailedAction extends Action {\n type: ShippingCountryActionType.LoadShippingCountriesFailed;\n}\n","import { createAction, createErrorAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { RequestOptions } from '../common/http-request';\n\nimport { LoadShippingCountriesAction, ShippingCountryActionType } from './shipping-country-actions';\nimport ShippingCountryRequestSender from './shipping-country-request-sender';\n\nexport default class ShippingCountryActionCreator {\n constructor(private _shippingCountryRequestSender: ShippingCountryRequestSender) {}\n\n loadCountries(options?: RequestOptions): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(createAction(ShippingCountryActionType.LoadShippingCountriesRequested));\n\n this._shippingCountryRequestSender\n .loadCountries(options)\n .then((response) => {\n observer.next(\n createAction(\n ShippingCountryActionType.LoadShippingCountriesSucceeded,\n response.body.data,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ShippingCountryActionType.LoadShippingCountriesFailed,\n response,\n ),\n );\n });\n });\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\nimport { CountryResponseBody } from '../geography';\n\nexport default class ShippingCountryRequestSender {\n constructor(private _requestSender: RequestSender, private _config: { locale?: string }) {}\n\n loadCountries({ timeout }: RequestOptions = {}): Promise> {\n const url = '/internalapi/v1/shipping/countries';\n const headers = {\n 'Accept-Language': this._config.locale,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.get(url, { headers, timeout });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nexport enum ShippingStrategyActionType {\n UpdateAddressFailed = 'SHIPPING_STRATEGY_UPDATE_ADDRESS_FAILED',\n UpdateAddressRequested = 'SHIPPING_STRATEGY_UPDATE_ADDRESS_REQUESTED',\n UpdateAddressSucceeded = 'SHIPPING_STRATEGY_UPDATE_ADDRESS_SUCCEEDED',\n SelectOptionFailed = 'SHIPPING_STRATEGY_SELECT_OPTION_FAILED',\n SelectOptionRequested = 'SHIPPING_STRATEGY_SELECT_OPTION_REQUESTED',\n SelectOptionSucceeded = 'SHIPPING_STRATEGY_SELECT_OPTION_SUCCEEDED',\n InitializeFailed = 'SHIPPING_STRATEGY_INITIALIZE_FAILED',\n InitializeRequested = 'SHIPPING_STRATEGY_INITIALIZE_REQUESTED',\n InitializeSucceeded = 'SHIPPING_STRATEGY_INITIALIZE_SUCCEEDED',\n DeinitializeFailed = 'SHIPPING_STRATEGY_DEINITIALIZE_FAILED',\n DeinitializeRequested = 'SHIPPING_STRATEGY_DEINITIALIZE_REQUESTED',\n DeinitializeSucceeded = 'SHIPPING_STRATEGY_DEINITIALIZE_SUCCEEDED',\n WidgetInteractionStarted = 'SHIPPING_STRATEGY_WIDGET_INTERACTION_STARTED',\n WidgetInteractionFinished = 'SHIPPING_STRATEGY_WIDGET_INTERACTION_FINISHED',\n WidgetInteractionFailed = 'SHIPPING_STRATEGY_WIDGET_INTERACTION_FAILED',\n}\n\nexport type ShippingStrategyAction =\n | ShippingStrategyUpdateAddressAction\n | ShippingStrategySelectOptionAction\n | ShippingStrategyInitializeAction\n | ShippingStrategyDeinitializeAction\n | ShippingStrategyWidgetAction;\n\nexport type ShippingStrategyUpdateAddressAction =\n | UpdateAddressRequestedAction\n | UpdateAddressSucceededAction\n | UpdateAddressFailedAction;\n\nexport type ShippingStrategySelectOptionAction =\n | SelectOptionRequestedAction\n | SelectOptionSucceededAction\n | SelectOptionFailedAction;\n\nexport type ShippingStrategyInitializeAction =\n | InitializeRequestedAction\n | InitializeSucceededAction\n | InitializeFailedAction;\n\nexport type ShippingStrategyDeinitializeAction =\n | DeinitializeRequestedAction\n | DeinitializeSucceededAction\n | DeinitializeFailedAction;\n\nexport type ShippingStrategyWidgetAction =\n | WidgetInteractionStartedAction\n | WidgetInteractionFinishedAction\n | WidgetInteractionFailedAction;\n\nexport interface UpdateAddressRequestedAction extends Action {\n type: ShippingStrategyActionType.UpdateAddressRequested;\n}\n\nexport interface UpdateAddressSucceededAction extends Action {\n type: ShippingStrategyActionType.UpdateAddressSucceeded;\n}\n\nexport interface UpdateAddressFailedAction extends Action {\n type: ShippingStrategyActionType.UpdateAddressFailed;\n}\n\nexport interface SelectOptionRequestedAction extends Action {\n type: ShippingStrategyActionType.SelectOptionRequested;\n}\n\nexport interface SelectOptionSucceededAction extends Action {\n type: ShippingStrategyActionType.SelectOptionSucceeded;\n}\n\nexport interface SelectOptionFailedAction extends Action {\n type: ShippingStrategyActionType.SelectOptionFailed;\n}\n\nexport interface InitializeRequestedAction extends Action {\n type: ShippingStrategyActionType.InitializeRequested;\n}\n\nexport interface InitializeSucceededAction extends Action {\n type: ShippingStrategyActionType.InitializeSucceeded;\n}\n\nexport interface InitializeFailedAction extends Action {\n type: ShippingStrategyActionType.InitializeFailed;\n}\n\nexport interface DeinitializeRequestedAction extends Action {\n type: ShippingStrategyActionType.DeinitializeRequested;\n}\n\nexport interface DeinitializeSucceededAction extends Action {\n type: ShippingStrategyActionType.DeinitializeSucceeded;\n}\n\nexport interface DeinitializeFailedAction extends Action {\n type: ShippingStrategyActionType.DeinitializeFailed;\n}\n\nexport interface WidgetInteractionStartedAction extends Action {\n type: ShippingStrategyActionType.WidgetInteractionStarted;\n}\n\nexport interface WidgetInteractionFinishedAction extends Action {\n type: ShippingStrategyActionType.WidgetInteractionFinished;\n}\n\nexport interface WidgetInteractionFailedAction extends Action {\n type: ShippingStrategyActionType.WidgetInteractionFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { AddressRequestBody } from '../address';\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { Registry } from '../common/registry';\n\nimport { ShippingInitializeOptions, ShippingRequestOptions } from './shipping-request-options';\nimport {\n ShippingStrategyAction,\n ShippingStrategyActionType,\n ShippingStrategyDeinitializeAction,\n ShippingStrategyInitializeAction,\n ShippingStrategySelectOptionAction,\n ShippingStrategyUpdateAddressAction,\n} from './shipping-strategy-actions';\nimport { ShippingStrategy } from './strategies';\n\nexport default class ShippingStrategyActionCreator {\n constructor(private _strategyRegistry: Registry) {}\n\n updateAddress(\n address: Partial,\n options?: ShippingRequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const payment = store.getState().payment.getPaymentId();\n const methodId = (options && options.methodId) || (payment && payment.providerId);\n\n observer.next(\n createAction(ShippingStrategyActionType.UpdateAddressRequested, undefined, {\n methodId,\n }),\n );\n\n this._strategyRegistry\n .get(methodId)\n .updateAddress(address, { ...options, methodId })\n .then(() => {\n observer.next(\n createAction(\n ShippingStrategyActionType.UpdateAddressSucceeded,\n undefined,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n ShippingStrategyActionType.UpdateAddressFailed,\n error,\n { methodId },\n ),\n );\n });\n });\n }\n\n selectOption(\n shippingOptionId: string,\n options?: ShippingRequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const payment = store.getState().payment.getPaymentId();\n const methodId = (options && options.methodId) || (payment && payment.providerId);\n\n observer.next(\n createAction(ShippingStrategyActionType.SelectOptionRequested, undefined, {\n methodId,\n }),\n );\n\n this._strategyRegistry\n .get(methodId)\n .selectOption(shippingOptionId, { ...options, methodId })\n .then(() => {\n observer.next(\n createAction(\n ShippingStrategyActionType.SelectOptionSucceeded,\n undefined,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n ShippingStrategyActionType.SelectOptionFailed,\n error,\n { methodId },\n ),\n );\n });\n });\n }\n\n initialize(\n options?: ShippingInitializeOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const payment = state.payment.getPaymentId();\n const methodId = (options && options.methodId) || (payment && payment.providerId);\n const mergedOptions = { ...options, methodId };\n\n if (methodId && state.shippingStrategies.isInitialized(methodId)) {\n return observer.complete();\n }\n\n observer.next(\n createAction(ShippingStrategyActionType.InitializeRequested, undefined, {\n methodId,\n }),\n );\n\n this._strategyRegistry\n .get(methodId)\n .initialize(mergedOptions)\n .then(() => {\n observer.next(\n createAction(\n ShippingStrategyActionType.InitializeSucceeded,\n undefined,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(ShippingStrategyActionType.InitializeFailed, error, {\n methodId,\n }),\n );\n });\n });\n }\n\n deinitialize(\n options?: ShippingRequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const payment = state.payment.getPaymentId();\n const methodId = (options && options.methodId) || (payment && payment.providerId);\n\n if (methodId && !state.shippingStrategies.isInitialized(methodId)) {\n return observer.complete();\n }\n\n observer.next(\n createAction(ShippingStrategyActionType.DeinitializeRequested, undefined, {\n methodId,\n }),\n );\n\n this._strategyRegistry\n .get(methodId)\n .deinitialize({ ...options, methodId })\n .then(() => {\n observer.next(\n createAction(\n ShippingStrategyActionType.DeinitializeSucceeded,\n undefined,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n ShippingStrategyActionType.DeinitializeFailed,\n error,\n { methodId },\n ),\n );\n });\n });\n }\n\n widgetInteraction(\n method: () => Promise,\n options?: ShippingRequestOptions,\n ): Observable {\n return Observable.create((observer: Observer) => {\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n observer.next(\n createAction(ShippingStrategyActionType.WidgetInteractionStarted, undefined, meta),\n );\n\n method()\n .then(() => {\n observer.next(\n createAction(\n ShippingStrategyActionType.WidgetInteractionFinished,\n undefined,\n meta,\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n ShippingStrategyActionType.WidgetInteractionFailed,\n error,\n meta,\n ),\n );\n });\n });\n }\n}\n","import { noop } from 'rxjs';\n\nimport { ConsignmentActionCreator, ShippingStrategyActionCreator } from '../..';\nimport { AddressRequestBody } from '../../../address';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../../../common/error/errors';\nimport { PaymentMethodActionCreator } from '../../../payment';\nimport {\n AmazonPayV2ChangeActionType,\n AmazonPayV2PaymentProcessor,\n} from '../../../payment/strategies/amazon-pay-v2';\nimport { ShippingInitializeOptions, ShippingRequestOptions } from '../../shipping-request-options';\nimport ShippingStrategy from '../shipping-strategy';\n\nexport default class AmazonPayV2ShippingStrategy implements ShippingStrategy {\n constructor(\n private _store: CheckoutStore,\n private _consignmentActionCreator: ConsignmentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _amazonPayV2PaymentProcessor: AmazonPayV2PaymentProcessor,\n private _shippingStrategyActionCreator: ShippingStrategyActionCreator,\n ) {}\n\n updateAddress(\n address: AddressRequestBody,\n options?: ShippingRequestOptions,\n ): Promise {\n const shippingAddress = this._store.getState().shippingAddress.getShippingAddress();\n\n if (!shippingAddress) {\n throw new MissingDataError(MissingDataErrorType.MissingShippingAddress);\n }\n\n const updateAddressRequestBody = {\n ...shippingAddress,\n customFields: address.customFields,\n };\n\n return this._store.dispatch(\n this._consignmentActionCreator.updateAddress(updateAddressRequestBody, options),\n );\n }\n\n selectOption(\n optionId: string,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(\n this._consignmentActionCreator.selectShippingOption(optionId, options),\n );\n }\n\n async initialize(options: ShippingInitializeOptions): Promise {\n const { amazonpay, methodId } = options;\n\n if (!amazonpay || !methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"options.amazonpay\" argument is not provided.',\n );\n }\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n await this._amazonPayV2PaymentProcessor.initialize(paymentMethod);\n\n const { paymentToken, region } = paymentMethod.initializationData;\n const buttonId = amazonpay.editAddressButtonId;\n\n if (paymentToken && buttonId) {\n const shouldShowLoadingSpinner = this._shouldShowLoadingSpinner(region);\n\n this._bindEditButton(buttonId, paymentToken, 'changeAddress', shouldShowLoadingSpinner);\n }\n\n return this._store.getState();\n }\n\n async deinitialize(): Promise {\n await this._amazonPayV2PaymentProcessor.deinitialize();\n\n return Promise.resolve(this._store.getState());\n }\n\n private _bindEditButton(\n id: string,\n sessionId: string,\n changeAction: AmazonPayV2ChangeActionType,\n shouldShowLoadingSpinner: boolean,\n ): void {\n const button = document.getElementById(id);\n\n if (!button || !button.parentNode) {\n return;\n }\n\n if (shouldShowLoadingSpinner) {\n const clone = button.cloneNode(true);\n\n button.parentNode.replaceChild(clone, button);\n\n clone.addEventListener('click', () => this._showLoadingSpinner());\n }\n\n this._amazonPayV2PaymentProcessor.bindButton(id, sessionId, changeAction);\n }\n\n private _showLoadingSpinner(): Promise {\n return this._store.dispatch(\n this._shippingStrategyActionCreator.widgetInteraction(() => new Promise(noop)),\n { queueId: 'widgetInteraction' },\n );\n }\n\n private _shouldShowLoadingSpinner(region: string) {\n return region !== 'us';\n }\n}\n","import { AddressRequestBody } from '../../../address';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport ConsignmentActionCreator from '../../consignment-action-creator';\nimport { ShippingRequestOptions } from '../../shipping-request-options';\nimport ShippingStrategy from '../shipping-strategy';\n\nexport default class DefaultShippingStrategy implements ShippingStrategy {\n constructor(\n private _store: CheckoutStore,\n private _consignmentActionCreator: ConsignmentActionCreator,\n ) {}\n\n updateAddress(\n address: AddressRequestBody,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(this._consignmentActionCreator.updateAddress(address, options));\n }\n\n selectOption(\n optionId: string,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(\n this._consignmentActionCreator.selectShippingOption(optionId, options),\n );\n }\n\n initialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n}\n","import { AddressRequestBody } from '../../../address';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../../../common/error/errors';\nimport { PaymentMethodActionCreator } from '../../../payment';\nimport {\n DisplayName,\n StripeElements,\n StripeElementsCreateOptions,\n StripeElementType,\n StripeEventType,\n StripeFormMode,\n StripeScriptLoader,\n StripeUPEAppearanceOptions,\n StripeUPEClient,\n} from '../../../payment/strategies/stripe-upe';\nimport ConsignmentActionCreator from '../../consignment-action-creator';\nimport { ShippingInitializeOptions, ShippingRequestOptions } from '../../shipping-request-options';\nimport ShippingStrategy from '../shipping-strategy';\n\nexport default class StripeUPEShippingStrategy implements ShippingStrategy {\n private _stripeUPEClient?: StripeUPEClient;\n private _stripeElements?: StripeElements;\n private sendData?: ReturnType;\n\n constructor(\n private _store: CheckoutStore,\n private _stripeUPEScriptLoader: StripeScriptLoader,\n private _consignmentActionCreator: ConsignmentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n ) {}\n\n updateAddress(\n address: AddressRequestBody,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(this._consignmentActionCreator.updateAddress(address, options));\n }\n\n selectOption(\n optionId: string,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(\n this._consignmentActionCreator.selectShippingOption(optionId, options),\n );\n }\n\n async initialize(options: ShippingInitializeOptions): Promise {\n if (!options.stripeupe) {\n throw new InvalidArgumentError(\n `Unable to proceed because \"options\" argument is not provided.`,\n );\n }\n\n const {\n container,\n gatewayId,\n methodId,\n onChangeShipping,\n getStyles,\n availableCountries,\n getStripeState,\n } = options.stripeupe;\n\n Object.entries(options.stripeupe).forEach(([key, value]) => {\n if (!value) {\n throw new InvalidArgumentError(\n `Unable to proceed because \"${key}\" argument is not provided.`,\n );\n }\n });\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n }),\n );\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId, gatewayId);\n const {\n initializationData: { stripePublishableKey, stripeConnectedAccount },\n } = paymentMethod;\n\n if (\n !paymentMethod ||\n !paymentMethod.initializationData.stripePublishableKey ||\n !paymentMethod.clientToken\n ) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._stripeUPEClient = await this._stripeUPEScriptLoader.getStripeClient(\n stripePublishableKey,\n stripeConnectedAccount,\n );\n\n let appearance: StripeUPEAppearanceOptions;\n const styles = getStyles && getStyles();\n\n const {\n form: { getShippingAddressFields },\n shippingAddress: { getShippingAddress },\n } = this._store.getState();\n\n const shippingFields = getShippingAddressFields([], '');\n\n if (styles) {\n appearance = {\n variables: {\n colorPrimary: styles.fieldInnerShadow,\n colorBackground: styles.fieldBackground,\n colorText: styles.labelText,\n colorDanger: styles.fieldErrorText,\n colorTextSecondary: styles.labelText,\n colorTextPlaceholder: styles.fieldPlaceholderText,\n spacingUnit: '4px',\n borderRadius: '4px',\n },\n rules: {\n '.Input': {\n borderColor: styles.fieldBorder,\n color: styles.fieldText,\n boxShadow: styles.fieldInnerShadow,\n },\n },\n };\n } else {\n appearance = {\n variables: {\n spacingUnit: '4px',\n borderRadius: '4px',\n },\n };\n }\n\n this._stripeElements = this._stripeUPEScriptLoader.getElements(this._stripeUPEClient, {\n clientSecret: paymentMethod.clientToken,\n appearance,\n });\n\n const shipping = getShippingAddress();\n const shippingPhoneField = shippingFields.find((field) => field.name === 'phone');\n let option: StripeElementsCreateOptions = {\n mode: StripeFormMode.SHIPPING,\n allowedCountries: [availableCountries],\n fields: {\n phone: 'always',\n },\n validation: {\n phone: {\n required:\n shippingPhoneField && shippingPhoneField.required ? 'always' : 'never',\n },\n },\n display: {\n name: DisplayName.SPLIT,\n },\n };\n\n if (shipping) {\n const {\n stateOrProvinceCode,\n countryCode,\n lastName,\n firstName,\n phone,\n address1,\n address2,\n city,\n postalCode,\n } = shipping;\n const stripeState =\n stateOrProvinceCode && countryCode\n ? getStripeState(countryCode, stateOrProvinceCode)\n : stateOrProvinceCode;\n\n option = {\n ...option,\n defaultValues: {\n firstName,\n lastName,\n phone,\n address: {\n line1: address1,\n line2: address2,\n city,\n state: stripeState,\n postal_code: postalCode,\n country: countryCode,\n },\n },\n };\n }\n\n let shippingAddressElement = this._stripeElements.getElement(StripeElementType.SHIPPING);\n\n if (shippingAddressElement) {\n shippingAddressElement.destroy();\n }\n\n shippingAddressElement = this._stripeElements.create(StripeElementType.SHIPPING, option);\n\n shippingAddressElement.on('change', (event: StripeEventType) => {\n if (!('isNewAddress' in event)) {\n throw new MissingDataError(MissingDataErrorType.MissingShippingAddress);\n }\n\n if (event.complete || event.isNewAddress) {\n if (this.sendData) {\n clearTimeout(this.sendData);\n }\n\n this.sendData = setTimeout(() => {\n onChangeShipping({\n ...event,\n phoneFieldRequired: shippingPhoneField\n ? shippingPhoneField.required\n : false,\n });\n }, 1000);\n }\n });\n\n shippingAddressElement.mount(`#${container}`);\n\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n /* The new shipping component by StripeLink has a small bug, when the component is unmounted,\n Stripe does not save the shipping, to solve this, we will leave it mounted,\n and once it is fixed will be unmounted again */\n\n // this._stripeElements?.getElement(StripeElementType.SHIPPING)?.unmount();\n\n return Promise.resolve(this._store.getState());\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { SignInEmail } from './signin-email';\n\nexport enum SignInEmailActionType {\n SendSignInEmailRequested = 'SEND_SIGNIN_EMAIL_REQUESTED',\n SendSignInEmailSucceeded = 'SEND_SIGNIN_EMAIL_SUCCEEDED',\n SendSignInEmailFailed = 'SEND_SIGNIN_EMAIL_FAILED',\n}\nexport type SendSignInEmailAction =\n | SendSignInEmailRequestedAction\n | SendSignInEmailSucceededAction\n | SendSignInEmailFailedAction;\n\nexport interface SendSignInEmailRequestedAction extends Action {\n type: SignInEmailActionType.SendSignInEmailRequested;\n}\n\nexport interface SendSignInEmailSucceededAction extends Action {\n type: SignInEmailActionType.SendSignInEmailSucceeded;\n}\n\nexport interface SendSignInEmailFailedAction extends Action {\n type: SignInEmailActionType.SendSignInEmailFailed;\n}\n","import { createAction } from '@bigcommerce/data-store';\nimport { concat, defer, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { throwErrorAction } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\n\nimport { SignInEmailRequestBody } from './signin-email';\nimport { SendSignInEmailAction, SignInEmailActionType } from './signin-email-actions';\nimport SignInEmailRequestSender from './signin-email-request-sender';\n\nexport default class SignInEmailActionCreator {\n constructor(private _requestSender: SignInEmailRequestSender) {}\n\n sendSignInEmail(\n emailRequest: SignInEmailRequestBody,\n options?: RequestOptions,\n ): Observable {\n return concat(\n of(createAction(SignInEmailActionType.SendSignInEmailRequested)),\n defer(async () => {\n const { body } = await this._requestSender.sendSignInEmail(emailRequest, options);\n\n return createAction(SignInEmailActionType.SendSignInEmailSucceeded, body);\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(SignInEmailActionType.SendSignInEmailFailed, error),\n ),\n );\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { ContentType, RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\nimport { parseUrl } from '../common/url';\n\nimport { SignInEmail, SignInEmailRequestBody } from './signin-email';\n\nexport default class SignInEmailRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n sendSignInEmail(\n { email, redirectUrl }: SignInEmailRequestBody,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = '/login.php?action=passwordless_login';\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, {\n body: {\n email,\n redirect_url: redirectUrl || parseUrl(window.top.location.href).pathname,\n },\n headers,\n timeout,\n });\n }\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"reselect\");","import { memoize } from '@bigcommerce/memoize';\nimport { createSelector as defaultSelectorCreator } from 'reselect';\n\n/**\n * Decorate selector creators with the ability to memoize the return value of\n * their combiner if it is a function (which effectively works as a partially\n * applied combiner).\n */\nexport default function withMemoizedCombiner(\n creator: T,\n): T {\n return ((...args: any[]) => {\n const combiner = args.pop();\n\n // Reselect's default `createSelector` has many overloads. To avoid having\n // to redefine all of them, we're using `any` to bypass the typechecker.\n return (creator as any)(...args, (...combinerArgs: any[]) => {\n // Although there are many overloads, all of them have the last argument\n // as the combiner.\n const result = combiner(...combinerArgs);\n\n if (typeof result === 'function') {\n return memoize(result);\n }\n\n return result;\n });\n }) as T;\n}\n","import { createSelector as defaultSelectorCreator } from 'reselect';\n\nimport withMemoizedCombiner from './with-memoized-combiner';\n\n/**\n * This is a decorated version of Reselect's default `createSelector` function.\n * If the return value of the combiner function is a function, it will create a\n * memorized version of that function and return it instead.\n */\nexport default withMemoizedCombiner(defaultSelectorCreator);\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"shallowequal\");","import { createSelectorCreator, defaultMemoize } from 'reselect';\nimport shallowEqual from 'shallowequal';\n\nimport withMemoizedCombiner from './with-memoized-combiner';\n\nconst createShallowEqualSelector = createSelectorCreator(defaultMemoize, (a: any, b: any) =>\n shallowEqual(a, b),\n);\n\nexport default withMemoizedCombiner(createShallowEqualSelector);\n","import { toSingleLine } from '../utility';\n\nexport default class ErrorMessageTransformer {\n constructor(private _messageCustomizer: (type: TError) => string) {}\n\n transform(error: TError): TError {\n error.message = toSingleLine(this._messageCustomizer(error));\n\n return error;\n }\n}\n","export default function toSingleLine(input?: string) {\n if (!input) {\n return '';\n }\n\n return input\n .split(/(?:\\r\\n|\\n|\\r)/)\n .map((line) => line.replace(/^\\s+/gm, ''))\n .join(' ')\n .trim();\n}\n","import { Action, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable } from 'rxjs';\n\nimport { AddressRequestBody } from '../address';\nimport { BillingAddressActionCreator, BillingAddressRequestBody } from '../billing';\nimport { createDataStoreProjection, DataStoreProjection } from '../common/data-store';\nimport { ErrorActionCreator, ErrorMessageTransformer } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\nimport { bindDecorator as bind } from '../common/utility';\nimport { ConfigActionCreator } from '../config';\nimport { CouponActionCreator, GiftCertificateActionCreator } from '../coupon';\nimport {\n CustomerAccountRequestBody,\n CustomerActionCreator,\n CustomerAddressRequestBody,\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerRequestOptions,\n CustomerStrategyActionCreator,\n ExecutePaymentMethodCheckoutOptions,\n GuestCredentials,\n} from '../customer';\nimport { ExtensionActionCreator, ExtensionRegion } from '../extension';\nimport { FormFieldsActionCreator } from '../form';\nimport { CountryActionCreator } from '../geography';\nimport { OrderActionCreator, OrderRequestBody } from '../order';\nimport {\n PaymentInitializeOptions,\n PaymentMethodActionCreator,\n PaymentRequestOptions,\n PaymentStrategyActionCreator,\n} from '../payment';\nimport { InstrumentActionCreator } from '../payment/instrument';\nimport {\n ConsignmentActionCreator,\n ConsignmentAssignmentRequestBody,\n ConsignmentsRequestBody,\n ConsignmentUpdateRequestBody,\n PickupOptionActionCreator,\n PickupOptionRequestBody,\n ShippingCountryActionCreator,\n ShippingInitializeOptions,\n ShippingRequestOptions,\n ShippingStrategyActionCreator,\n} from '../shipping';\nimport { SignInEmailActionCreator, SignInEmailRequestBody } from '../signin-email';\nimport { SpamProtectionActionCreator, SpamProtectionOptions } from '../spam-protection';\nimport { StoreCreditActionCreator } from '../store-credit';\nimport { Subscriptions, SubscriptionsActionCreator } from '../subscription';\n\nimport { CheckoutRequestBody } from './checkout';\nimport CheckoutActionCreator from './checkout-action-creator';\nimport CheckoutParams from './checkout-params';\nimport CheckoutSelectors from './checkout-selectors';\nimport CheckoutStore from './checkout-store';\nimport {\n CheckoutSelectorsFactory,\n createCheckoutSelectorsFactory,\n} from './create-checkout-selectors';\nimport createCheckoutServiceErrorTransformer from './create-checkout-service-error-transformer';\n\n/**\n * Responsible for completing the checkout process for the current customer.\n *\n * This object can be used to collect all information that is required for\n * checkout, such as shipping and billing information. It can also be used to\n * retrieve the current checkout state and subscribe to its changes.\n */\n@bind\nexport default class CheckoutService {\n private _storeProjection: DataStoreProjection;\n private _errorTransformer: ErrorMessageTransformer;\n private _selectorsFactory: CheckoutSelectorsFactory;\n\n /**\n * @internal\n */\n constructor(\n private _store: CheckoutStore,\n private _billingAddressActionCreator: BillingAddressActionCreator,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _configActionCreator: ConfigActionCreator,\n private _customerActionCreator: CustomerActionCreator,\n private _consignmentActionCreator: ConsignmentActionCreator,\n private _countryActionCreator: CountryActionCreator,\n private _couponActionCreator: CouponActionCreator,\n private _customerStrategyActionCreator: CustomerStrategyActionCreator,\n private _errorActionCreator: ErrorActionCreator,\n private _giftCertificateActionCreator: GiftCertificateActionCreator,\n private _instrumentActionCreator: InstrumentActionCreator,\n private _orderActionCreator: OrderActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentStrategyActionCreator: PaymentStrategyActionCreator,\n private _pickupOptionActionCreator: PickupOptionActionCreator,\n private _shippingCountryActionCreator: ShippingCountryActionCreator,\n private _shippingStrategyActionCreator: ShippingStrategyActionCreator,\n private _signInEmailActionCreator: SignInEmailActionCreator,\n private _spamProtectionActionCreator: SpamProtectionActionCreator,\n private _storeCreditActionCreator: StoreCreditActionCreator,\n private _subscriptionsActionCreator: SubscriptionsActionCreator,\n private _formFieldsActionCreator: FormFieldsActionCreator,\n private _extensionActionCreator: ExtensionActionCreator,\n ) {\n this._errorTransformer = createCheckoutServiceErrorTransformer();\n this._selectorsFactory = createCheckoutSelectorsFactory();\n this._storeProjection = createDataStoreProjection(this._store, this._selectorsFactory);\n }\n\n /**\n * Returns a snapshot of the current checkout state.\n *\n * The method returns a new instance every time there is a change in the\n * checkout state. You can query the state by calling any of its getter\n * methods.\n *\n * ```js\n * const state = service.getState();\n *\n * console.log(state.data.getOrder());\n * console.log(state.errors.getSubmitOrderError());\n * console.log(state.statuses.isSubmittingOrder());\n * ```\n *\n * @returns The current customer's checkout state\n */\n getState(): CheckoutSelectors {\n return this._storeProjection.getState();\n }\n\n /**\n * Notifies all subscribers with the current state.\n *\n * When this method gets called, the subscribers get called regardless if\n * they have any filters applied.\n */\n notifyState(): void {\n this._storeProjection.notifyState();\n }\n\n /**\n * Subscribes to any changes to the current state.\n *\n * The method registers a callback function and executes it every time there\n * is a change in the checkout state.\n *\n * ```js\n * service.subscribe(state => {\n * console.log(state.data.getCart());\n * });\n * ```\n *\n * The method can be configured to notify subscribers only regarding\n * relevant changes, by providing a filter function.\n *\n * ```js\n * const filter = state => state.data.getCart();\n *\n * // Only trigger the subscriber when the cart changes.\n * service.subscribe(state => {\n * console.log(state.data.getCart())\n * }, filter);\n * ```\n *\n * @param subscriber - The function to subscribe to state changes.\n * @param filters - One or more functions to filter out irrelevant state\n * changes. If more than one function is provided, the subscriber will only\n * be triggered if all conditions are met.\n * @returns A function, if called, will unsubscribe the subscriber.\n */\n subscribe(\n subscriber: (state: CheckoutSelectors) => void,\n ...filters: Array<(state: CheckoutSelectors) => any>\n ): () => void {\n return this._storeProjection.subscribe(subscriber, ...filters);\n }\n\n /**\n * Loads the current checkout.\n *\n * This method can only be called if there is an active checkout. Also, it\n * can only retrieve data that belongs to the current customer. When it is\n * successfully executed, you can retrieve the data by calling\n * `CheckoutStoreSelector#getCheckout`.\n *\n * ```js\n * const state = await service.loadCheckout('0cfd6c06-57c3-4e29-8d7a-de55cc8a9052');\n *\n * console.log(state.data.getCheckout());\n * ```\n *\n * @param id - The identifier of the checkout to load, or the default checkout if not provided.\n * @param options - Options for loading the current checkout.\n * @returns A promise that resolves to the current state.\n */\n loadCheckout(\n id?: string,\n options?: RequestOptions,\n ): Promise {\n return this._dispatch(\n id\n ? this._checkoutActionCreator.loadCheckout(id, options)\n : this._checkoutActionCreator.loadDefaultCheckout(options),\n );\n }\n\n /**\n * Updates specific properties of the current checkout.\n *\n * ```js\n * const state = await service.updateCheckout(checkout);\n *\n * console.log(state.data.getCheckout());\n * ```\n *\n * @param payload - The checkout properties to be updated.\n * @param options - Options for loading the current checkout.\n * @returns A promise that resolves to the current state.\n */\n updateCheckout(\n payload: CheckoutRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._checkoutActionCreator.updateCheckout(payload, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Loads an order by an id.\n *\n * The method can only retrieve an order if the order belongs to the current\n * customer. If it is successfully executed, the data can be retrieved by\n * calling `CheckoutStoreSelector#getOrder`.\n *\n * ```js\n * const state = await service.loadOrder(123);\n *\n * console.log(state.data.getOrder());\n * ```\n *\n * @param orderId - The identifier of the order to load.\n * @param options - Options for loading the order.\n * @returns A promise that resolves to the current state.\n */\n loadOrder(orderId: number, options?: RequestOptions): Promise {\n const loadCheckoutAction = this._orderActionCreator.loadOrder(orderId, options);\n const formFieldsAction = this._formFieldsActionCreator.loadFormFields(options);\n const loadConfigAction = this._configActionCreator.loadConfig(options);\n\n return Promise.all([\n this._dispatch(loadCheckoutAction),\n this._dispatch(loadConfigAction, { queueId: 'config' }),\n this._dispatch(formFieldsAction, { queueId: 'formFields' }),\n ]).then(() => this.getState());\n }\n\n /**\n * Submits an order, thereby completing a checkout process.\n *\n * Before you can submit an order, you must initialize the payment method\n * chosen by the customer by calling `CheckoutService#initializePayment`.\n *\n * ```js\n * await service.initializePayment({ methodId: 'braintree' });\n * await service.submitOrder({\n * payment: {\n * methodId: 'braintree',\n * paymentData: {\n * ccExpiry: { month: 10, year: 20 },\n * ccName: 'BigCommerce',\n * ccNumber: '4111111111111111',\n * ccCvv: 123,\n * },\n * },\n * });\n * ```\n *\n * You are not required to include `paymentData` if the order does not\n * require additional payment details. For example, the customer has already\n * entered their payment details on the cart page using one of the hosted\n * payment methods, such as PayPal. Or the customer has applied a gift\n * certificate that exceeds the grand total amount.\n *\n * If the order is submitted successfully, you can retrieve the newly\n * created order by calling `CheckoutStoreSelector#getOrder`.\n *\n * ```js\n * const state = await service.submitOrder(payload);\n *\n * console.log(state.data.getOrder());\n * ```\n *\n * @param payload - The request payload to submit for the current order.\n * @param options - Options for submitting the current order.\n * @returns A promise that resolves to the current state.\n */\n submitOrder(payload: OrderRequestBody, options?: RequestOptions): Promise {\n const action = this._paymentStrategyActionCreator.execute(payload, options);\n\n return this._dispatch(action, { queueId: 'paymentStrategy' });\n }\n\n /**\n * Finalizes the submission process for an order.\n *\n * This method is only required for certain hosted payment methods that\n * require a customer to enter their credit card details on their website.\n * You need to call this method once the customer has redirected back to\n * checkout in order to complete the checkout process.\n *\n * If the method is called before order finalization is required or for a\n * payment method that does not require order finalization, an error will be\n * thrown. Conversely, if the method is called successfully, you should\n * immediately redirect the customer to the order confirmation page.\n *\n * ```js\n * try {\n * await service.finalizeOrderIfNeeded();\n *\n * window.location.assign('/order-confirmation');\n * } catch (error) {\n * if (error.type !== 'order_finalization_not_required') {\n * throw error;\n * }\n * }\n * ```\n *\n * @param options - Options for finalizing the current order.\n * @returns A promise that resolves to the current state.\n * @throws `OrderFinalizationNotRequiredError` error if order finalization\n * is not required for the current order at the time of execution.\n */\n finalizeOrderIfNeeded(options?: RequestOptions): Promise {\n const action = this._paymentStrategyActionCreator.finalize(options);\n\n return this._dispatch(action, { queueId: 'paymentStrategy' });\n }\n\n /**\n * Loads a list of payment methods available for checkout.\n *\n * If a customer enters their payment details before navigating to the\n * checkout page (i.e.: using PayPal checkout button on the cart page), only\n * one payment method will be available for the customer - the selected\n * payment method. Otherwise, by default, all payment methods configured by\n * the merchant will be available for the customer.\n *\n * Once the method is executed successfully, you can call\n * `CheckoutStoreSelector#getPaymentMethods` to retrieve the list of payment\n * methods.\n *\n * ```js\n * const state = service.loadPaymentMethods();\n *\n * console.log(state.data.getPaymentMethods());\n * ```\n *\n * @param options - Options for loading the payment methods that are\n * available to the current customer.\n * @returns A promise that resolves to the current state.\n */\n loadPaymentMethods(options?: RequestOptions): Promise {\n const action = this._paymentMethodActionCreator.loadPaymentMethods(options);\n\n return this._dispatch(action, { queueId: 'paymentMethods' });\n }\n\n /**\n * Loads a payment method by an id.\n *\n * This method does not work with multi-option payment providers. Due to its\n * limitation, it is deprecated and will be removed in the future.\n *\n * @deprecated\n * @internal\n * @param methodId - The identifier for the payment method to load.\n * @param options - Options for loading the payment method.\n * @returns A promise that resolves to the current state.\n */\n loadPaymentMethod(methodId: string, options?: RequestOptions): Promise {\n const action = this._paymentMethodActionCreator.loadPaymentMethod(methodId, options);\n\n return this._dispatch(action, { queueId: 'paymentMethods' });\n }\n\n /**\n * Initializes the payment step of a checkout process.\n *\n * Before a payment method can accept payment details, it must first be\n * initialized. Some payment methods require you to provide additional\n * initialization options. For example, you can provide an element ID for\n * Amazon Pay if you want users to be able to select a different payment\n * method by clicking on the element.\n *\n * ```js\n * await service.initializePayment({\n * methodId: 'amazonpay',\n * amazonpay: {\n * editButtonId: 'edit-button',\n * },\n * });\n * ```\n *\n * @param options - Options for initializing the payment step of checkout.\n * @returns A promise that resolves to the current state.\n */\n initializePayment(options: PaymentInitializeOptions): Promise {\n const action = this._paymentStrategyActionCreator.initialize(options);\n\n return this._dispatch(action, { queueId: 'paymentStrategy' });\n }\n\n /**\n * De-initializes the payment step of a checkout process.\n *\n * The method should be called once you no longer require a payment method\n * to be initialized. It can perform any necessary clean-up behind the\n * scene, i.e.: remove DOM nodes or event handlers that are attached as a\n * result of payment initialization.\n *\n * ```js\n * await service.deinitializePayment({\n * methodId: 'amazonpay',\n * });\n * ```\n *\n * @param options - Options for deinitializing the payment step of checkout.\n * @returns A promise that resolves to the current state.\n */\n deinitializePayment(options: PaymentRequestOptions): Promise {\n const action = this._paymentStrategyActionCreator.deinitialize(options);\n\n return this._dispatch(action, { queueId: 'paymentStrategy' });\n }\n\n /**\n * Loads a list of countries available for billing.\n *\n * Once you make a successful request, you will be able to retrieve the list\n * of countries by calling `CheckoutStoreSelector#getBillingCountries`.\n *\n * ```js\n * const state = await service.loadBillingCountries();\n *\n * console.log(state.data.getBillingCountries());\n * ```\n *\n * @param options - Options for loading the available billing countries.\n * @returns A promise that resolves to the current state.\n */\n loadBillingCountries(options?: RequestOptions): Promise {\n const action = this._countryActionCreator.loadCountries(options);\n\n return this._dispatch(action, { queueId: 'billingCountries' });\n }\n\n /**\n * Loads a list of countries available for shipping.\n *\n * The list is determined based on the shipping zones configured by a\n * merchant. Once you make a successful call, you will be able to retrieve\n * the list of available shipping countries by calling\n * `CheckoutStoreSelector#getShippingCountries`.\n *\n * ```js\n * const state = await service.loadShippingCountries();\n *\n * console.log(state.data.getShippingCountries());\n * ```\n *\n * @param options - Options for loading the available shipping countries.\n * @returns A promise that resolves to the current state.\n */\n loadShippingCountries(options?: RequestOptions): Promise {\n const action = this._shippingCountryActionCreator.loadCountries(options);\n\n return this._dispatch(action, { queueId: 'shippingCountries' });\n }\n\n /**\n * Loads a list of pickup options for a given criteria.\n *\n * ```js\n * const consignmentId = '1';\n * const searchArea = {\n * radius: {\n * value: 1.4,\n * unit: 'KM'\n * },\n * coordinates: {\n * latitude: 1.4,\n * longitude: 0\n * },\n * };\n * const state = await service.loadPickupOptions({ consignmentId, searchArea });\n *\n * console.log(state.data.getPickupOptions(consignmentId, searchArea));\n * ```\n *\n * @alpha\n * @param options - Options for loading the available shipping countries.\n * @returns A promise that resolves to the current state.\n */\n loadPickupOptions(query: PickupOptionRequestBody): Promise {\n const action = this._pickupOptionActionCreator.loadPickupOptions(query);\n\n return this._dispatch(action, { queueId: 'pickupOptions' });\n }\n\n /**\n * Loads a set of form fields that should be presented to customers in order\n * to capture their billing address.\n *\n * Once the method has been executed successfully, you can call\n * `CheckoutStoreSelector#getBillingAddressFields` to retrieve the set of\n * form fields.\n *\n * ```js\n * const state = service.loadBillingAddressFields();\n *\n * console.log(state.data.getBillingAddressFields('US'));\n * ```\n *\n * @param options - Options for loading the billing address form fields.\n * @returns A promise that resolves to the current state.\n */\n loadBillingAddressFields(options?: RequestOptions): Promise {\n return this.loadBillingCountries(options);\n }\n\n /**\n * Loads a set of form fields that should be presented to customers in order\n * to capture their shipping address.\n *\n * Once the method has been executed successfully, you can call\n * `CheckoutStoreSelector#getShippingAddressFields` to retrieve the set of\n * form fields.\n *\n * ```js\n * const state = service.loadShippingAddressFields();\n *\n * console.log(state.data.getShippingAddressFields('US'));\n * ```\n *\n * @param options - Options for loading the shipping address form fields.\n * @returns A promise that resolves to the current state.\n */\n loadShippingAddressFields(options?: RequestOptions): Promise {\n return this.loadShippingCountries(options);\n }\n\n /**\n * Initializes the sign-in step of a checkout process.\n *\n * Some payment methods, such as Amazon Pay, have their own sign-in flow. In\n * order to support them, this method must be called.\n *\n * ```js\n * await service.initializeCustomer({\n * methodId: 'amazonpay',\n * amazonpay: {\n * container: 'signInButton',\n * },\n * });\n * ```\n *\n * @param options - Options for initializing the customer step of checkout.\n * @returns A promise that resolves to the current state.\n */\n initializeCustomer(options?: CustomerInitializeOptions): Promise {\n const action = this._customerStrategyActionCreator.initialize(options);\n\n return this._dispatch(action, { queueId: 'customerStrategy' });\n }\n\n /**\n * De-initializes the sign-in step of a checkout process.\n *\n * It should be called once you no longer want to prompt customers to sign\n * in. It can perform any necessary clean-up behind the scene, i.e.: remove\n * DOM nodes or event handlers that are attached as a result of customer\n * initialization.\n *\n * ```js\n * await service.deinitializeCustomer({\n * methodId: 'amazonpay',\n * });\n * ```\n *\n * @param options - Options for deinitializing the customer step of checkout.\n * @returns A promise that resolves to the current state.\n */\n deinitializeCustomer(options?: CustomerRequestOptions): Promise {\n const action = this._customerStrategyActionCreator.deinitialize(options);\n\n return this._dispatch(action, { queueId: 'customerStrategy' });\n }\n\n /**\n * Sends a email that contains a single-use sign-in link. When a valid links is clicked,\n * signs in the customer without requiring any password, redirecting them to the account page if no redirectUrl is provided.\n *\n *\n * ```js\n * checkoutService.sendSignInEmail({ email: 'foo@bar.com', redirectUrl: 'checkout' });\n * ```\n *\n * @param signInEmailRequest - The sign-in email request values.\n * @param options - Options for the send email request.\n * @returns A promise that resolves to the current state.\n */\n sendSignInEmail(\n signInEmailRequest: SignInEmailRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._signInEmailActionCreator.sendSignInEmail(signInEmailRequest, options);\n\n return this._dispatch(action, { queueId: 'signInEmail' });\n }\n\n /**\n * Creates a customer account.\n *\n * @remarks\n * ```js\n * checkoutService.createCustomerAccount({\n * email: 'foo@bar.com',\n * firstName: 'Foo',\n * lastName: 'Bar',\n * password: 'password',\n * acceptsMarketingEmails: true,\n * customFields: [],\n * });\n * ```\n * Please note that `createCustomerAccount` is currently in an early stage\n * of development. Therefore the API is unstable and not ready for public\n * consumption.\n *\n * @alpha\n * @param customerAccount - The customer account data.\n * @param options - Options for creating customer account.\n * @returns A promise that resolves to the current state.\n */\n createCustomerAccount(\n customerAccount: CustomerAccountRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._customerActionCreator.createCustomer(customerAccount, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Creates a customer account address.\n *\n * @remarks\n * ```js\n * checkoutService.createCustomerAddress({\n * firstName: 'Foo',\n * lastName: 'Bar',\n * address1: '55 Market St',\n * stateOrProvinceCode: 'CA',\n * countryCode: 'US',\n * postalCode: '90110',\n * customFields: [],\n * });\n * ```\n * Please note that `createCustomerAccountAddress` is currently in an early stage\n * of development. Therefore the API is unstable and not ready for public\n * consumption.\n *\n * @alpha\n * @param customerAddress - The customer account data.\n * @param options - Options for creating customer account.\n * @returns A promise that resolves to the current state.\n */\n createCustomerAddress(\n customerAddress: CustomerAddressRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._customerActionCreator.createAddress(customerAddress, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Updates the subscriptions associated to an email.\n *\n * @param subscriptions - The email and associated subscriptions to update.\n * @param options - Options for continuing as a guest.\n * @returns A promise that resolves to the current state.\n */\n updateSubscriptions(\n subscriptions: Subscriptions,\n options?: RequestOptions,\n ): Promise {\n const action = this._subscriptionsActionCreator.updateSubscriptions(subscriptions, options);\n\n return this._dispatch(action, { queueId: 'subscriptions' });\n }\n\n /**\n * Continues to check out as a guest.\n *\n * If your Checkout Settings allow it, your customers could continue the checkout as guests (without signing in).\n * If you have enabled the checkout setting \"Prompt existing accounts to sign in\", this information is\n * exposed as part of the [Customer](../interfaces/customer.md) object.\n *\n * Once they provide their email address, it will be stored as\n * part of their [billing address](../interfaces/billingaddress.md).\n *\n * @param credentials - The guest credentials to use, with optional subscriptions.\n * @param options - Options for continuing as a guest.\n * @returns A promise that resolves to the current state.\n */\n continueAsGuest(\n credentials: GuestCredentials,\n options?: RequestOptions,\n ): Promise {\n const action = this._billingAddressActionCreator.continueAsGuest(credentials, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Signs into a customer's registered account.\n *\n * Once the customer is signed in successfully, the checkout state will be\n * populated with information associated with the customer, such as their\n * saved addresses. You can call `CheckoutStoreSelector#getCustomer` to\n * retrieve the data.\n *\n * ```js\n * const state = await service.signInCustomer({\n * email: 'foo@bar.com',\n * password: 'password123',\n * });\n *\n * console.log(state.data.getCustomer());\n * ```\n *\n * @param credentials - The credentials to be used for signing in the customer.\n * @param options - Options for signing in the customer.\n * @returns A promise that resolves to the current state.\n */\n signInCustomer(\n credentials: CustomerCredentials,\n options?: CustomerRequestOptions,\n ): Promise {\n const action = this._customerStrategyActionCreator.signIn(credentials, options);\n\n return this._dispatch(action, { queueId: 'customerStrategy' });\n }\n\n /**\n * Signs out the current customer if they are previously signed in.\n *\n * Once the customer is successfully signed out, the checkout state will be\n * reset automatically.\n *\n * ```js\n * const state = await service.signOutCustomer();\n *\n * // The returned object should not contain information about the previously signed-in customer.\n * console.log(state.data.getCustomer());\n * ```\n *\n * When a store has \"Allow customers to access their cart across multiple devices\" enabled, signing out\n * will remove the cart/checkout data from the current session. An error with type=\"checkout_not_available\" will be thrown.\n *\n * ```js\n * try {\n * await service.signOutCustomer();\n * } catch (error) {\n * if (error.type === 'checkout_not_available') {\n * window.top.location.assign('/');\n * }\n * }\n * ```\n *\n * @param options - Options for signing out the customer.\n * @returns A promise that resolves to the current state.\n */\n signOutCustomer(options?: CustomerRequestOptions): Promise {\n const action = this._customerStrategyActionCreator.signOut(options);\n\n return this._dispatch(action, { queueId: 'customerStrategy' });\n }\n\n /**\n * Executes custom checkout of the priority payment method.\n *\n * Some payment methods, such as Bolt, can use their own checkout\n * with autofilled customers data, to make checkout passing process\n * easier and faster for customers with Bolt account.\n *\n * ```js\n * await service.executePaymentMethodCheckout({\n * methodId: 'bolt',\n * fallback: () => {},\n * });\n * ```\n *\n * @param options - Options for executing payment method checkout.\n * @returns A promise that resolves to the current state.\n */\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n const action = this._customerStrategyActionCreator.executePaymentMethodCheckout(options);\n\n return this._dispatch(action, { queueId: 'customerStrategy' });\n }\n\n /**\n * Loads a list of shipping options available for checkout.\n *\n * Available shipping options can only be determined once a customer\n * provides their shipping address. If the method is executed successfully,\n * `CheckoutStoreSelector#getShippingOptions` can be called to retrieve the\n * list of shipping options.\n *\n * ```js\n * const state = await service.loadShippingOptions();\n *\n * console.log(state.data.getShippingOptions());\n * ```\n *\n * @param options - Options for loading the available shipping options.\n * @returns A promise that resolves to the current state.\n */\n loadShippingOptions(options?: RequestOptions): Promise {\n const action = this._consignmentActionCreator.loadShippingOptions(options);\n\n return this._dispatch(action);\n }\n\n /**\n * Initializes the shipping step of a checkout process.\n *\n * Some payment methods, such as Amazon Pay, can provide shipping\n * information to be used for checkout. In order to support them, this\n * method must be called.\n *\n * ```js\n * await service.initializeShipping({\n * methodId: 'amazonpay',\n * amazonpay: {\n * editAddressButtonId: 'changeAddressButton',\n * },\n * });\n * ```\n *\n * @param options - Options for initializing the shipping step of checkout.\n * @returns A promise that resolves to the current state.\n */\n initializeShipping(options?: ShippingInitializeOptions): Promise {\n const action = this._shippingStrategyActionCreator.initialize(options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * De-initializes the shipping step of a checkout process.\n *\n * It should be called once you no longer need to collect shipping details.\n * It can perform any necessary clean-up behind the scene, i.e.: remove DOM\n * nodes or event handlers that are attached as a result of shipping\n * initialization.\n *\n * ```js\n * await service.deinitializeShipping({\n * methodId: 'amazonpay',\n * });\n * ```\n *\n * @param options - Options for deinitializing the shipping step of checkout.\n * @returns A promise that resolves to the current state.\n */\n deinitializeShipping(options?: ShippingRequestOptions): Promise {\n const action = this._shippingStrategyActionCreator.deinitialize(options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Selects a shipping option for the current address.\n *\n * If a shipping option has an additional cost, the quote for the current\n * order will be adjusted once the option is selected.\n *\n * ```js\n * const state = await service.selectShippingOption('address-id', 'shipping-option-id');\n *\n * console.log(state.data.getSelectedShippingOption());\n * ```\n *\n * @param shippingOptionId - The identifier of the shipping option to\n * select.\n * @param options - Options for selecting the shipping option.\n * @returns A promise that resolves to the current state.\n */\n selectShippingOption(\n shippingOptionId: string,\n options?: ShippingRequestOptions,\n ): Promise {\n const action = this._shippingStrategyActionCreator.selectOption(shippingOptionId, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Updates the shipping address for the current checkout.\n *\n * When a customer updates their shipping address for an order, they will\n * see an updated list of shipping options and the cost for each option,\n * unless no options are available. If the update is successful, you can\n * call `CheckoutStoreSelector#getShippingAddress` to retrieve the address.\n *\n * If the shipping address changes and the selected shipping option becomes\n * unavailable for the updated address, the shipping option will be\n * deselected.\n *\n * You can submit an address that is partially complete. The address does\n * not get validated until you submit the order.\n *\n * ```js\n * const state = await service.updateShippingAddress(address);\n *\n * console.log(state.data.getShippingAddress());\n * ```\n *\n * @param address - The address to be used for shipping.\n * @param options - Options for updating the shipping address.\n * @returns A promise that resolves to the current state.\n */\n updateShippingAddress(\n address: Partial,\n options?: ShippingRequestOptions,\n ): Promise {\n const action = this._shippingStrategyActionCreator.updateAddress(address, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Creates consignments given a list.\n *\n * Note: this is used when items need to be shipped to multiple addresses,\n * for single shipping address, use `CheckoutService#updateShippingAddress`.\n *\n * When consignments are created, an updated list of shipping options will\n * become available for each consignment, unless no options are available.\n * If the update is successful, you can call\n * `CheckoutStoreSelector#getConsignments` to retrieve the updated list of\n * consignments.'\n *\n * Beware that if a consignment includes all line items from another\n * consignment, that consignment will be deleted as a valid consignment must\n * include at least one valid line item.\n *\n * You can submit an address that is partially complete. The address does\n * not get validated until you submit the order.\n *\n * ```js\n * const state = await service.createConsignments(consignments);\n *\n * console.log(state.data.getConsignments());\n * ```\n *\n * @param consignments - The list of consignments to be created.\n * @param options - Options for updating the shipping address.\n * @returns A promise that resolves to the current state.\n */\n createConsignments(\n consignments: ConsignmentsRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._consignmentActionCreator.createConsignments(consignments, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Deletes a consignment\n *\n * ```js\n * const state = await service.deleteConsignment('55c96cda6f04c');\n *\n * console.log(state.data.getConsignments());\n * ```\n *\n * @param consignmentId - The ID of the consignment to be deleted\n * @param options - Options for the consignment delete request\n * @returns A promise that resolves to the current state.\n */\n deleteConsignment(consignmentId: string, options?: RequestOptions): Promise {\n const action = this._consignmentActionCreator.deleteConsignment(consignmentId, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Updates a specific consignment.\n *\n * Note: this is used when items need to be shipped to multiple addresses,\n * for single shipping address, use `CheckoutService#selectShippingOption`.\n *\n * When a shipping address for a consignment is updated, an updated list of\n * shipping options will become available for the consignment, unless no\n * options are available. If the update is successful, you can call\n * `CheckoutStoreSelector#getConsignments` to retrieve updated list of\n * consignments.\n *\n * Beware that if the updated consignment includes all line items from another\n * consignment, that consignment will be deleted as a valid consignment must\n * include at least one valid line item.\n *\n * If the shipping address changes and the selected shipping option becomes\n * unavailable for the updated address, the shipping option will be\n * deselected.\n *\n * You can submit an address that is partially complete. The address does\n * not get validated until you submit the order.\n *\n * ```js\n * const state = await service.updateConsignment(consignment);\n *\n * console.log(state.data.getConsignments());\n * ```\n *\n * @param consignment - The consignment data that will be used.\n * @param options - Options for updating the shipping address.\n * @returns A promise that resolves to the current state.\n */\n updateConsignment(\n consignment: ConsignmentUpdateRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._consignmentActionCreator.updateConsignment(consignment, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Convenience method that assigns items to be shipped to a specific address.\n *\n * Note: this method finds an existing consignment that matches the provided address\n * and assigns the provided items. If no consignment matches the address, a new one\n * will be created.\n *\n * @param consignment - The consignment data that will be used.\n * @param options - Options for the request\n * @returns A promise that resolves to the current state.\n */\n assignItemsToAddress(\n consignment: ConsignmentAssignmentRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._consignmentActionCreator.assignItemsByAddress(consignment, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Convenience method that unassigns items from a specific shipping address.\n *\n * Note: this method finds an existing consignment that matches the provided address\n * and unassigns the specified items. If the consignment ends up with no line items\n * after the unassignment, it will be deleted.\n *\n * @param consignment - The consignment data that will be used.\n * @param options - Options for the request\n * @returns A promise that resolves to the current state.\n */\n unassignItemsToAddress(\n consignment: ConsignmentAssignmentRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._consignmentActionCreator.unassignItemsByAddress(consignment, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Selects a shipping option for a given consignment.\n *\n * Note: this is used when items need to be shipped to multiple addresses,\n * for single shipping address, use `CheckoutService#updateShippingAddress`.\n *\n * If a shipping option has an additional cost, the quote for the current\n * order will be adjusted once the option is selected.\n *\n * ```js\n * const state = await service.selectConsignmentShippingOption(consignmentId, optionId);\n *\n * console.log(state.data.getConsignments());\n * ```\n *\n * @param consignmentId - The identified of the consignment to be updated.\n * @param shippingOptionId - The identifier of the shipping option to\n * select.\n * @param options - Options for selecting the shipping option.\n * @returns A promise that resolves to the current state.\n */\n selectConsignmentShippingOption(\n consignmentId: string,\n shippingOptionId: string,\n options?: ShippingRequestOptions,\n ): Promise {\n const action = this._consignmentActionCreator.updateShippingOption(\n {\n id: consignmentId,\n shippingOptionId,\n },\n options,\n );\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Updates the billing address for the current checkout.\n *\n * A customer must provide their billing address before they can proceed to\n * pay for their order.\n *\n * You can submit an address that is partially complete. The address does\n * not get validated until you submit the order.\n *\n * ```js\n * const state = await service.updateBillingAddress(address);\n *\n * console.log(state.data.getBillingAddress());\n * ```\n *\n * @param address - The address to be used for billing.\n * @param options - Options for updating the billing address.\n * @returns A promise that resolves to the current state.\n */\n updateBillingAddress(\n address: Partial,\n options: RequestOptions = {},\n ): Promise {\n const action = this._billingAddressActionCreator.updateAddress(address, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Applies or removes customer's store credit code to the current checkout.\n *\n * Once the store credit gets applied, the outstanding balance will be adjusted accordingly.\n *\n * ```js\n * const state = await service.applyStoreCredit(true);\n *\n * console.log(state.data.getCheckout().outstandingBalance);\n * ```\n *\n * @param options - Options for applying store credit.\n * @returns A promise that resolves to the current state.\n */\n applyStoreCredit(\n useStoreCredit: boolean,\n options?: RequestOptions,\n ): Promise {\n const action = this._storeCreditActionCreator.applyStoreCredit(useStoreCredit, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Applies a coupon code to the current checkout.\n *\n * Once the coupon code gets applied, the quote for the current checkout will\n * be adjusted accordingly. The same coupon code cannot be applied more than\n * once.\n *\n * ```js\n * await service.applyCoupon('COUPON');\n * ```\n *\n * @param code - The coupon code to apply to the current checkout.\n * @param options - Options for applying the coupon code.\n * @returns A promise that resolves to the current state.\n */\n applyCoupon(code: string, options?: RequestOptions): Promise {\n const action = this._couponActionCreator.applyCoupon(code, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Removes a coupon code from the current checkout.\n *\n * Once the coupon code gets removed, the quote for the current checkout will\n * be adjusted accordingly.\n *\n * ```js\n * await service.removeCoupon('COUPON');\n * ```\n *\n * @param code - The coupon code to remove from the current checkout.\n * @param options - Options for removing the coupon code.\n * @returns A promise that resolves to the current state.\n */\n removeCoupon(code: string, options?: RequestOptions): Promise {\n const action = this._couponActionCreator.removeCoupon(code, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Applies a gift certificate to the current checkout.\n *\n * Once the gift certificate gets applied, the quote for the current\n * checkout will be adjusted accordingly.\n *\n * ```js\n * await service.applyGiftCertificate('GIFT_CERTIFICATE');\n * ```\n *\n * @param code - The gift certificate to apply to the current checkout.\n * @param options - Options for applying the gift certificate.\n * @returns A promise that resolves to the current state.\n */\n applyGiftCertificate(code: string, options?: RequestOptions): Promise {\n const action = this._giftCertificateActionCreator.applyGiftCertificate(code, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Removes a gift certificate from an order.\n *\n * Once the gift certificate gets removed, the quote for the current\n * checkout will be adjusted accordingly.\n *\n * ```js\n * await service.removeGiftCertificate('GIFT_CERTIFICATE');\n * ```\n *\n * @param code - The gift certificate to remove from the current checkout.\n * @param options - Options for removing the gift certificate.\n * @returns A promise that resolves to the current state.\n */\n removeGiftCertificate(code: string, options?: RequestOptions): Promise {\n const action = this._giftCertificateActionCreator.removeGiftCertificate(code, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Loads a list of payment instruments associated with a customer.\n *\n * Once the method has been called successfully, you can retrieve the list\n * of payment instruments by calling `CheckoutStoreSelector#getInstruments`.\n * If the customer does not have any payment instruments on record, i.e.:\n * credit card, you will get an empty list instead.\n *\n * ```js\n * const state = service.loadInstruments();\n *\n * console.log(state.data.getInstruments());\n * ```\n *\n * @returns A promise that resolves to the current state.\n */\n loadInstruments(): Promise {\n const action = this._instrumentActionCreator.loadInstruments();\n\n return this._dispatch(action);\n }\n\n /**\n * Deletes a payment instrument by an id.\n *\n * Once an instrument gets removed, it can no longer be retrieved using\n * `CheckoutStoreSelector#getInstruments`.\n *\n * ```js\n * const state = service.deleteInstrument('123');\n *\n * console.log(state.data.getInstruments());\n * ```\n *\n * @param instrumentId - The identifier of the payment instrument to delete.\n * @returns A promise that resolves to the current state.\n */\n deleteInstrument(instrumentId: string): Promise {\n const action = this._instrumentActionCreator.deleteInstrument(instrumentId);\n\n return this._dispatch(action).then(() => this.loadInstruments());\n }\n\n /**\n * Clear errors that have been collected from previous calls.\n *\n * ```js\n * const state = await service.clearError(error);\n *\n * console.log(state.errors.getError());\n * ```\n *\n * @param error - Specific error object to clear\n * @returns A promise that resolves to the current state.\n */\n clearError(error: Error): Promise {\n const action = this._errorActionCreator.clearError(error);\n\n return this._dispatch(action);\n }\n\n /**\n * Initializes the spam protection for order creation.\n *\n * Note: Use `CheckoutService#executeSpamCheck` instead.\n * You do not need to call this method before calling\n * `CheckoutService#executeSpamCheck`.\n *\n * With spam protection enabled, the customer has to be verified as\n * a human. The order creation will fail if spam protection\n * is enabled but verification fails.\n *\n * ```js\n * await service.initializeSpamProtection();\n * ```\n *\n * @param options - Options for initializing spam protection.\n * @returns A promise that resolves to the current state.\n * @deprecated - Use CheckoutService#executeSpamCheck instead.\n */\n initializeSpamProtection(options: SpamProtectionOptions): Promise {\n const action = this._spamProtectionActionCreator.initialize(options);\n\n return this._dispatch(action, { queueId: 'spamProtection' });\n }\n\n /**\n * Verifies whether the current checkout is created by a human.\n *\n * Note: this method will do the initialization, therefore you do not\n * need to call `CheckoutService#initializeSpamProtection`\n * before calling this method.\n *\n * With spam protection enabled, the customer has to be verified as\n * a human. The order creation will fail if spam protection\n * is enabled but verification fails. You should call this method before\n * `submitOrder` method is called (i.e.: when the shopper\n * first gets to the payment step).\n *\n * **Note**: You need to enable Google ReCAPTCHA bot protection in your Checkout Settings.\n *\n * ```js\n * await service.executeSpamCheck();\n * ```\n *\n * @returns A promise that resolves to the current state.\n */\n executeSpamCheck(): Promise {\n const action = this._spamProtectionActionCreator.verifyCheckoutSpamProtection();\n\n return this._dispatch(action, { queueId: 'spamProtection' });\n }\n\n /**\n * Loads a list of extensions available for checkout.\n *\n * ```js\n * const state = await service.loadExtensions();\n *\n * console.log(state.data.getExtensions());\n * ```\n *\n * @alpha\n * @param options - Options for loading the extensions that are\n * available to the current customer.\n * @returns A promise that resolves to the current state.\n */\n loadExtensions(options?: RequestOptions): Promise {\n const action = this._extensionActionCreator.loadExtensions(options);\n\n return this._dispatch(action, { queueId: 'extensions' });\n }\n\n /**\n * Renders an extension for a checkout extension region.\n * Currently, only one extension is allowed per region.\n *\n * @alpha\n * @param container The ID of a container which the extension should be inserted.\n * @param region The name of an area where the extension should be presented.\n * @returns A promise that resolves to the current state.\n */\n renderExtension(container: string, region: ExtensionRegion): Promise {\n const action = this._extensionActionCreator.renderExtension(container, region);\n\n return this._dispatch(action, { queueId: 'extensions' });\n }\n\n /**\n * Dispatches an action through the data store and returns the current state\n * once the action is dispatched.\n *\n * @param action - The action to dispatch.\n * @returns A promise that resolves to the current state.\n */\n private _dispatch(\n action: Action | Observable | ThunkAction,\n options?: { queueId?: string },\n ): Promise {\n return this._store\n .dispatch(action, options)\n .then(() => this.getState())\n .catch((error) => {\n throw this._errorTransformer.transform(error);\n });\n }\n}\n","import { ErrorMessageTransformer } from '../common/error';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../common/error/errors';\nimport { getEnvironment } from '../common/utility';\n\nexport type CheckoutServiceErrorType = MissingDataError | NotInitializedError;\nexport type CheckoutServiceErrorTransformer = ErrorMessageTransformer<\n CheckoutServiceErrorType | Error\n>;\n\nexport default function createCheckoutServiceErrorTransformer(\n isDevelopment: boolean = getEnvironment() === 'development',\n): CheckoutServiceErrorTransformer {\n return new ErrorMessageTransformer((error) => {\n if (!isDevelopment || !isCheckoutServiceError(error)) {\n return error.message;\n }\n\n switch (error.subtype || error.type) {\n case MissingDataErrorType.MissingConsignments:\n return `\n ${error.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 `;\n\n case MissingDataErrorType.MissingCart:\n case MissingDataErrorType.MissingCheckout:\n return `\n ${error.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 `;\n\n case MissingDataErrorType.MissingCheckoutConfig:\n return `\n ${error.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 `;\n\n case MissingDataErrorType.MissingOrder:\n return `\n ${error.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 `;\n\n case MissingDataErrorType.MissingOrderId:\n return `\n ${error.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 `;\n\n case MissingDataErrorType.MissingPaymentMethod:\n return `\n ${error.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 `;\n\n case NotInitializedErrorType.CustomerNotInitialized:\n 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 `;\n\n case NotInitializedErrorType.PaymentNotInitialized:\n return `\n ${error.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 `;\n\n case NotInitializedErrorType.ShippingNotInitialized:\n return `\n ${error.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 `;\n\n default:\n return error.message;\n }\n });\n}\n\nfunction isCheckoutServiceError(error: any): error is CheckoutServiceErrorType {\n return !!(error.subtype || error.type);\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { omit, values } from 'lodash';\n\nimport { Address } from '../address';\nimport { BillingAddress } from '../billing';\nimport { Cart } from '../cart';\nimport { createSelector } from '../common/selector';\nimport { cloneResult as clone } from '../common/utility';\nimport { FlashMessage, FlashMessageType, StoreConfig, UserExperienceSettings } from '../config';\nimport { Coupon, GiftCertificate } from '../coupon';\nimport { Customer } from '../customer';\nimport { Extension } from '../extension';\nimport { FormField } from '../form';\nimport { Country } from '../geography';\nimport { Order } from '../order';\nimport { PaymentMethod } from '../payment';\nimport { CardInstrument, PaymentInstrument } from '../payment/instrument';\nimport { Consignment, PickupOptionResult, SearchArea, ShippingOption } from '../shipping';\nimport { SignInEmail } from '../signin-email';\n\nimport Checkout from './checkout';\nimport InternalCheckoutSelectors from './internal-checkout-selectors';\n\nexport type Instrument = CardInstrument;\n\n/**\n * Responsible for getting the state of the current checkout.\n *\n * This object has a set of methods that allow you to get a specific piece of\n * checkout information, such as shipping and billing details.\n */\nexport default interface CheckoutStoreSelector {\n /**\n * Gets the current checkout.\n *\n * @returns The current checkout if it is loaded, otherwise undefined.\n */\n getCheckout(): Checkout | undefined;\n\n /**\n * Gets the current order.\n *\n * @returns The current order if it is loaded, otherwise undefined.\n */\n getOrder(): Order | undefined;\n\n /**\n * Gets the checkout configuration of a store.\n *\n * @returns The configuration object if it is loaded, otherwise undefined.\n */\n getConfig(): StoreConfig | undefined;\n\n /**\n * Gets the sign-in email.\n *\n * @returns The sign-in email object if sent, otherwise undefined\n */\n getSignInEmail(): SignInEmail | undefined;\n\n /**\n * Gets the shipping address of the current checkout.\n *\n * If the address is partially complete, it may not have shipping options\n * associated with it.\n *\n * @returns The shipping address object if it is loaded, otherwise\n * undefined.\n */\n getShippingAddress(): Address | undefined;\n\n /**\n * Gets a list of shipping options available for the shipping address.\n *\n * If there is no shipping address assigned to the current checkout, the\n * list of shipping options will be empty.\n *\n * @returns The list of shipping options if any, otherwise undefined.\n */\n getShippingOptions(): ShippingOption[] | undefined;\n\n /**\n * Gets a list of consignments.\n *\n * If there are no consignments created for to the current checkout, the\n * list will be empty.\n *\n * @returns The list of consignments if any, otherwise undefined.\n */\n getConsignments(): Consignment[] | undefined;\n\n /**\n * Gets the selected shipping option for the current checkout.\n *\n * @returns The shipping option object if there is a selected option,\n * otherwise undefined.\n */\n getSelectedShippingOption(): ShippingOption | undefined;\n\n /**\n * Gets a list of countries available for shipping.\n *\n * @returns The list of countries if it is loaded, otherwise undefined.\n */\n getShippingCountries(): Country[] | undefined;\n\n /**\n * Gets the billing address of an order.\n *\n * @returns The billing address object if it is loaded, otherwise undefined.\n */\n getBillingAddress(): BillingAddress | undefined;\n\n /**\n * Gets a list of countries available for billing.\n *\n * @returns The list of countries if it is loaded, otherwise undefined.\n */\n getBillingCountries(): Country[] | undefined;\n\n /**\n * Gets a list of payment methods available for checkout.\n *\n * @returns The list of payment methods if it is loaded, otherwise undefined.\n */\n getPaymentMethods(): PaymentMethod[] | undefined;\n\n /**\n * Gets a payment method by an id.\n *\n * The method returns undefined if unable to find a payment method with the\n * specified id, either because it is not available for the customer, or it\n * is not loaded.\n *\n * @param methodId - The identifier of the payment method.\n * @param gatewayId - The identifier of a payment provider providing the\n * payment method.\n * @returns The payment method object if loaded and available, otherwise,\n * undefined.\n */\n getPaymentMethod(methodId: string, gatewayId?: string): PaymentMethod | undefined;\n\n /**\n * Gets the payment method that is selected for checkout.\n *\n * @returns The payment method object if there is a selected method;\n * undefined if otherwise.\n */\n getSelectedPaymentMethod(): PaymentMethod | undefined;\n\n /**\n * Gets the available flash messages.\n *\n * Flash messages contain messages set by the server,\n * e.g: when trying to sign in using an invalid email link.\n *\n * @param type - The type of flash messages to be returned. Optional\n * @returns The flash messages if available, otherwise undefined.\n */\n getFlashMessages(type?: FlashMessageType): FlashMessage[] | undefined;\n\n /**\n * Gets the current cart.\n *\n * @returns The current cart object if it is loaded, otherwise undefined.\n */\n getCart(): Cart | undefined;\n\n /**\n * Gets a list of coupons that are applied to the current checkout.\n *\n * @returns The list of applied coupons if there is any, otherwise undefined.\n */\n getCoupons(): Coupon[] | undefined;\n\n /**\n * Gets a list of gift certificates that are applied to the current checkout.\n *\n * @returns The list of applied gift certificates if there is any, otherwise undefined.\n */\n getGiftCertificates(): GiftCertificate[] | undefined;\n\n /**\n * Gets the current customer.\n *\n * @returns The current customer object if it is loaded, otherwise\n * undefined.\n */\n getCustomer(): Customer | undefined;\n\n /**\n * Checks if payment data is required or not.\n *\n * If payment data is required, customers should be prompted to enter their\n * payment details.\n *\n * ```js\n * if (state.checkout.isPaymentDataRequired()) {\n * // Render payment form\n * } else {\n * // Render \"Payment is not required for this order\" message\n * }\n * ```\n *\n * @param useStoreCredit - If true, check whether payment data is required\n * with store credit applied; otherwise, check without store credit.\n * @returns True if payment data is required, otherwise false.\n */\n isPaymentDataRequired(useStoreCredit?: boolean): boolean;\n\n /**\n * Checks if payment data is submitted or not.\n *\n * If payment data is already submitted using a payment method, customers\n * should not be prompted to enter their payment details again.\n *\n * @param methodId - The identifier of the payment method.\n * @param gatewayId - The identifier of a payment provider providing the\n * payment method.\n * @returns True if payment data is submitted, otherwise false.\n */\n isPaymentDataSubmitted(methodId: string, gatewayId?: string): boolean;\n\n /**\n * Gets a list of payment instruments associated with the current customer.\n *\n * @returns The list of payment instruments if it is loaded, otherwise undefined.\n */\n getInstruments(): Instrument[] | undefined;\n getInstruments(paymentMethod: PaymentMethod): PaymentInstrument[] | undefined;\n\n /**\n * Gets a set of form fields that should be presented in order to create a customer.\n *\n * @returns The set of customer account form fields if it is loaded,\n * otherwise undefined.\n */\n getCustomerAccountFields(): FormField[];\n\n /**\n * Gets a set of form fields that should be presented to customers in order\n * to capture their billing address for a specific country.\n *\n * @param countryCode - A 2-letter country code (ISO 3166-1 alpha-2).\n * @returns The set of billing address form fields if it is loaded,\n * otherwise undefined.\n */\n getBillingAddressFields(countryCode: string): FormField[];\n\n /**\n * Gets a set of form fields that should be presented to customers in order\n * to capture their shipping address for a specific country.\n *\n * @param countryCode - A 2-letter country code (ISO 3166-1 alpha-2).\n * @returns The set of shipping address form fields if it is loaded,\n * otherwise undefined.\n */\n getShippingAddressFields(countryCode: string): FormField[];\n\n /**\n * Gets a list of pickup options for specified parameters.\n *\n * @param consignmentId - Id of consignment.\n * @param searchArea - An object containing of radius and co-ordinates.\n * @returns The set of shipping address form fields if it is loaded,\n * otherwise undefined.\n */\n getPickupOptions(\n consignmentId: string,\n searchArea: SearchArea,\n ): PickupOptionResult[] | undefined;\n\n /**\n * Gets user experience settings.\n *\n * @returns The object of user experience settings if it is loaded, otherwise undefined.\n */\n getUserExperienceSettings(): UserExperienceSettings | undefined;\n\n /**\n * Gets a list of extensions available for checkout.\n *\n * @alpha\n * @returns The list of extensions if it is loaded, otherwise undefined.\n */\n getExtensions(): Extension[] | undefined;\n}\n\nexport type CheckoutStoreSelectorFactory = (\n state: InternalCheckoutSelectors,\n) => CheckoutStoreSelector;\n\nexport function createCheckoutStoreSelectorFactory(): CheckoutStoreSelectorFactory {\n const getCheckout = createSelector(\n ({ checkout }: InternalCheckoutSelectors) => checkout.getCheckout,\n (getCheckout) => clone(getCheckout),\n );\n\n const getOrder = createSelector(\n ({ order }: InternalCheckoutSelectors) => order.getOrder,\n (getOrder) => clone(getOrder),\n );\n\n const getConfig = createSelector(\n ({ config }: InternalCheckoutSelectors) => config.getStoreConfig,\n (getStoreConfig) => clone(getStoreConfig),\n );\n\n const getShippingAddress = createSelector(\n ({ shippingAddress }: InternalCheckoutSelectors) => shippingAddress.getShippingAddress,\n ({ config }: InternalCheckoutSelectors) => config.getContextConfig,\n (getShippingAddress, getContextConfig) =>\n clone(() => {\n const shippingAddress = getShippingAddress();\n const context = getContextConfig();\n\n if (!shippingAddress) {\n if (!context || !context.geoCountryCode) {\n return;\n }\n\n return {\n firstName: '',\n lastName: '',\n company: '',\n address1: '',\n address2: '',\n city: '',\n stateOrProvince: '',\n stateOrProvinceCode: '',\n postalCode: '',\n country: '',\n phone: '',\n customFields: [],\n countryCode: context.geoCountryCode,\n };\n }\n\n return shippingAddress;\n }),\n );\n\n const getShippingOptions = createSelector(\n ({ consignments }: InternalCheckoutSelectors) => consignments.getConsignments,\n (getConsignments) =>\n clone(() => {\n const consignments = getConsignments();\n\n const shippingConsignment = consignments?.find(\n (consignment) => !consignment.selectedPickupOption,\n );\n\n return shippingConsignment?.availableShippingOptions;\n }),\n );\n\n const getConsignments = createSelector(\n ({ consignments }: InternalCheckoutSelectors) => consignments.getConsignments,\n (getConsignments) => clone(getConsignments),\n );\n\n const getSelectedShippingOption = createSelector(\n ({ consignments }: InternalCheckoutSelectors) => consignments.getConsignments,\n (getConsignments) =>\n clone(() => {\n const consignments = getConsignments();\n const shippingConsignment = consignments?.find(\n (consignment) => !consignment.selectedPickupOption,\n );\n\n return shippingConsignment?.selectedShippingOption;\n }),\n );\n\n const getShippingCountries = createSelector(\n ({ shippingCountries }: InternalCheckoutSelectors) =>\n shippingCountries.getShippingCountries,\n (getShippingCountries) => clone(getShippingCountries),\n );\n\n const getBillingAddress = createSelector(\n ({ billingAddress }: InternalCheckoutSelectors) => billingAddress.getBillingAddress,\n ({ config }: InternalCheckoutSelectors) => config.getContextConfig,\n (getBillingAddress, getContextConfig) =>\n clone(() => {\n const billingAddress = getBillingAddress();\n const context = getContextConfig();\n const isEmptyBillingAddress =\n !billingAddress ||\n values(omit(billingAddress, 'shouldSaveAddress', 'email', 'id')).every(\n (val) => !val || !val.length,\n );\n\n if (isEmptyBillingAddress) {\n if (!context || !context.geoCountryCode) {\n return billingAddress;\n }\n\n return {\n id: billingAddress ? billingAddress.id : '',\n firstName: '',\n lastName: '',\n company: '',\n address1: '',\n address2: '',\n city: '',\n email: billingAddress ? billingAddress.email : '',\n stateOrProvince: '',\n stateOrProvinceCode: '',\n postalCode: '',\n country: '',\n phone: '',\n customFields: [],\n countryCode: context.geoCountryCode,\n };\n }\n\n return billingAddress;\n }),\n );\n\n const getBillingCountries = createSelector(\n ({ countries }: InternalCheckoutSelectors) => countries.getCountries,\n (getCountries) => clone(getCountries),\n );\n\n const getPaymentMethods = createSelector(\n ({ paymentMethods }: InternalCheckoutSelectors) => paymentMethods.getPaymentMethods,\n (getPaymentMethods) => clone(getPaymentMethods),\n );\n\n const getPaymentMethod = createSelector(\n ({ paymentMethods }: InternalCheckoutSelectors) => paymentMethods.getPaymentMethod,\n (getPaymentMethod) => clone(getPaymentMethod),\n );\n\n const getSelectedPaymentMethod = createSelector(\n ({ payment }: InternalCheckoutSelectors) => payment.getPaymentId,\n ({ paymentMethods }: InternalCheckoutSelectors) => paymentMethods.getPaymentMethod,\n (getPaymentId, getPaymentMethod) =>\n clone(() => {\n const payment = getPaymentId();\n\n return payment && getPaymentMethod(payment.providerId, payment.gatewayId);\n }),\n );\n\n const getCart = createSelector(\n ({ cart }: InternalCheckoutSelectors) => cart.getCart,\n (getCart) => clone(getCart),\n );\n\n const getCoupons = createSelector(\n ({ coupons }: InternalCheckoutSelectors) => coupons.getCoupons,\n (getCoupons) => clone(getCoupons),\n );\n\n const getGiftCertificates = createSelector(\n ({ giftCertificates }: InternalCheckoutSelectors) => giftCertificates.getGiftCertificates,\n (getGiftCertificates) => clone(getGiftCertificates),\n );\n\n const getCustomer = createSelector(\n ({ customer }: InternalCheckoutSelectors) => customer.getCustomer,\n (getCustomer) => clone(getCustomer),\n );\n\n const getSignInEmail = createSelector(\n ({ signInEmail }: InternalCheckoutSelectors) => signInEmail.getEmail,\n (getEmail) => clone(getEmail),\n );\n\n const isPaymentDataRequired = createSelector(\n ({ payment }: InternalCheckoutSelectors) => payment.isPaymentDataRequired,\n (isPaymentDataRequired) => clone(isPaymentDataRequired),\n );\n\n const isPaymentDataSubmitted = createSelector(\n ({ payment }: InternalCheckoutSelectors) => payment.isPaymentDataSubmitted,\n ({ paymentMethods }: InternalCheckoutSelectors) => paymentMethods.getPaymentMethod,\n (isPaymentDataSubmitted, getPaymentMethod) =>\n clone((methodId: string, gatewayId?: string) => {\n return isPaymentDataSubmitted(getPaymentMethod(methodId, gatewayId));\n }),\n );\n\n const getInstruments = createSelector(\n ({ instruments }: InternalCheckoutSelectors) => instruments.getInstruments,\n ({ instruments }: InternalCheckoutSelectors) => instruments.getInstrumentsByPaymentMethod,\n (getInstruments, getInstrumentsByPaymentMethod) => {\n function getInstrumentsSelector(): Instrument[] | undefined;\n function getInstrumentsSelector(\n paymentMethod: PaymentMethod,\n ): PaymentInstrument[] | undefined;\n\n function getInstrumentsSelector(\n paymentMethod?: PaymentMethod,\n ): PaymentInstrument[] | undefined {\n return paymentMethod\n ? getInstrumentsByPaymentMethod(paymentMethod)\n : getInstruments();\n }\n\n return clone(getInstrumentsSelector);\n },\n );\n\n const getCustomerAccountFields = createSelector(\n ({ form }: InternalCheckoutSelectors) => form.getCustomerAccountFields,\n (getCustomerAccountFields) => clone(getCustomerAccountFields),\n );\n\n const getBillingAddressFields = createSelector(\n ({ form }: InternalCheckoutSelectors) => form.getBillingAddressFields,\n ({ countries }: InternalCheckoutSelectors) => countries.getCountries,\n (getBillingAddressFields, getCountries) =>\n clone((countryCode: string) => {\n return getBillingAddressFields(getCountries(), countryCode);\n }),\n );\n\n const getShippingAddressFields = createSelector(\n ({ form }: InternalCheckoutSelectors) => form.getShippingAddressFields,\n ({ shippingCountries }: InternalCheckoutSelectors) =>\n shippingCountries.getShippingCountries,\n (getShippingAddressFields, getShippingCountries) =>\n clone((countryCode: string) => {\n return getShippingAddressFields(getShippingCountries(), countryCode);\n }),\n );\n\n const getFlashMessages = createSelector(\n ({ config }: InternalCheckoutSelectors) => config.getFlashMessages,\n (getFlashMessages) => clone(getFlashMessages),\n );\n\n const getPickupOptions = createSelector(\n ({ pickupOptions }: InternalCheckoutSelectors) => pickupOptions.getPickupOptions,\n (getPickupOptions) => clone(getPickupOptions),\n );\n\n const getUserExperienceSettings = createSelector(\n ({ config }: InternalCheckoutSelectors) => config.getStoreConfig,\n (getStoreConfig) =>\n clone(() => {\n const config = getStoreConfig();\n\n if (!config) {\n return;\n }\n\n return config.checkoutSettings.checkoutUserExperienceSettings;\n }),\n );\n\n const getExtensions = createSelector(\n ({ extensions }: InternalCheckoutSelectors) => extensions.getExtensions,\n (getExtensions) => clone(getExtensions),\n );\n\n return memoizeOne((state: InternalCheckoutSelectors): CheckoutStoreSelector => {\n return {\n getCheckout: getCheckout(state),\n getOrder: getOrder(state),\n getConfig: getConfig(state),\n getExtensions: getExtensions(state),\n getFlashMessages: getFlashMessages(state),\n getShippingAddress: getShippingAddress(state),\n getShippingOptions: getShippingOptions(state),\n getConsignments: getConsignments(state),\n getSelectedShippingOption: getSelectedShippingOption(state),\n getShippingCountries: getShippingCountries(state),\n getBillingAddress: getBillingAddress(state),\n getBillingCountries: getBillingCountries(state),\n getPaymentMethods: getPaymentMethods(state),\n getPaymentMethod: getPaymentMethod(state),\n getSelectedPaymentMethod: getSelectedPaymentMethod(state),\n getCart: getCart(state),\n getCoupons: getCoupons(state),\n getGiftCertificates: getGiftCertificates(state),\n getCustomer: getCustomer(state),\n isPaymentDataRequired: isPaymentDataRequired(state),\n isPaymentDataSubmitted: isPaymentDataSubmitted(state),\n getSignInEmail: getSignInEmail(state),\n getInstruments: getInstruments(state),\n getCustomerAccountFields: getCustomerAccountFields(state),\n getBillingAddressFields: getBillingAddressFields(state),\n getShippingAddressFields: getShippingAddressFields(state),\n getPickupOptions: getPickupOptions(state),\n getUserExperienceSettings: getUserExperienceSettings(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { CartChangedError, CartConsistencyError } from '../cart/errors';\nimport { RequestError } from '../common/error/errors';\nimport { createSelector, createShallowEqualSelector } from '../common/selector';\nimport { Omit } from '../common/types';\n\nimport InternalCheckoutSelectors from './internal-checkout-selectors';\n\n/**\n * Responsible for getting the error of any asynchronous checkout action, if\n * there is any.\n *\n * This object has a set of getters that would return an error if an action is\n * not executed successfully. For example, if you are unable to submit an order,\n * you can use this object to retrieve the reason for the failure.\n */\nexport default interface CheckoutStoreErrorSelector {\n getError(): Error | undefined;\n\n /**\n * Returns an error if unable to load the current checkout.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadCheckoutError(): Error | undefined;\n\n /**\n * Returns an error if unable to update the current checkout.\n *\n * @returns The error object if unable to update, otherwise undefined.\n */\n getUpdateCheckoutError(): Error | undefined;\n\n /**\n * Returns an error if unable to submit the current order.\n *\n * @returns The error object if unable to submit, otherwise undefined.\n */\n getSubmitOrderError(): Error | CartChangedError | CartConsistencyError | undefined;\n\n /**\n * Returns an error if unable to finalize the current order.\n *\n * @returns The error object if unable to finalize, otherwise undefined.\n */\n getFinalizeOrderError(): Error | undefined;\n\n /**\n * Returns an error if unable to load the current order.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadOrderError(): Error | undefined;\n\n /**\n * Returns an error if unable to load the current cart.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadCartError(): Error | undefined;\n\n /**\n * Returns an error if unable to load billing countries.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadBillingCountriesError(): Error | undefined;\n\n /**\n * Returns an error if unable to load shipping countries.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadShippingCountriesError(): Error | undefined;\n\n /**\n * Returns an error if unable to load payment methods.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadPaymentMethodsError(): Error | undefined;\n\n /**\n * Returns an error if unable to load a specific payment method.\n *\n * @param methodId - The identifier of the payment method to load.\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadPaymentMethodError(methodId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to initialize a specific payment method.\n *\n * @param methodId - The identifier of the payment method to initialize.\n * @returns The error object if unable to initialize, otherwise undefined.\n */\n getInitializePaymentError(methodId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to sign in.\n *\n * @returns The error object if unable to sign in, otherwise undefined.\n */\n getSignInError(): Error | undefined;\n\n /**\n * Returns an error if unable to sign out.\n *\n * @returns The error object if unable to sign out, otherwise undefined.\n */\n getSignOutError(): Error | undefined;\n\n /**\n * Returns an error if unable to initialize the customer step of a checkout\n * process.\n *\n * @param methodId - The identifer of the initialization method to execute.\n * @returns The error object if unable to initialize, otherwise undefined.\n */\n getInitializeCustomerError(methodId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to load shipping options.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadShippingOptionsError(): Error | undefined;\n\n /**\n * Returns an error if unable to select a shipping option.\n *\n * A consignment ID should be provided when checking for an error for a\n * specific consignment, otherwise it will check for all available consignments.\n *\n * @param consignmentId - The identifier of the consignment to be checked.\n * @returns The error object if unable to select, otherwise undefined.\n */\n getSelectShippingOptionError(consignmentId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to continue as guest.\n *\n * The call could fail in scenarios where guest checkout is not allowed, for example, when existing accounts are required to sign-in.\n *\n * In the background, this call tries to set the billing address email using the Storefront API. You could access the Storefront API response status code using `getContinueAsGuestError` error selector.\n *\n * ```js\n * console.log(state.errors.getContinueAsGuestError());\n * console.log(state.errors.getContinueAsGuestError().status);\n * ```\n *\n * For more information about status codes, check [Checkout Storefront API - Add Checkout Billing Address](https://developer.bigcommerce.com/api-reference/cart-checkout/storefront-checkout-api/checkout-billing-address/checkoutsbillingaddressbycheckoutidpost).\n *\n * @returns The error object if unable to continue, otherwise undefined.\n */\n getContinueAsGuestError(): Error | undefined;\n\n /**\n * Returns an error if unable to update billing address.\n *\n * @returns The error object if unable to update, otherwise undefined.\n */\n getUpdateBillingAddressError(): Error | undefined;\n\n /**\n * Returns an error if unable to update subscriptions.\n *\n * @returns The error object if unable to update, otherwise undefined.\n */\n getUpdateSubscriptionsError(): Error | undefined;\n\n /**\n * Returns an error if unable to update shipping address.\n *\n * @returns The error object if unable to update, otherwise undefined.\n */\n getUpdateShippingAddressError(): Error | undefined;\n\n /**\n * Returns an error if unable to delete a consignment.\n *\n * A consignment ID should be provided when checking for an error for a\n * specific consignment, otherwise it will check for all available consignments.\n *\n * @param consignmentId - The identifier of the consignment to be checked.\n * @returns The error object if unable to delete, otherwise undefined.\n */\n getDeleteConsignmentError(consignmentId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to update a consignment.\n *\n * A consignment ID should be provided when checking for an error for a\n * specific consignment, otherwise it will check for all available consignments.\n *\n * @param consignmentId - The identifier of the consignment to be checked.\n * @returns The error object if unable to update, otherwise undefined.\n */\n getUpdateConsignmentError(consignmentId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to create consignments.\n *\n * @returns The error object if unable to create, otherwise undefined.\n */\n getCreateConsignmentsError(): Error | undefined;\n\n /**\n * Returns an error if unable to initialize the shipping step of a checkout\n * process.\n *\n * @param methodId - The identifer of the initialization method to execute.\n * @returns The error object if unable to initialize, otherwise undefined.\n */\n getInitializeShippingError(methodId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to apply store credit.\n *\n * @returns The error object if unable to apply, otherwise undefined.\n */\n getApplyStoreCreditError(): RequestError | undefined;\n\n /**\n * Returns an error if unable to apply a coupon code.\n *\n * @returns The error object if unable to apply, otherwise undefined.\n */\n getApplyCouponError(): RequestError | undefined;\n\n /**\n * Returns an error if unable to remove a coupon code.\n *\n * @returns The error object if unable to remove, otherwise undefined.\n */\n getRemoveCouponError(): RequestError | undefined;\n\n /**\n * Returns an error if unable to apply a gift certificate.\n *\n * @returns The error object if unable to apply, otherwise undefined.\n */\n getApplyGiftCertificateError(): RequestError | undefined;\n\n /**\n * Returns an error if unable to remove a gift certificate.\n *\n * @returns The error object if unable to remove, otherwise undefined.\n */\n getRemoveGiftCertificateError(): RequestError | undefined;\n\n /**\n * Returns an error if unable to load payment instruments.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadInstrumentsError(): Error | undefined;\n\n /**\n * Returns an error if unable to delete a payment instrument.\n *\n * @param instrumentId - The identifier of the payment instrument to delete.\n * @returns The error object if unable to delete, otherwise undefined.\n */\n getDeleteInstrumentError(instrumentId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to load the checkout configuration of a store.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadConfigError(): Error | undefined;\n\n /**\n * Returns an error if unable to send sign-in email.\n *\n * @returns The error object if unable to send email, otherwise undefined.\n */\n getSignInEmailError(): Error | undefined;\n\n /**\n * Returns an error if unable to create customer account.\n *\n * @returns The error object if unable to create account, otherwise undefined.\n */\n getCreateCustomerAccountError(): Error | undefined;\n\n /**\n * Returns an error if unable to create customer address.\n *\n * @returns The error object if unable to create address, otherwise undefined.\n */\n getCreateCustomerAddressError(): Error | undefined;\n\n /**\n * Returns an error if unable to fetch pickup options.\n *\n * @returns The error object if unable to fetch pickup options, otherwise undefined.\n */\n getPickupOptionsError(): Error | undefined;\n\n /**\n * Returns an error if unable to fetch extensions.\n *\n * @alpha\n * @returns The error object if unable to fetch extensions, otherwise undefined.\n */\n getLoadExtensionsError(): Error | undefined;\n}\n\nexport type CheckoutStoreErrorSelectorFactory = (\n state: InternalCheckoutSelectors,\n) => CheckoutStoreErrorSelector;\n\nexport function createCheckoutStoreErrorSelectorFactory(): CheckoutStoreErrorSelectorFactory {\n const getError = createShallowEqualSelector(\n (selector: Omit) => selector,\n (selector) => () => {\n for (const key of Object.keys(selector) as Array<\n keyof Omit\n >) {\n const error = selector[key]();\n\n if (error) {\n return error;\n }\n }\n },\n );\n\n const getSelectShippingOptionError = createSelector(\n ({ shippingStrategies }: InternalCheckoutSelectors) =>\n shippingStrategies.getSelectOptionError,\n ({ consignments }: InternalCheckoutSelectors) => consignments.getUpdateShippingOptionError,\n (getSelectOptionError, getUpdateShippingOptionError) => (consignmentId?: string) => {\n return getSelectOptionError() || getUpdateShippingOptionError(consignmentId);\n },\n );\n\n return memoizeOne((state: InternalCheckoutSelectors): CheckoutStoreErrorSelector => {\n const selector = {\n getLoadCheckoutError: state.checkout.getLoadError,\n getUpdateCheckoutError: state.checkout.getUpdateError,\n getSubmitOrderError: state.paymentStrategies.getExecuteError,\n getFinalizeOrderError: state.paymentStrategies.getFinalizeError,\n getLoadOrderError: state.order.getLoadError,\n getLoadCartError: state.cart.getLoadError,\n getLoadBillingCountriesError: state.countries.getLoadError,\n getLoadShippingCountriesError: state.shippingCountries.getLoadError,\n getLoadPaymentMethodsError: state.paymentMethods.getLoadError,\n getLoadPaymentMethodError: state.paymentMethods.getLoadMethodError,\n getInitializePaymentError: state.paymentStrategies.getInitializeError,\n getSignInError: state.customerStrategies.getSignInError,\n getSignOutError: state.customerStrategies.getSignOutError,\n getInitializeCustomerError: state.customerStrategies.getInitializeError,\n getLoadShippingOptionsError: state.consignments.getLoadShippingOptionsError,\n getSelectShippingOptionError: getSelectShippingOptionError(state),\n getContinueAsGuestError: state.billingAddress.getContinueAsGuestError,\n getUpdateBillingAddressError: state.billingAddress.getUpdateError,\n getUpdateSubscriptionsError: state.subscriptions.getUpdateError,\n getUpdateShippingAddressError: state.shippingStrategies.getUpdateAddressError,\n getDeleteConsignmentError: state.consignments.getDeleteError,\n getUpdateConsignmentError: state.consignments.getUpdateError,\n getCreateConsignmentsError: state.consignments.getCreateError,\n getInitializeShippingError: state.shippingStrategies.getInitializeError,\n getApplyStoreCreditError: state.storeCredit.getApplyError,\n getApplyCouponError: state.coupons.getApplyError,\n getRemoveCouponError: state.coupons.getRemoveError,\n getApplyGiftCertificateError: state.giftCertificates.getApplyError,\n getRemoveGiftCertificateError: state.giftCertificates.getRemoveError,\n getLoadInstrumentsError: state.instruments.getLoadError,\n getDeleteInstrumentError: state.instruments.getDeleteError,\n getLoadConfigError: state.config.getLoadError,\n getSignInEmailError: state.signInEmail.getSendError,\n getCreateCustomerAccountError: state.customer.getCreateAccountError,\n getCreateCustomerAddressError: state.customer.getCreateAddressError,\n getPickupOptionsError: state.pickupOptions.getLoadError,\n getLoadExtensionsError: state.extensions.getLoadError,\n };\n\n return {\n getError: getError(selector),\n ...selector,\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector, createShallowEqualSelector } from '../common/selector';\nimport { Omit } from '../common/types';\n\nimport InternalCheckoutSelectors from './internal-checkout-selectors';\n\n/**\n * Responsible for checking the statuses of various asynchronous actions related\n * to checkout.\n *\n * This object has a set of getters that return true if an action is in\n * progress. For example, you can check whether a customer is submitting an\n * order and waiting for the request to complete.\n */\nexport default interface CheckoutStoreStatusSelector {\n /**\n * Checks whether any checkout action is pending.\n *\n * @returns True if there is a pending action, otherwise false.\n */\n isPending(): boolean;\n\n /**\n * Checks whether the current checkout is loading.\n *\n * @returns True if the current checkout is loading, otherwise false.\n */\n isLoadingCheckout(): boolean;\n\n /**\n * Checks whether the current checkout is being updated.\n *\n * @returns True if the current checkout is being updated, otherwise false.\n */\n isUpdatingCheckout(): boolean;\n\n /**\n * Checks whether spam check is executing.\n *\n * @returns True if the current checkout is being updated, otherwise false.\n */\n isExecutingSpamCheck(): boolean;\n\n /**\n * Checks whether the current order is submitting.\n *\n * @returns True if the current order is submitting, otherwise false.\n */\n isSubmittingOrder(): boolean;\n\n /**\n * Checks whether the current order is finalizing.\n *\n * @returns True if the current order is finalizing, otherwise false.\n */\n isFinalizingOrder(): boolean;\n\n /**\n * Checks whether the current order is loading.\n *\n * @returns True if the current order is loading, otherwise false.\n */\n isLoadingOrder(): boolean;\n\n /**\n * Checks whether the current cart is loading.\n *\n * @returns True if the current cart is loading, otherwise false.\n */\n isLoadingCart(): boolean;\n\n /**\n * Checks whether billing countries are loading.\n *\n * @returns True if billing countries are loading, otherwise false.\n */\n isLoadingBillingCountries(): boolean;\n\n /**\n * Checks whether shipping countries are loading.\n *\n * @returns True if shipping countries are loading, otherwise false.\n */\n isLoadingShippingCountries(): boolean;\n\n /**\n * Checks whether payment methods are loading.\n *\n * @returns True if payment methods are loading, otherwise false.\n */\n isLoadingPaymentMethods(): boolean;\n\n /**\n * Checks whether a specific or any payment method is loading.\n *\n * The method returns true if no ID is provided and at least one payment\n * method is loading.\n *\n * @param methodId - The identifier of the payment method to check.\n * @returns True if the payment method is loading, otherwise false.\n */\n isLoadingPaymentMethod(methodId?: string): boolean;\n\n /**\n * Checks whether a specific or any payment method is initializing.\n *\n * The method returns true if no ID is provided and at least one payment\n * method is initializing.\n *\n * @param methodId - The identifier of the payment method to check.\n * @returns True if the payment method is initializing, otherwise false.\n */\n isInitializingPayment(methodId?: string): boolean;\n\n /**\n * Checks whether the current customer is signing in.\n *\n * If an ID is provided, the method also checks whether the customer is\n * signing in using a specific customer method with the same ID.\n *\n * @param methodId - The identifier of the method used for signing in the\n * current customer.\n * @returns True if the customer is signing in, otherwise false.\n */\n isSigningIn(methodId?: string): boolean;\n\n /**\n * Checks whether the current customer is signing out.\n *\n * If an ID is provided, the method also checks whether the customer is\n * signing out using a specific customer method with the same ID.\n *\n * @param methodId - The identifier of the method used for signing out the\n * current customer.\n * @returns True if the customer is signing out, otherwise false.\n */\n isSigningOut(methodId?: string): boolean;\n\n /**\n * Checks whether the customer step is initializing.\n *\n * If an ID is provided, the method also checks whether the customer step is\n * initializing using a specific customer method with the same ID.\n *\n * @param methodId - The identifier of the method used for initializing the\n * customer step of checkout.\n * @returns True if the customer step is initializing, otherwise false.\n */\n isInitializingCustomer(methodId?: string): boolean;\n\n /**\n * Checks whether a wallet button is initialized.\n *\n * @param methodId - The identifier of the payment method to check.\n * @returns True if the wallet button method is initialized, otherwise false.\n */\n isInitializedCustomer(methodId?: string): boolean;\n\n /**\n * Checks whether the current customer is executing payment method checkout.\n *\n * If an ID is provided, the method also checks whether the customer is\n * executing payment method checkout using a specific customer method with the same ID.\n *\n * @param methodId - The identifier of the method used for continuing the\n * current customer.\n * @returns True if the customer is executing payment method checkout, otherwise false.\n */\n isExecutingPaymentMethodCheckout(methodId?: string): boolean;\n\n /**\n * Checks whether shipping options are loading.\n *\n * @returns True if shipping options are loading, otherwise false.\n */\n isLoadingShippingOptions(): boolean;\n\n /**\n * Checks whether a shipping option is being selected.\n *\n * A consignment ID should be provided when checking if a shipping option\n * is being selected for a specific consignment, otherwise it will check\n * for all consignments.\n *\n * @param consignmentId - The identifier of the consignment to be checked.\n * @returns True if selecting a shipping option, otherwise false.\n */\n isSelectingShippingOption(consignmentId?: string): boolean;\n\n /**\n * Checks whether the billing address is being updated.\n *\n * @returns True if updating their billing address, otherwise false.\n */\n isUpdatingBillingAddress(): boolean;\n\n /**\n * Checks whether the shopper is continuing out as a guest.\n *\n * @returns True if continuing as guest, otherwise false.\n */\n isContinuingAsGuest(): boolean;\n\n /**\n * Checks the shipping address is being updated.\n *\n * @returns True if updating their shipping address, otherwise false.\n */\n isUpdatingShippingAddress(): boolean;\n\n /**\n * Checks whether a given/any consignment is being updated.\n *\n * A consignment ID should be provided when checking for a specific consignment,\n * otherwise it will check for any consignment.\n *\n * @param consignmentId - The identifier of the consignment to be checked.\n * @returns True if updating consignment(s), otherwise false.\n */\n isUpdatingConsignment(consignmentId?: string): boolean;\n\n /**\n * Checks whether a given/any consignment is being deleted.\n *\n * A consignment ID should be provided when checking for a specific consignment,\n * otherwise it will check for any consignment.\n *\n * @param consignmentId - The identifier of the consignment to be checked.\n * @returns True if deleting consignment(s), otherwise false.\n */\n isDeletingConsignment(consignmentId?: string): boolean;\n\n /**\n * Checks whether a given/any consignment is being updated.\n *\n * A consignment ID should be provided when checking for a specific consignment,\n * otherwise it will check for any consignment.\n *\n * @returns True if creating consignments, otherwise false.\n */\n isCreatingConsignments(): boolean;\n\n /**\n * Checks whether the shipping step of a checkout process is initializing.\n *\n * If an identifier is provided, the method also checks whether the shipping\n * step is initializing using a specific shipping method with the same\n * identifier.\n *\n * @param methodId - The identifer of the initialization method to check.\n * @returns True if the shipping step is initializing, otherwise false.\n */\n isInitializingShipping(methodId?: string): boolean;\n\n /**\n * Checks whether the current customer is applying a coupon code.\n *\n * @returns True if applying a coupon code, otherwise false.\n */\n isApplyingCoupon(): boolean;\n\n /**\n * Checks whether the current customer is applying store credit.\n *\n * @returns True if applying store credit, otherwise false.\n */\n isApplyingStoreCredit(): boolean;\n\n /**\n * Checks whether the current customer is removing a coupon code.\n *\n * @returns True if removing a coupon code, otherwise false.\n */\n isRemovingCoupon(): boolean;\n\n /**\n * Checks whether a sign-in email is being sent.\n *\n * @returns True if sending a sign-in email, otherwise false\n */\n isSendingSignInEmail(): boolean;\n\n /**\n * Checks whether the current customer is applying a gift certificate.\n *\n * @returns True if applying a gift certificate, otherwise false.\n */\n isApplyingGiftCertificate(): boolean;\n\n /**\n * Checks whether the current customer is removing a gift certificate.\n *\n * @returns True if removing a gift certificate, otherwise false.\n */\n isRemovingGiftCertificate(): boolean;\n\n /**\n * Checks whether the current customer's payment instruments are loading.\n *\n * @returns True if payment instruments are loading, otherwise false.\n */\n isLoadingInstruments(): boolean;\n\n /**\n * Checks whether the current customer is deleting a payment instrument.\n *\n * @returns True if deleting a payment instrument, otherwise false.\n */\n isDeletingInstrument(instrumentId?: string): boolean;\n\n /**\n * Checks whether the checkout configuration of a store is loading.\n *\n * @returns True if the configuration is loading, otherwise false.\n */\n isLoadingConfig(): boolean;\n\n /**\n * Checks whether the customer step of a checkout is in a pending state.\n *\n * The customer step is considered to be pending if it is in the process of\n * initializing, signing in, signing out, and/or interacting with a customer\n * widget.\n *\n * @returns True if the customer step is pending, otherwise false.\n */\n isCustomerStepPending(): boolean;\n\n /**\n * Checks whether the shipping step of a checkout is in a pending state.\n *\n * The shipping step is considered to be pending if it is in the process of\n * initializing, updating address, selecting a shipping option, and/or\n * interacting with a shipping widget.\n *\n * @returns True if the shipping step is pending, otherwise false.\n */\n isShippingStepPending(): boolean;\n\n /**\n * Checks whether the payment step of a checkout is in a pending state.\n *\n * The payment step is considered to be pending if it is in the process of\n * initializing, submitting an order, finalizing an order, and/or\n * interacting with a payment widget.\n *\n * @returns True if the payment step is pending, otherwise false.\n */\n isPaymentStepPending(): boolean;\n\n /**\n * Checks whether the subscriptions are being updated.\n *\n * @returns True if updating subscriptions, otherwise false.\n */\n isUpdatingSubscriptions(): boolean;\n\n /**\n * Checks whether a customer account is being created\n *\n * @returns True if creating, otherwise false.\n */\n isCreatingCustomerAccount(): boolean;\n\n /**\n * Checks whether a customer address is being created\n *\n * @returns True if creating, otherwise false.\n */\n isCreatingCustomerAddress(): boolean;\n\n /**\n * Checks whether pickup options are loading.\n *\n * @returns True if pickup options are loading, otherwise false.\n */\n isLoadingPickupOptions(): boolean;\n}\n\nexport type CheckoutStoreStatusSelectorFactory = (\n state: InternalCheckoutSelectors,\n) => CheckoutStoreStatusSelector;\n\nexport function createCheckoutStoreStatusSelectorFactory(): CheckoutStoreStatusSelectorFactory {\n const isPending = createShallowEqualSelector(\n (selector: Omit) => selector,\n (selector) => () => {\n return (\n Object.keys(selector) as Array>\n ).some((key) => selector[key]());\n },\n );\n\n const isSelectingShippingOption = createSelector(\n ({ shippingStrategies }: InternalCheckoutSelectors) => shippingStrategies.isSelectingOption,\n ({ consignments }: InternalCheckoutSelectors) => consignments.isUpdatingShippingOption,\n (isSelectingOption, isUpdatingShippingOption) => (consignmentId?: string) => {\n return isSelectingOption() || isUpdatingShippingOption(consignmentId);\n },\n );\n\n const isCustomerStepPending = createSelector(\n ({ customerStrategies }: InternalCheckoutSelectors) => customerStrategies.isInitializing,\n ({ customerStrategies }: InternalCheckoutSelectors) => customerStrategies.isSigningIn,\n ({ customerStrategies }: InternalCheckoutSelectors) => customerStrategies.isSigningOut,\n ({ customerStrategies }: InternalCheckoutSelectors) =>\n customerStrategies.isExecutingPaymentMethodCheckout,\n ({ customerStrategies }: InternalCheckoutSelectors) =>\n customerStrategies.isWidgetInteracting,\n (\n isInitializing,\n isSigningIn,\n isSigningOut,\n isExecutingPaymentMethodCheckout,\n isWidgetInteracting,\n ) =>\n (methodId?: string) => {\n return (\n isInitializing(methodId) ||\n isSigningIn(methodId) ||\n isSigningOut(methodId) ||\n isExecutingPaymentMethodCheckout(methodId) ||\n isWidgetInteracting(methodId)\n );\n },\n );\n\n const isShippingStepPending = createSelector(\n ({ shippingStrategies }: InternalCheckoutSelectors) => shippingStrategies.isInitializing,\n ({ shippingStrategies }: InternalCheckoutSelectors) => shippingStrategies.isUpdatingAddress,\n ({ shippingStrategies }: InternalCheckoutSelectors) => shippingStrategies.isSelectingOption,\n ({ shippingStrategies }: InternalCheckoutSelectors) =>\n shippingStrategies.isWidgetInteracting,\n (isInitializing, isUpdatingAddress, isSelectingOption, isWidgetInteracting) =>\n (methodId?: string) => {\n return (\n isInitializing(methodId) ||\n isUpdatingAddress(methodId) ||\n isSelectingOption(methodId) ||\n isWidgetInteracting(methodId)\n );\n },\n );\n\n const isPaymentStepPending = createSelector(\n ({ paymentStrategies }: InternalCheckoutSelectors) => paymentStrategies.isInitializing,\n ({ paymentStrategies }: InternalCheckoutSelectors) => paymentStrategies.isExecuting,\n ({ paymentStrategies }: InternalCheckoutSelectors) => paymentStrategies.isFinalizing,\n ({ paymentStrategies }: InternalCheckoutSelectors) => paymentStrategies.isWidgetInteracting,\n (isInitializing, isExecuting, isFinalizing, isWidgetInteracting) => (methodId?: string) => {\n return (\n isInitializing(methodId) ||\n isExecuting(methodId) ||\n isFinalizing(methodId) ||\n isWidgetInteracting(methodId)\n );\n },\n );\n\n const isSubmittingOrder = createSelector(\n ({ paymentStrategies }: InternalCheckoutSelectors) => paymentStrategies.isExecuting,\n ({ checkout }: InternalCheckoutSelectors) => checkout.isExecutingSpamCheck, // Remove this when CheckoutService#initializeSpamProtection is deprecated\n (isExecuting, isExecutingSpamCheck) => (methodId?: string) => {\n return isExecuting(methodId) || isExecutingSpamCheck();\n },\n );\n\n return memoizeOne((state: InternalCheckoutSelectors): CheckoutStoreStatusSelector => {\n const selector = {\n isLoadingCheckout: state.checkout.isLoading,\n isUpdatingCheckout: state.checkout.isUpdating,\n isExecutingSpamCheck: state.checkout.isExecutingSpamCheck,\n isSubmittingOrder: isSubmittingOrder(state),\n isFinalizingOrder: state.paymentStrategies.isFinalizing,\n isLoadingOrder: state.order.isLoading,\n isLoadingCart: state.cart.isLoading,\n isLoadingBillingCountries: state.countries.isLoading,\n isLoadingShippingCountries: state.shippingCountries.isLoading,\n isLoadingPaymentMethods: state.paymentMethods.isLoading,\n isLoadingPaymentMethod: state.paymentMethods.isLoadingMethod,\n isInitializingPayment: state.paymentStrategies.isInitializing,\n isSigningIn: state.customerStrategies.isSigningIn,\n isSigningOut: state.customerStrategies.isSigningOut,\n isExecutingPaymentMethodCheckout:\n state.customerStrategies.isExecutingPaymentMethodCheckout,\n isInitializingCustomer: state.customerStrategies.isInitializing,\n isInitializedCustomer: state.customerStrategies.isInitialized,\n isLoadingShippingOptions: state.consignments.isLoadingShippingOptions,\n isSelectingShippingOption: isSelectingShippingOption(state),\n isUpdatingBillingAddress: state.billingAddress.isUpdating,\n isUpdatingSubscriptions: state.subscriptions.isUpdating,\n isCreatingCustomerAccount: state.customer.isCreatingCustomerAccount,\n isCreatingCustomerAddress: state.customer.isCreatingCustomerAddress,\n isContinuingAsGuest: state.billingAddress.isContinuingAsGuest,\n isUpdatingShippingAddress: state.shippingStrategies.isUpdatingAddress,\n isUpdatingConsignment: state.consignments.isUpdating,\n isDeletingConsignment: state.consignments.isDeleting,\n isCreatingConsignments: state.consignments.isCreating,\n isInitializingShipping: state.shippingStrategies.isInitializing,\n isApplyingStoreCredit: state.storeCredit.isApplying,\n isApplyingCoupon: state.coupons.isApplying,\n isRemovingCoupon: state.coupons.isRemoving,\n isApplyingGiftCertificate: state.giftCertificates.isApplying,\n isRemovingGiftCertificate: state.giftCertificates.isRemoving,\n isLoadingInstruments: state.instruments.isLoading,\n isDeletingInstrument: state.instruments.isDeleting,\n isLoadingConfig: state.config.isLoading,\n isSendingSignInEmail: state.signInEmail.isSending,\n isCustomerStepPending: isCustomerStepPending(state),\n isShippingStepPending: isShippingStepPending(state),\n isPaymentStepPending: isPaymentStepPending(state),\n isLoadingPickupOptions: state.pickupOptions.isLoading,\n };\n\n return {\n isPending: isPending(selector),\n ...selector,\n };\n });\n}\n","import {\n CheckoutSelectors,\n createCheckoutStoreErrorSelectorFactory,\n createCheckoutStoreSelectorFactory,\n createCheckoutStoreStatusSelectorFactory,\n InternalCheckoutSelectors,\n} from '../checkout';\n\nexport type CheckoutSelectorsFactory = (selectors: InternalCheckoutSelectors) => CheckoutSelectors;\n\nexport function createCheckoutSelectorsFactory(): CheckoutSelectorsFactory {\n const createCheckoutStoreSelector = createCheckoutStoreSelectorFactory();\n const createCheckoutStoreErrorSelector = createCheckoutStoreErrorSelectorFactory();\n const createCheckoutStoreStatusSelector = createCheckoutStoreStatusSelectorFactory();\n\n return (selectors: InternalCheckoutSelectors) => {\n const data = createCheckoutStoreSelector(selectors);\n const errors = createCheckoutStoreErrorSelector(selectors);\n const statuses = createCheckoutStoreStatusSelector(selectors);\n\n return {\n data,\n errors,\n statuses,\n };\n };\n}\n\nexport default function createCheckoutSelectors(\n selectors: InternalCheckoutSelectors,\n): CheckoutSelectors {\n return createCheckoutSelectorsFactory()(selectors);\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport RequestError from './request-error';\n\n/**\n * Throw this error if there is an unexpected error and it is not possible to\n * recover from unless the shopper creates a new checkout session.\n */\nexport default class UnrecoverableError extends RequestError {\n constructor(response: Response, message?: string) {\n super(response, {\n message:\n message ||\n 'An unexpected error has occurred. The checkout process cannot continue as a result.',\n });\n\n this.name = 'UnrecoverableError';\n this.type = 'unrecoverable';\n }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { InternalErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport RequestError from './request-error';\n\nexport default function mapFromInternalErrorResponse(\n response: Response,\n message?: string,\n): RequestError {\n const { body } = response;\n const { errors = [] } = body;\n\n return new RequestError(response, {\n message: joinErrors(errors) || body.detail || body.title || message,\n errors: errors.length\n ? errors.map((message) => ({ code: body.type, message }))\n : [{ code: body.type, message: body.detail || body.title }],\n });\n}\n\nfunction joinErrors(errors: string[]): string | undefined {\n return errors\n .reduce((result: string[], error) => {\n if (error) {\n return [...result, error];\n }\n\n return result;\n }, [])\n .join(' ');\n}\n","import { Response } from '@bigcommerce/request-sender';\nimport { last } from 'lodash';\n\nimport {\n ErrorResponseBody,\n InternalErrorResponseBody,\n StorefrontErrorResponseBody,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n mapFromInternalErrorResponse,\n mapFromPaymentErrorResponse,\n mapFromStorefrontErrorResponse,\n RequestError,\n TimeoutError,\n} from './errors';\n\nexport default class RequestErrorFactory {\n private _factoryMethods: { [key: string]: ErrorFactoryMethod } = {};\n\n constructor() {\n this.register('default', (response, message) => new RequestError(response, { message }));\n this.register('internal', (response, message) =>\n mapFromInternalErrorResponse(response, message),\n );\n this.register('storefront', (response, message) =>\n mapFromStorefrontErrorResponse(response, message),\n );\n this.register('payment', (response, message) =>\n mapFromPaymentErrorResponse(response, message),\n );\n this.register('timeout', (response) => new TimeoutError(response));\n }\n\n register(type: string, factoryMethod: ErrorFactoryMethod): void {\n this._factoryMethods[type] = factoryMethod;\n }\n\n createError(response: Response, message?: string): RequestError {\n const factoryMethod =\n this._factoryMethods[this._getType(response)] || this._factoryMethods.default;\n\n return factoryMethod(response, message);\n }\n\n private _getType(response: Response): string {\n if (response.status === 0) {\n return 'timeout';\n }\n\n if (this._isStorefrontErrorResponseBody(response.body)) {\n return 'storefront';\n }\n\n if (this._isInternalErrorResponseBody(response.body)) {\n const internalType = last(response.body.type.split('/'));\n\n return internalType && this._factoryMethods[internalType] ? internalType : 'internal';\n }\n\n const error = last(response.body && response.body.errors);\n\n if (error && error.code && this._factoryMethods[error.code]) {\n return error.code;\n }\n\n return 'payment';\n }\n\n private _isStorefrontErrorResponseBody(\n errorResponse: ErrorResponseBody,\n ): errorResponse is StorefrontErrorResponseBody {\n const storefrontErrorResponse = errorResponse as StorefrontErrorResponseBody;\n\n return (\n !this._isInternalErrorResponseBody(errorResponse) &&\n typeof storefrontErrorResponse.title === 'string' &&\n typeof storefrontErrorResponse.type === 'string' &&\n typeof storefrontErrorResponse.status === 'number' &&\n typeof storefrontErrorResponse.detail === 'string'\n );\n }\n\n private _isInternalErrorResponseBody(\n errorResponse: ErrorResponseBody,\n ): errorResponse is InternalErrorResponseBody {\n const internalErrorResponse = errorResponse as InternalErrorResponseBody;\n\n return (\n typeof internalErrorResponse.errors === 'object' &&\n typeof internalErrorResponse.title === 'string' &&\n typeof internalErrorResponse.type === 'string' &&\n typeof internalErrorResponse.status === 'number'\n );\n }\n}\n\nexport type ErrorFactoryMethod = (response: Response, message?: string) => RequestError;\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport RequestError from './request-error';\n\nexport default function mapFromStorefrontErrorResponse(\n response: Response,\n message?: string,\n): RequestError {\n const { body } = response;\n\n return new RequestError(response, {\n message: message || body.detail || body.title,\n errors: [\n {\n code: body.code || body.type,\n message: body.detail || body.title,\n },\n ],\n });\n}\n","import { isPlainObject, omitBy, transform } from 'lodash';\n\nexport default function omitDeep(\n object: any,\n predicate: (value: any, key: string) => boolean,\n): any {\n if (Array.isArray(object)) {\n return object.map((value) => omitDeep(value, predicate));\n }\n\n if (isPlainObject(object)) {\n return transform(\n omitBy(object, predicate),\n (result, value, key) => {\n result[key] = omitDeep(value, predicate);\n },\n {} as { [key: string]: any },\n );\n }\n\n return object;\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { omitDeep } from '../utility';\n\nimport { ClearErrorAction, ErrorActionType } from './error-actions';\n\nexport default function clearErrorReducer<\n TState extends { [key: string]: any },\n TAction extends Action,\n>(state: TState, action: TAction): TState | undefined {\n if (isClearErrorAction(action)) {\n return omitDeep(state, (value) => value === action.payload);\n }\n\n return state;\n}\n\nfunction isClearErrorAction(action: Action): action is ClearErrorAction {\n return action.type === ErrorActionType.ClearError;\n}\n","export interface CompareOptions {\n keyFilter?(key: string): boolean;\n}\n\nexport default function isEqual(objectA: any, objectB: any, options?: CompareOptions): boolean {\n if (objectA === objectB) {\n return true;\n }\n\n if (objectA && objectB && typeof objectA === 'object' && typeof objectB === 'object') {\n if (Array.isArray(objectA) && Array.isArray(objectB)) {\n return isArrayEqual(objectA, objectB, options);\n }\n\n if (Array.isArray(objectA) || Array.isArray(objectB)) {\n return false;\n }\n\n if (objectA instanceof Date && objectB instanceof Date) {\n return isDateEqual(objectA, objectB);\n }\n\n if (objectA instanceof Date || objectB instanceof Date) {\n return false;\n }\n\n if (objectA instanceof RegExp && objectB instanceof RegExp) {\n return isRegExpEqual(objectA, objectB);\n }\n\n if (objectA instanceof RegExp || objectB instanceof RegExp) {\n return false;\n }\n\n return isObjectEqual(objectA, objectB, options);\n }\n\n return objectA === objectB;\n}\n\nfunction isRegExpEqual(objectA: RegExp, objectB: RegExp): boolean {\n return objectA.toString() === objectB.toString();\n}\n\nfunction isDateEqual(objectA: Date, objectB: Date): boolean {\n return objectA.getTime() === objectB.getTime();\n}\n\nfunction isArrayEqual(objectA: any[], objectB: any[], options?: CompareOptions): boolean {\n if (objectA.length !== objectB.length) {\n return false;\n }\n\n for (let index = 0, length = objectA.length; index < length; index++) {\n if (!isEqual(objectA[index], objectB[index], options)) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction isObjectEqual(\n objectA: { [key: string]: any },\n objectB: { [key: string]: any },\n options?: CompareOptions,\n): boolean {\n const filter = options && options.keyFilter;\n const keysA = filter ? Object.keys(objectA).filter(filter) : Object.keys(objectA);\n const keysB = filter ? Object.keys(objectB).filter(filter) : Object.keys(objectB);\n\n if (keysA.length !== keysB.length) {\n return false;\n }\n\n for (let index = 0, length = keysA.length; index < length; index++) {\n const key = keysA[index];\n\n if (!Object.prototype.hasOwnProperty.call(objectB, key)) {\n return false;\n }\n\n if (!isEqual(objectA[key], objectB[key], options)) {\n return false;\n }\n }\n\n return true;\n}\n","import isEqual from './is-equal';\n\n/**\n * Replace the current value with a new value if the former is different to the\n * latter.\n */\nexport default function replace(currentValue: T, newValue?: T): T {\n if (newValue === undefined || isEqual(currentValue, newValue)) {\n return currentValue;\n }\n\n return newValue;\n}\n","import isEqual from './is-equal';\n\n/**\n * Set a new value to an object under a key if the new value is different to the\n * current value of the key.\n */\nexport default function objectSet(\n object: T | undefined,\n key: K,\n value: T[K],\n): T {\n if (\n object &&\n Object.prototype.hasOwnProperty.call(object, key) &&\n isEqual(object[key], value)\n ) {\n return object;\n }\n\n return {\n ...(object as any),\n [key]: value,\n };\n}\n","import BillingAddress from './billing-address';\n\nexport default interface BillingAddressState {\n data?: BillingAddress;\n errors: BillingAddressErrorsState;\n statuses: BillingAddressStatusesState;\n}\n\nexport interface BillingAddressErrorsState {\n loadError?: Error;\n updateError?: Error;\n continueAsGuestError?: Error;\n}\n\nexport interface BillingAddressStatusesState {\n isLoading?: boolean;\n isUpdating?: boolean;\n isContinuingAsGuest?: boolean;\n}\n\nexport const DEFAULT_STATE: BillingAddressState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { objectSet, replace } from '../common/utility';\nimport { OrderAction } from '../order';\nimport { SubscriptionsActionType, UpdateSubscriptionsAction } from '../subscription';\n\nimport BillingAddress from './billing-address';\nimport { BillingAddressAction, BillingAddressActionType } from './billing-address-actions';\nimport BillingAddressState, {\n BillingAddressErrorsState,\n BillingAddressStatusesState,\n DEFAULT_STATE,\n} from './billing-address-state';\n\nexport default function billingAddressReducer(\n state: BillingAddressState = DEFAULT_STATE,\n action: Action,\n): BillingAddressState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: BillingAddress | undefined,\n action: CheckoutAction | BillingAddressAction | OrderAction,\n): BillingAddress | undefined {\n switch (action.type) {\n case BillingAddressActionType.UpdateBillingAddressSucceeded:\n case BillingAddressActionType.ContinueAsGuestSucceeded:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return replace(data, action.payload && action.payload.billingAddress);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: BillingAddressErrorsState = DEFAULT_STATE.errors,\n action: CheckoutAction | BillingAddressAction | OrderAction | UpdateSubscriptionsAction,\n): BillingAddressErrorsState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case CheckoutActionType.LoadCheckoutFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n case BillingAddressActionType.UpdateBillingAddressRequested:\n case BillingAddressActionType.UpdateBillingAddressSucceeded:\n return objectSet(errors, 'updateError', undefined);\n\n case BillingAddressActionType.UpdateBillingAddressFailed:\n return objectSet(errors, 'updateError', action.payload);\n\n case SubscriptionsActionType.UpdateSubscriptionsRequested:\n case SubscriptionsActionType.UpdateSubscriptionsSucceeded:\n case BillingAddressActionType.ContinueAsGuestRequested:\n case BillingAddressActionType.ContinueAsGuestSucceeded:\n return objectSet(errors, 'continueAsGuestError', undefined);\n\n case SubscriptionsActionType.UpdateSubscriptionsFailed:\n case BillingAddressActionType.ContinueAsGuestFailed:\n return objectSet(errors, 'continueAsGuestError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: BillingAddressStatusesState = DEFAULT_STATE.statuses,\n action: CheckoutAction | BillingAddressAction | OrderAction | UpdateSubscriptionsAction,\n): BillingAddressStatusesState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case CheckoutActionType.LoadCheckoutSucceeded:\n case CheckoutActionType.LoadCheckoutFailed:\n return objectSet(statuses, 'isLoading', false);\n\n case BillingAddressActionType.UpdateBillingAddressRequested:\n return objectSet(statuses, 'isUpdating', true);\n\n case BillingAddressActionType.UpdateBillingAddressFailed:\n case BillingAddressActionType.UpdateBillingAddressSucceeded:\n return objectSet(statuses, 'isUpdating', false);\n\n case BillingAddressActionType.ContinueAsGuestRequested:\n case SubscriptionsActionType.UpdateSubscriptionsRequested:\n return objectSet(statuses, 'isContinuingAsGuest', true);\n\n case SubscriptionsActionType.UpdateSubscriptionsSucceeded:\n case SubscriptionsActionType.UpdateSubscriptionsFailed:\n case BillingAddressActionType.ContinueAsGuestFailed:\n case BillingAddressActionType.ContinueAsGuestSucceeded:\n return objectSet(statuses, 'isContinuingAsGuest', false);\n\n default:\n return statuses;\n }\n}\n","import { isArray } from 'lodash';\n\nimport isPlainObject from './is-plain-object';\nimport objectMerge from './object-merge';\nimport replace from './replace';\n\nexport interface ArrayReplaceOptions {\n matchObject(objectA: any, objectB: any): boolean;\n}\n\nfunction arrayReplace(\n currentArray: T[] | undefined,\n newArray: T[],\n options?: ArrayReplaceOptions,\n): T[];\nfunction arrayReplace(\n currentArray: T[],\n newArray?: T[],\n options?: ArrayReplaceOptions,\n): undefined;\nfunction arrayReplace(\n currentArray?: T[],\n newArray?: T[],\n options?: ArrayReplaceOptions,\n): T[] | undefined;\n\nfunction arrayReplace(\n currentArray?: T[],\n newArray?: T[],\n options?: ArrayReplaceOptions,\n): T[] | undefined {\n const { matchObject = (a: any, b: any) => a.id !== undefined && a.id === b.id } = options || {};\n\n // Return the new array if the current array does not exist\n if (!currentArray) {\n return newArray;\n }\n\n // If the new array does not exist, or the current array is strictly equal\n // to the new array, exit early and return the current array so that the\n // object reference doesn't change\n if (!newArray || currentArray === newArray) {\n return currentArray;\n }\n\n // Otherwise, try to replace the items of the current array with the new\n // array. If the item from the two arrays are the same, keep the current\n // one. Do it recursively until all arrays are replaced.\n let sameAsCurrentCount = 0;\n let sameAsNewCount = 0;\n\n const countSameAsReplaced = (replacedValue: T, currentValue: T, newValue: T): T => {\n sameAsCurrentCount += replacedValue === currentValue ? 1 : 0;\n sameAsNewCount += replacedValue === newValue ? 1 : 0;\n\n return replacedValue;\n };\n\n const result = newArray.map((newItem, index) => {\n const currentItem = currentArray && currentArray[index];\n\n if (isPlainObject(currentItem) && isPlainObject(newItem)) {\n if (matchObject(currentItem, newItem)) {\n return countSameAsReplaced(objectMerge(currentItem, newItem), currentItem, newItem);\n }\n\n return countSameAsReplaced(replace(currentItem, newItem), currentItem, newItem);\n }\n\n if (isArray(currentItem) && isArray(newItem)) {\n return countSameAsReplaced(arrayReplace(currentItem, newItem), currentItem, newItem);\n }\n\n return countSameAsReplaced(replace(currentItem, newItem), currentItem, newItem);\n }) as T[];\n\n // If all items in the result are identical to the current array, and the\n // current array and the new array have the same size, simply return the\n // current array instead of the result.\n if (\n sameAsCurrentCount === newArray.length &&\n currentArray &&\n currentArray.length === newArray.length\n ) {\n return currentArray;\n }\n\n // If all items in the result are identical to the new array, simply return\n // the new array.\n if (sameAsNewCount === newArray.length) {\n return newArray;\n }\n\n return result;\n}\n\nexport default arrayReplace;\n","import { isArray } from 'lodash';\n\nimport arrayReplace from './array-replace';\nimport isPlainObject from './is-plain-object';\nimport objectSet from './object-set';\n\nfunction objectMerge(currentObject: T, newObject?: Partial): T;\nfunction objectMerge(\n currentObject: T | undefined,\n newObject: Partial,\n): Partial;\nfunction objectMerge(currentObject?: T, newObject?: Partial): T | undefined;\n\nfunction objectMerge(\n currentObject?: T,\n newObject?: Partial,\n): T | Partial | undefined {\n if (!currentObject) {\n return newObject;\n }\n\n // If the new object does not exist but the current object does, or the new\n // object is strictly equal to the current object, return the current object\n if (!newObject || currentObject === newObject) {\n return currentObject;\n }\n\n // If both objects exist, but some values might be different, perform a merge.\n // Retain values that are equal and only replace them with the new values if\n // they are different.\n return (Object.keys(newObject) as Array).reduce((result, key) => {\n const currentValue = result[key];\n const newValue = newObject[key];\n\n if (isPlainObject(currentValue) && isPlainObject(newValue)) {\n return objectSet(result, key, objectMerge(currentValue, newValue));\n }\n\n if (isArray(currentValue) && isArray(newValue)) {\n return objectSet(result, key, arrayReplace(currentValue, newValue) as any);\n }\n\n return objectSet(result, key, newValue as any);\n }, currentObject);\n}\n\nexport default objectMerge;\n","import Cart from './cart';\n\nexport default interface CartState {\n data?: Cart;\n errors: CartErrorsState;\n statuses: CartStatusesState;\n}\n\nexport interface CartErrorsState {\n loadError?: Error;\n}\n\nexport interface CartStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: CartState = {\n errors: {},\n statuses: {},\n};\n","import { Action } from '@bigcommerce/data-store';\n\nimport { LoadPaymentMethodAction } from '../payment';\n\nimport { CheckoutButtonMethodType } from './strategies';\n\nexport enum CheckoutButtonActionType {\n InitializeButtonFailed = 'INITIALIZE_BUTTON_FAILED',\n InitializeButtonRequested = 'INITIALIZE_BUTTON_REQUESTED',\n InitializeButtonSucceeded = 'INITIALIZE_BUTTON_SUCCEEDED',\n\n DeinitializeButtonFailed = 'DEINITIALIZE_BUTTON_FAILED',\n DeinitializeButtonRequested = 'DEINITIALIZE_BUTTON_REQUESTED',\n DeinitializeButtonSucceeded = 'DEINITIALIZE_BUTTON_SUCCEEDED',\n}\n\nexport type CheckoutButtonAction = InitializeButtonAction | DeinitializeButtonAction;\n\nexport type InitializeButtonAction =\n | InitializeButtonRequestedAction\n | InitializeButtonSucceededAction\n | InitializeButtonFailedAction\n | LoadPaymentMethodAction;\n\nexport type DeinitializeButtonAction =\n | DeinitializeButtonRequestedAction\n | DeinitializeButtonSucceededAction\n | DeinitializeButtonFailedAction;\n\nexport interface CheckoutButtonActionMeta {\n methodId: CheckoutButtonMethodType;\n}\n\nexport interface InitializeButtonActionMeta extends CheckoutButtonActionMeta {\n containerId: string;\n}\n\nexport interface InitializeButtonRequestedAction\n extends Action {\n type: CheckoutButtonActionType.InitializeButtonRequested;\n}\n\nexport interface InitializeButtonSucceededAction\n extends Action {\n type: CheckoutButtonActionType.InitializeButtonSucceeded;\n}\n\nexport interface InitializeButtonFailedAction extends Action {\n type: CheckoutButtonActionType.InitializeButtonFailed;\n}\n\nexport interface DeinitializeButtonRequestedAction\n extends Action {\n type: CheckoutButtonActionType.DeinitializeButtonRequested;\n}\n\nexport interface DeinitializeButtonSucceededAction\n extends Action {\n type: CheckoutButtonActionType.DeinitializeButtonSucceeded;\n}\n\nexport interface DeinitializeButtonFailedAction extends Action {\n type: CheckoutButtonActionType.DeinitializeButtonFailed;\n}\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { BillingAddressAction, BillingAddressActionType } from '../billing';\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\nimport {\n CouponAction,\n CouponActionType,\n GiftCertificateAction,\n GiftCertificateActionType,\n} from '../coupon';\nimport { ConsignmentAction, ConsignmentActionType } from '../shipping';\n\nimport Cart from './cart';\nimport CartState, { CartErrorsState, CartStatusesState, DEFAULT_STATE } from './cart-state';\n\nexport default function cartReducer(state: CartState = DEFAULT_STATE, action: Action): CartState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: Cart | undefined,\n action:\n | BillingAddressAction\n | CheckoutAction\n | ConsignmentAction\n | CouponAction\n | GiftCertificateAction,\n): Cart | undefined {\n switch (action.type) {\n case BillingAddressActionType.UpdateBillingAddressSucceeded:\n case CheckoutActionType.LoadCheckoutSucceeded:\n case ConsignmentActionType.CreateConsignmentsSucceeded:\n case ConsignmentActionType.DeleteConsignmentSucceeded:\n case ConsignmentActionType.UpdateConsignmentSucceeded:\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n case ConsignmentActionType.LoadShippingOptionsSucceeded:\n case CouponActionType.ApplyCouponSucceeded:\n case CouponActionType.RemoveCouponSucceeded:\n case GiftCertificateActionType.ApplyGiftCertificateSucceeded:\n case GiftCertificateActionType.RemoveGiftCertificateSucceeded:\n return objectMerge(data, action.payload && action.payload.cart);\n\n default:\n return data;\n }\n}\n\nfunction statusesReducer(\n statuses: CartStatusesState = DEFAULT_STATE.statuses,\n action: CheckoutAction,\n): CartStatusesState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case CheckoutActionType.LoadCheckoutFailed:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n\nfunction errorsReducer(\n errors: CartErrorsState = DEFAULT_STATE.errors,\n action: CheckoutAction,\n): CartErrorsState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case CheckoutActionType.LoadCheckoutFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n","import { CheckoutButtonMethodType } from './strategies';\n\nexport default interface CheckoutButtonState {\n data: {\n [key in CheckoutButtonMethodType]?: CheckoutButtonDataState | undefined;\n };\n errors: {\n [key in CheckoutButtonMethodType]?: CheckoutButtonErrorsState | undefined;\n };\n statuses: {\n [key in CheckoutButtonMethodType]?: CheckoutButtonStatusesState | undefined;\n };\n}\n\nexport interface CheckoutButtonDataState {\n initializedContainers: {\n [key: string]: boolean;\n };\n}\n\nexport interface CheckoutButtonErrorsState {\n initializeError?: Error;\n deinitializeError?: Error;\n}\n\nexport interface CheckoutButtonStatusesState {\n isInitializing?: boolean;\n isDeinitializing?: boolean;\n}\n\nexport const DEFAULT_STATE: CheckoutButtonState = {\n data: {},\n errors: {},\n statuses: {},\n};\n","import { combineReducers } from '@bigcommerce/data-store';\n\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport { CheckoutButtonAction, CheckoutButtonActionType } from './checkout-button-actions';\nimport CheckoutButtonState, {\n CheckoutButtonDataState,\n CheckoutButtonErrorsState,\n CheckoutButtonStatusesState,\n DEFAULT_STATE,\n} from './checkout-button-state';\n\nconst DEFAULT_DATA_STATE: CheckoutButtonDataState = { initializedContainers: {} };\nconst DEFAULT_ERROR_STATE: CheckoutButtonErrorsState = {};\nconst DEFAULT_STATUS_STATE: CheckoutButtonStatusesState = {};\n\nexport default function checkoutButtonReducer(\n state: CheckoutButtonState = DEFAULT_STATE,\n action: CheckoutButtonAction,\n): CheckoutButtonState {\n if (!action.meta || !action.meta.methodId) {\n return state;\n }\n\n const reducer = combineReducers({\n data: combineReducers({\n [action.meta.methodId]: dataReducer,\n }),\n errors: combineReducers({\n [action.meta.methodId]: errorsReducer,\n }),\n statuses: combineReducers({\n [action.meta.methodId]: statusesReducer,\n }),\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: CheckoutButtonDataState = DEFAULT_DATA_STATE,\n action: CheckoutButtonAction,\n): CheckoutButtonDataState {\n switch (action.type) {\n case CheckoutButtonActionType.InitializeButtonSucceeded:\n if (!action.meta || !action.meta.containerId) {\n return data;\n }\n\n return objectMerge(data, {\n initializedContainers: {\n [action.meta.containerId]: true,\n },\n });\n\n case CheckoutButtonActionType.DeinitializeButtonSucceeded:\n return objectSet(data, 'initializedContainers', {});\n }\n\n return data;\n}\n\nfunction errorsReducer(\n errors: CheckoutButtonErrorsState = DEFAULT_ERROR_STATE,\n action: CheckoutButtonAction,\n): CheckoutButtonErrorsState {\n switch (action.type) {\n case CheckoutButtonActionType.InitializeButtonRequested:\n case CheckoutButtonActionType.InitializeButtonSucceeded:\n return objectSet(errors, 'initializeError', undefined);\n\n case CheckoutButtonActionType.InitializeButtonFailed:\n return objectSet(errors, 'initializeError', action.payload);\n\n case CheckoutButtonActionType.DeinitializeButtonRequested:\n case CheckoutButtonActionType.DeinitializeButtonSucceeded:\n return objectSet(errors, 'deinitializeError', undefined);\n\n case CheckoutButtonActionType.DeinitializeButtonFailed:\n return objectSet(errors, 'deinitializeError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: CheckoutButtonStatusesState = DEFAULT_STATUS_STATE,\n action: CheckoutButtonAction,\n): CheckoutButtonStatusesState {\n switch (action.type) {\n case CheckoutButtonActionType.InitializeButtonRequested:\n return objectSet(statuses, 'isInitializing', true);\n\n case CheckoutButtonActionType.InitializeButtonFailed:\n case CheckoutButtonActionType.InitializeButtonSucceeded:\n return objectSet(statuses, 'isInitializing', false);\n\n case CheckoutButtonActionType.DeinitializeButtonRequested:\n return objectSet(statuses, 'isDeinitializing', true);\n\n case CheckoutButtonActionType.DeinitializeButtonFailed:\n case CheckoutButtonActionType.DeinitializeButtonSucceeded:\n return objectSet(statuses, 'isDeinitializing', false);\n\n default:\n return statuses;\n }\n}\n","import Config from './config';\n\nexport default interface ConfigState {\n data?: Config;\n meta?: ConfigMetaState;\n errors: ConfigErrorsState;\n statuses: ConfigStatusesState;\n}\n\nexport interface ConfigMetaState {\n externalSource?: string;\n variantIdentificationToken?: string;\n host?: string;\n locale?: string;\n}\n\nexport interface ConfigErrorsState {\n loadError?: Error;\n}\n\nexport interface ConfigStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: ConfigState = {\n meta: {},\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport Config from './config';\nimport { ConfigActionType, LoadConfigAction } from './config-actions';\nimport ConfigState, { ConfigErrorsState, ConfigStatusesState, DEFAULT_STATE } from './config-state';\n\nexport default function configReducer(\n state: ConfigState = DEFAULT_STATE,\n action: Action,\n): ConfigState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(data: Config | undefined, action: LoadConfigAction): Config | undefined {\n switch (action.type) {\n case ConfigActionType.LoadConfigSucceeded:\n return objectMerge(data, action.payload);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: ConfigErrorsState = DEFAULT_STATE.errors,\n action: LoadConfigAction,\n): ConfigErrorsState {\n switch (action.type) {\n case ConfigActionType.LoadConfigSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case ConfigActionType.LoadConfigFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: ConfigStatusesState = DEFAULT_STATE.statuses,\n action: LoadConfigAction,\n): ConfigStatusesState {\n switch (action.type) {\n case ConfigActionType.LoadConfigRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case ConfigActionType.LoadConfigSucceeded:\n case ConfigActionType.LoadConfigFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","import { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RequestError } from '../common/error/errors';\n\nimport Coupon from './coupon';\n\nexport default interface CouponState {\n data?: Coupon[];\n errors: CouponErrorsState;\n statuses: CouponStatusesState;\n}\n\nexport interface CouponErrorsState {\n applyCouponError?: RequestError;\n removeCouponError?: RequestError;\n}\n\nexport interface CouponStatusesState {\n isApplyingCoupon?: boolean;\n isRemovingCoupon?: boolean;\n}\n\nexport const DEFAULT_STATE: CouponState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectSet } from '../common/utility';\nimport { OrderAction, OrderActionType } from '../order';\nimport { ConsignmentAction, ConsignmentActionType } from '../shipping';\n\nimport Coupon from './coupon';\nimport { CouponAction, CouponActionType } from './coupon-actions';\nimport CouponState, { CouponErrorsState, CouponStatusesState, DEFAULT_STATE } from './coupon-state';\n\nexport default function couponReducer(\n state: CouponState = DEFAULT_STATE,\n action: Action,\n): CouponState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: Coupon[] | undefined,\n action: CouponAction | CheckoutAction | OrderAction | ConsignmentAction,\n): Coupon[] | undefined {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutSucceeded:\n case CouponActionType.ApplyCouponSucceeded:\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n case CouponActionType.RemoveCouponSucceeded:\n case OrderActionType.LoadOrderSucceeded:\n return arrayReplace(data, action.payload && action.payload.coupons);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(errors: CouponErrorsState = {}, action: CouponAction): CouponErrorsState {\n switch (action.type) {\n case CouponActionType.ApplyCouponRequested:\n case CouponActionType.ApplyCouponSucceeded:\n return objectSet(errors, 'applyCouponError', undefined);\n\n case CouponActionType.ApplyCouponFailed:\n return objectSet(errors, 'applyCouponError', action.payload);\n\n case CouponActionType.RemoveCouponRequested:\n case CouponActionType.RemoveCouponSucceeded:\n return objectSet(errors, 'removeCouponError', undefined);\n\n case CouponActionType.RemoveCouponFailed:\n return objectSet(errors, 'removeCouponError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: CouponStatusesState = {},\n action: CouponAction,\n): CouponStatusesState {\n switch (action.type) {\n case CouponActionType.ApplyCouponRequested:\n return objectSet(statuses, 'isApplyingCoupon', true);\n\n case CouponActionType.ApplyCouponSucceeded:\n case CouponActionType.ApplyCouponFailed:\n return objectSet(statuses, 'isApplyingCoupon', false);\n\n case CouponActionType.RemoveCouponRequested:\n return objectSet(statuses, 'isRemovingCoupon', true);\n\n case CouponActionType.RemoveCouponSucceeded:\n case CouponActionType.RemoveCouponFailed:\n return objectSet(statuses, 'isRemovingCoupon', false);\n\n default:\n return statuses;\n }\n}\n","import { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RequestError } from '../common/error/errors';\n\nimport GiftCertificate from './gift-certificate';\n\nexport default interface GiftCertificateState {\n data?: GiftCertificate[];\n errors: GiftCertificateErrorsState;\n statuses: GiftCertificateStatusesState;\n}\n\nexport interface GiftCertificateErrorsState {\n applyGiftCertificateError?: RequestError;\n removeGiftCertificateError?: RequestError;\n}\n\nexport interface GiftCertificateStatusesState {\n isApplyingGiftCertificate?: boolean;\n isRemovingGiftCertificate?: boolean;\n}\n\nexport const DEFAULT_STATE: GiftCertificateState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectSet } from '../common/utility';\nimport { ConsignmentAction, ConsignmentActionType } from '../shipping';\n\nimport { CouponAction, CouponActionType } from './coupon-actions';\nimport GiftCertificate from './gift-certificate';\nimport { GiftCertificateAction, GiftCertificateActionType } from './gift-certificate-actions';\nimport GiftCertificateState, {\n DEFAULT_STATE,\n GiftCertificateErrorsState,\n GiftCertificateStatusesState,\n} from './gift-certificate-state';\n\nexport default function giftCertificateReducer(\n state: GiftCertificateState = DEFAULT_STATE,\n action: Action,\n): GiftCertificateState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: GiftCertificate[] | undefined,\n action: CheckoutAction | GiftCertificateAction | ConsignmentAction | CouponAction,\n): GiftCertificate[] | undefined {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutSucceeded:\n case ConsignmentActionType.CreateConsignmentsSucceeded:\n case ConsignmentActionType.UpdateConsignmentSucceeded:\n case ConsignmentActionType.DeleteConsignmentSucceeded:\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n case CouponActionType.ApplyCouponSucceeded:\n case CouponActionType.RemoveCouponSucceeded:\n case GiftCertificateActionType.ApplyGiftCertificateSucceeded:\n case GiftCertificateActionType.RemoveGiftCertificateSucceeded:\n return arrayReplace(data, action.payload && action.payload.giftCertificates);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: GiftCertificateErrorsState = DEFAULT_STATE.errors,\n action: GiftCertificateAction,\n): GiftCertificateErrorsState {\n switch (action.type) {\n case GiftCertificateActionType.ApplyGiftCertificateRequested:\n case GiftCertificateActionType.ApplyGiftCertificateSucceeded:\n return objectSet(errors, 'applyGiftCertificateError', undefined);\n\n case GiftCertificateActionType.ApplyGiftCertificateFailed:\n return objectSet(errors, 'applyGiftCertificateError', action.payload);\n\n case GiftCertificateActionType.RemoveGiftCertificateRequested:\n case GiftCertificateActionType.RemoveGiftCertificateSucceeded:\n return objectSet(errors, 'removeGiftCertificateError', undefined);\n\n case GiftCertificateActionType.RemoveGiftCertificateFailed:\n return objectSet(errors, 'removeGiftCertificateError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: GiftCertificateStatusesState = DEFAULT_STATE.statuses,\n action: GiftCertificateAction,\n): GiftCertificateStatusesState {\n switch (action.type) {\n case GiftCertificateActionType.ApplyGiftCertificateRequested:\n return objectSet(statuses, 'isApplyingGiftCertificate', true);\n\n case GiftCertificateActionType.ApplyGiftCertificateSucceeded:\n case GiftCertificateActionType.ApplyGiftCertificateFailed:\n return objectSet(statuses, 'isApplyingGiftCertificate', false);\n\n case GiftCertificateActionType.RemoveGiftCertificateRequested:\n return objectSet(statuses, 'isRemovingGiftCertificate', true);\n\n case GiftCertificateActionType.RemoveGiftCertificateSucceeded:\n case GiftCertificateActionType.RemoveGiftCertificateFailed:\n return objectSet(statuses, 'isRemovingGiftCertificate', false);\n\n default:\n return statuses;\n }\n}\n","import Customer from './customer';\n\nexport default interface CustomerState {\n data?: Customer;\n statuses: CustomerStatusesState;\n errors: CustomerErrorsState;\n}\n\nexport interface CustomerErrorsState {\n createError?: Error;\n createAddressError?: Error;\n}\n\nexport interface CustomerStatusesState {\n isCreating?: boolean;\n isCreatingAddress?: boolean;\n}\n\nexport const DEFAULT_STATE: CustomerState = {\n errors: {},\n statuses: {},\n};\n","import { combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { BillingAddressActionType, ContinueAsGuestAction } from '../billing';\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport Customer from './customer';\nimport {\n CustomerAction,\n CustomerActionType,\n StripeLinkAuthenticatedAction,\n} from './customer-actions';\nimport CustomerState, {\n CustomerErrorsState,\n CustomerStatusesState,\n DEFAULT_STATE,\n} from './customer-state';\n\ntype ReducerActionType =\n | CheckoutAction\n | ContinueAsGuestAction\n | CustomerAction\n | StripeLinkAuthenticatedAction;\n\nexport default function customerReducer(\n state: CustomerState = DEFAULT_STATE,\n action: ReducerActionType,\n): CustomerState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(data: Customer | undefined, action: ReducerActionType): Customer | undefined {\n switch (action.type) {\n case BillingAddressActionType.ContinueAsGuestSucceeded:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return objectMerge(data, action.payload && action.payload.customer);\n\n case CustomerActionType.CreateCustomerAddressSucceeded:\n return objectMerge(data, action.payload);\n\n case CustomerActionType.StripeLinkAuthenticated:\n return objectSet(data, 'isStripeLinkAuthenticated', action.payload);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: CustomerErrorsState = DEFAULT_STATE.errors,\n action: ReducerActionType,\n): CustomerErrorsState {\n switch (action.type) {\n case CustomerActionType.CreateCustomerRequested:\n case CustomerActionType.CreateCustomerSucceeded:\n return objectSet(errors, 'createError', undefined);\n\n case CustomerActionType.CreateCustomerFailed:\n return objectSet(errors, 'createError', action.payload);\n\n case CustomerActionType.CreateCustomerAddressRequested:\n case CustomerActionType.CreateCustomerAddressSucceeded:\n return objectSet(errors, 'createAddressError', undefined);\n\n case CustomerActionType.CreateCustomerAddressFailed:\n return objectSet(errors, 'createAddressError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: CustomerStatusesState = DEFAULT_STATE.statuses,\n action: ReducerActionType,\n): CustomerStatusesState {\n switch (action.type) {\n case CustomerActionType.CreateCustomerRequested:\n return objectSet(statuses, 'isCreating', true);\n\n case CustomerActionType.CreateCustomerFailed:\n case CustomerActionType.CreateCustomerSucceeded:\n return objectSet(statuses, 'isCreating', false);\n\n case CustomerActionType.CreateCustomerAddressRequested:\n return objectSet(statuses, 'isCreatingAddress', true);\n\n case CustomerActionType.CreateCustomerAddressFailed:\n case CustomerActionType.CreateCustomerAddressSucceeded:\n return objectSet(statuses, 'isCreatingAddress', false);\n\n default:\n return statuses;\n }\n}\n","export default interface CustomerStrategyState {\n data: CustomerStrategyDataState;\n errors: CustomerStrategyErrorsState;\n statuses: CustomerStrategyStatusesState;\n}\n\nexport interface CustomerStrategyDataState {\n [key: string]: {\n isInitialized: boolean;\n };\n}\n\nexport interface CustomerStrategyErrorsState {\n deinitializeError?: Error;\n deinitializeMethodId?: string;\n initializeErrors?: { [key: string]: Error };\n initializeMethodId?: string;\n signInError?: Error;\n signInMethodId?: string;\n signOutError?: Error;\n signOutMethodId?: string;\n executePaymentMethodCheckoutError?: Error;\n executePaymentMethodCheckoutMethodId?: string;\n widgetInteractionError?: Error;\n widgetInteractionMethodId?: string;\n}\n\nexport interface CustomerStrategyStatusesState {\n deinitializeMethodId?: string;\n initializeMethodId?: string;\n isDeinitializing?: boolean;\n isInitializing?: boolean;\n isSigningIn?: boolean;\n isSigningOut?: boolean;\n signInMethodId?: string;\n signOutMethodId?: string;\n isExecutingPaymentMethodCheckout?: boolean;\n executePaymentMethodCheckoutMethodId?: string;\n isWidgetInteracting?: boolean;\n widgetInteractionMethodId?: string;\n}\n\nexport const DEFAULT_STATE: CustomerStrategyState = {\n data: {},\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge } from '../common/utility';\n\nimport { CustomerStrategyAction, CustomerStrategyActionType } from './customer-strategy-actions';\nimport CustomerStrategyState, {\n CustomerStrategyDataState,\n CustomerStrategyErrorsState,\n CustomerStrategyStatusesState,\n DEFAULT_STATE,\n} from './customer-strategy-state';\n\nexport default function customerStrategyReducer(\n state: CustomerStrategyState = DEFAULT_STATE,\n action: Action,\n): CustomerStrategyState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: CustomerStrategyDataState = DEFAULT_STATE.data,\n action: CustomerStrategyAction,\n): CustomerStrategyDataState {\n switch (action.type) {\n case CustomerStrategyActionType.InitializeSucceeded:\n return objectMerge(data, {\n [action.meta && action.meta.methodId]: {\n isInitialized: true,\n },\n });\n\n case CustomerStrategyActionType.DeinitializeSucceeded:\n return objectMerge(data, {\n [action.meta && action.meta.methodId]: {\n isInitialized: false,\n },\n });\n }\n\n return data;\n}\n\nfunction errorsReducer(\n errors: CustomerStrategyErrorsState = DEFAULT_STATE.errors,\n action: CustomerStrategyAction,\n): CustomerStrategyErrorsState {\n switch (action.type) {\n case CustomerStrategyActionType.InitializeRequested:\n case CustomerStrategyActionType.InitializeSucceeded:\n return objectMerge(errors, {\n initializeErrors: { ...errors.initializeErrors },\n initializeMethodId: errors.initializeMethodId\n ? errors.initializeMethodId\n : undefined,\n });\n\n case CustomerStrategyActionType.InitializeFailed:\n return objectMerge(errors, {\n initializeErrors: {\n ...errors.initializeErrors,\n [action.meta && action.meta.methodId]: action.payload,\n },\n initializeMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.DeinitializeRequested:\n case CustomerStrategyActionType.DeinitializeSucceeded:\n return objectMerge(errors, {\n deinitializeError: undefined,\n deinitializeMethodId: undefined,\n });\n\n case CustomerStrategyActionType.DeinitializeFailed:\n return objectMerge(errors, {\n deinitializeError: action.payload,\n deinitializeMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.SignInRequested:\n case CustomerStrategyActionType.SignInSucceeded:\n return objectMerge(errors, {\n signInError: undefined,\n signInMethodId: undefined,\n });\n\n case CustomerStrategyActionType.SignInFailed:\n return objectMerge(errors, {\n signInError: action.payload,\n signInMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.SignOutRequested:\n case CustomerStrategyActionType.SignOutSucceeded:\n return objectMerge(errors, {\n signOutError: undefined,\n signOutMethodId: undefined,\n });\n\n case CustomerStrategyActionType.SignOutFailed:\n return objectMerge(errors, {\n signOutError: action.payload,\n signOutMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.ExecutePaymentMethodCheckoutRequested:\n case CustomerStrategyActionType.ExecutePaymentMethodCheckoutSucceeded:\n return objectMerge(errors, {\n executePaymentMethodCheckoutError: undefined,\n executePaymentMethodCheckoutMethodId: undefined,\n });\n\n case CustomerStrategyActionType.ExecutePaymentMethodCheckoutFailed:\n return objectMerge(errors, {\n executePaymentMethodCheckoutError: action.payload,\n executePaymentMethodCheckoutMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.WidgetInteractionStarted:\n case CustomerStrategyActionType.WidgetInteractionFinished:\n return objectMerge(errors, {\n widgetInteractionError: undefined,\n widgetInteractionMethodId: undefined,\n });\n\n case CustomerStrategyActionType.WidgetInteractionFailed:\n return objectMerge(errors, {\n widgetInteractionError: action.payload,\n widgetInteractionMethodId: action.meta.methodId,\n });\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: CustomerStrategyStatusesState = DEFAULT_STATE.statuses,\n action: CustomerStrategyAction,\n): CustomerStrategyStatusesState {\n switch (action.type) {\n case CustomerStrategyActionType.InitializeRequested:\n return objectMerge(statuses, {\n isInitializing: true,\n initializeMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.InitializeFailed:\n case CustomerStrategyActionType.InitializeSucceeded:\n return objectMerge(statuses, {\n isInitializing: false,\n initializeMethodId: undefined,\n });\n\n case CustomerStrategyActionType.DeinitializeRequested:\n return objectMerge(statuses, {\n isDeinitializing: true,\n deinitializeMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.DeinitializeFailed:\n case CustomerStrategyActionType.DeinitializeSucceeded:\n return objectMerge(statuses, {\n isDeinitializing: false,\n deinitializeMethodId: undefined,\n });\n\n case CustomerStrategyActionType.SignInRequested:\n return objectMerge(statuses, {\n isSigningIn: true,\n signInMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.SignInFailed:\n case CustomerStrategyActionType.SignInSucceeded:\n return objectMerge(statuses, {\n isSigningIn: false,\n signInMethodId: undefined,\n });\n\n case CustomerStrategyActionType.SignOutRequested:\n return objectMerge(statuses, {\n isSigningOut: true,\n signOutMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.SignOutFailed:\n case CustomerStrategyActionType.SignOutSucceeded:\n return objectMerge(statuses, {\n isSigningOut: false,\n signOutMethodId: undefined,\n });\n\n case CustomerStrategyActionType.ExecutePaymentMethodCheckoutRequested:\n return objectMerge(statuses, {\n isExecutingPaymentMethodCheckout: true,\n executePaymentMethodCheckoutMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.ExecutePaymentMethodCheckoutFailed:\n case CustomerStrategyActionType.ExecutePaymentMethodCheckoutSucceeded:\n return objectMerge(statuses, {\n isExecutingPaymentMethodCheckout: false,\n executePaymentMethodCheckoutMethodId: undefined,\n });\n\n case CustomerStrategyActionType.WidgetInteractionStarted:\n return objectMerge(statuses, {\n isWidgetInteracting: true,\n widgetInteractionMethodId: action.meta.methodId,\n });\n\n case CustomerStrategyActionType.WidgetInteractionFinished:\n case CustomerStrategyActionType.WidgetInteractionFailed:\n return objectMerge(statuses, {\n isWidgetInteracting: false,\n widgetInteractionMethodId: undefined,\n });\n\n default:\n return statuses;\n }\n}\n","import { Extension } from './extension';\n\nexport interface ExtensionState {\n data?: Extension[];\n errors: ExtensionErrorsState;\n statuses: ExtensionStatusesState;\n}\n\nexport interface ExtensionErrorsState {\n loadError?: Error;\n}\n\nexport interface ExtensionStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: ExtensionState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectSet } from '../common/utility';\n\nimport { Extension } from './extension';\nimport { ExtensionAction, ExtensionActionType } from './extension-actions';\nimport {\n DEFAULT_STATE,\n ExtensionErrorsState,\n ExtensionState,\n ExtensionStatusesState,\n} from './extension-state';\n\nexport function extensionReducer(\n state: ExtensionState = DEFAULT_STATE,\n action: Action,\n): ExtensionState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: Extension[] | undefined,\n action: ExtensionAction,\n): Extension[] | undefined {\n if (action.type === ExtensionActionType.LoadExtensionsSucceeded) {\n return arrayReplace(data, action.payload);\n }\n\n return data;\n}\n\nfunction errorsReducer(\n errors: ExtensionErrorsState = DEFAULT_STATE.errors,\n action: ExtensionAction,\n): ExtensionErrorsState {\n switch (action.type) {\n case ExtensionActionType.LoadExtensionsRequested:\n case ExtensionActionType.LoadExtensionsSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case ExtensionActionType.LoadExtensionsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: ExtensionStatusesState = DEFAULT_STATE.statuses,\n action: ExtensionAction,\n): ExtensionStatusesState {\n switch (action.type) {\n case ExtensionActionType.LoadExtensionsRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case ExtensionActionType.LoadExtensionsSucceeded:\n case ExtensionActionType.LoadExtensionsFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","import { FormFields } from './form-field';\n\nexport default interface FormFieldsState {\n data?: FormFields;\n errors: FormFieldsErrorState;\n statuses: FormFieldsStatusesState;\n}\n\nexport interface FormFieldsErrorState {\n loadError?: Error;\n}\n\nexport interface FormFieldsStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: FormFieldsState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport { FormFields } from './form-field';\nimport { FormFieldsActionType, LoadFormFieldsAction } from './form-fields-actions';\nimport FormFieldsState, {\n DEFAULT_STATE,\n FormFieldsErrorState,\n FormFieldsStatusesState,\n} from './form-fields-state';\n\nexport default function formFieldsReducer(\n state: FormFieldsState = DEFAULT_STATE,\n action: Action,\n): FormFieldsState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: FormFields | undefined,\n action: LoadFormFieldsAction,\n): FormFields | undefined {\n switch (action.type) {\n case FormFieldsActionType.LoadFormFieldsSucceeded:\n return objectMerge(data, action.payload);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: FormFieldsErrorState = DEFAULT_STATE.errors,\n action: LoadFormFieldsAction,\n): FormFieldsErrorState {\n switch (action.type) {\n case FormFieldsActionType.LoadFormFieldsSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case FormFieldsActionType.LoadFormFieldsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: FormFieldsStatusesState = DEFAULT_STATE.statuses,\n action: LoadFormFieldsAction,\n): FormFieldsStatusesState {\n switch (action.type) {\n case FormFieldsActionType.LoadFormFieldsRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case FormFieldsActionType.LoadFormFieldsSucceeded:\n case FormFieldsActionType.LoadFormFieldsFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","import Country from './country';\n\nexport default interface CountryState {\n data?: Country[];\n errors: CountryErrorsState;\n statuses: CountryStatusesState;\n}\n\nexport interface CountryErrorsState {\n loadError?: Error;\n}\n\nexport interface CountryStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: CountryState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectSet } from '../common/utility';\n\nimport Country from './country';\nimport { CountryActionType, LoadCountriesAction } from './country-actions';\nimport CountryState, {\n CountryErrorsState,\n CountryStatusesState,\n DEFAULT_STATE,\n} from './country-state';\n\nexport default function countryReducer(\n state: CountryState = DEFAULT_STATE,\n action: Action,\n): CountryState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: Country[] | undefined,\n action: LoadCountriesAction,\n): Country[] | undefined {\n switch (action.type) {\n case CountryActionType.LoadCountriesSucceeded:\n return arrayReplace(data, action.payload);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: CountryErrorsState = DEFAULT_STATE.errors,\n action: LoadCountriesAction,\n): CountryErrorsState {\n switch (action.type) {\n case CountryActionType.LoadCountriesRequested:\n case CountryActionType.LoadCountriesSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case CountryActionType.LoadCountriesFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: CountryStatusesState = DEFAULT_STATE.statuses,\n action: LoadCountriesAction,\n): CountryStatusesState {\n switch (action.type) {\n case CountryActionType.LoadCountriesRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case CountryActionType.LoadCountriesSucceeded:\n case CountryActionType.LoadCountriesFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","import { Omit } from '../common/types';\n\nimport { InternalOrderMeta, InternalOrderPayment } from './internal-order';\nimport Order from './order';\n\nexport default interface OrderState {\n data?: OrderDataState;\n meta?: OrderMetaState;\n errors: OrderErrorsState;\n statuses: OrderStatusesState;\n}\n\nexport type OrderDataState = Omit;\n\nexport interface OrderMetaState extends InternalOrderMeta {\n token?: string;\n orderToken?: string;\n callbackUrl?: string;\n payment?: InternalOrderPayment;\n}\n\nexport interface OrderErrorsState {\n loadError?: Error;\n submitError?: Error;\n finalizeError?: Error;\n}\n\nexport interface OrderStatusesState {\n isLoading?: boolean;\n isSubmitting?: boolean;\n isFinalizing?: boolean;\n}\n\nexport const DEFAULT_STATE: OrderState = {\n errors: {},\n meta: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\nimport { omit } from 'lodash';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport { OrderAction, OrderActionType } from './order-actions';\nimport OrderState, {\n DEFAULT_STATE,\n OrderDataState,\n OrderErrorsState,\n OrderMetaState,\n OrderStatusesState,\n} from './order-state';\n\nexport default function orderReducer(\n state: OrderState = DEFAULT_STATE,\n action: Action,\n): OrderState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n meta: metaReducer,\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: OrderDataState | undefined,\n action: OrderAction,\n): OrderDataState | undefined {\n switch (action.type) {\n case OrderActionType.LoadOrderSucceeded:\n case OrderActionType.LoadOrderPaymentsSucceeded:\n return objectMerge(\n data,\n omit(action.payload, ['billingAddress', 'coupons']),\n ) as OrderDataState;\n\n default:\n return data;\n }\n}\n\nfunction metaReducer(\n meta: OrderMetaState | undefined,\n action: OrderAction,\n): OrderMetaState | undefined {\n switch (action.type) {\n case OrderActionType.FinalizeOrderSucceeded:\n case OrderActionType.SubmitOrderSucceeded:\n return objectMerge(meta, {\n ...action.meta,\n callbackUrl: action.payload && action.payload.order.callbackUrl,\n orderToken: action.payload && action.payload.order.token,\n payment: action.payload && action.payload.order && action.payload.order.payment,\n });\n\n default:\n return meta;\n }\n}\n\nfunction errorsReducer(\n errors: OrderErrorsState = DEFAULT_STATE.errors,\n action: OrderAction,\n): OrderErrorsState {\n switch (action.type) {\n case OrderActionType.LoadOrderRequested:\n case OrderActionType.LoadOrderSucceeded:\n case OrderActionType.LoadOrderPaymentsSucceeded:\n case OrderActionType.LoadOrderPaymentsRequested:\n return objectSet(errors, 'loadError', undefined);\n\n case OrderActionType.LoadOrderFailed:\n case OrderActionType.LoadOrderPaymentsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: OrderStatusesState = DEFAULT_STATE.statuses,\n action: OrderAction,\n): OrderStatusesState {\n switch (action.type) {\n case OrderActionType.LoadOrderRequested:\n case OrderActionType.LoadOrderPaymentsRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case OrderActionType.LoadOrderSucceeded:\n case OrderActionType.LoadOrderFailed:\n case OrderActionType.LoadOrderPaymentsSucceeded:\n case OrderActionType.LoadOrderPaymentsFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","import { Address } from '../address';\n\nexport interface OrderBillingAddress extends Address {\n email?: string;\n}\n\nexport default interface OrderBillingAddressState {\n data?: OrderBillingAddress;\n}\n\nexport const DEFAULT_STATE: OrderBillingAddressState = {};\n","import { Action, combineReducers } from '@bigcommerce/data-store';\n\nimport { replace } from '../common/utility';\nimport { OrderAction, OrderActionType } from '../order';\n\nimport OrderBillingAddressState, {\n DEFAULT_STATE,\n OrderBillingAddress,\n} from './order-billing-address-state';\n\nexport default function orderBillingAddressReducer(\n state: OrderBillingAddressState = DEFAULT_STATE,\n action: Action,\n): OrderBillingAddressState {\n const reducer = combineReducers({\n data: dataReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: OrderBillingAddress | undefined,\n action: OrderAction,\n): OrderBillingAddress | undefined {\n switch (action.type) {\n case OrderActionType.LoadOrderPaymentsSucceeded:\n case OrderActionType.LoadOrderSucceeded:\n return replace(data, action.payload && action.payload.billingAddress);\n\n default:\n return data;\n }\n}\n","import { combineReducers } from '@bigcommerce/data-store';\n\nimport { PaymentAction, PaymentActionType } from './payment-actions';\nimport PaymentResponseBody from './payment-response-body';\nimport PaymentState from './payment-state';\n\nexport default function paymentReducer(\n state: PaymentState = {},\n action: PaymentAction,\n): PaymentState {\n const reducer = combineReducers({\n data: dataReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: PaymentResponseBody | undefined,\n action: PaymentAction,\n): PaymentResponseBody | undefined {\n switch (action.type) {\n case PaymentActionType.SubmitPaymentSucceeded:\n return action.payload;\n\n default:\n return data;\n }\n}\n","import PaymentMethod from './payment-method';\nimport PaymentMethodMeta from './payment-method-meta';\n\nexport default interface PaymentMethodState {\n data?: PaymentMethod[];\n meta?: PaymentMethodMeta;\n errors: PaymentMethodErrorsState;\n statuses: PaymentMethodStatusesState;\n}\n\nexport interface PaymentMethodErrorsState {\n loadMethodId?: string;\n loadError?: Error;\n loadMethodError?: Error;\n}\n\nexport interface PaymentMethodStatusesState {\n loadMethodId?: string;\n isLoading?: boolean;\n isLoadingMethod?: boolean;\n}\n\nexport const DEFAULT_STATE: PaymentMethodState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, mergeOrPush, objectMerge, objectSet } from '../common/utility';\n\nimport PaymentMethod from './payment-method';\nimport { PaymentMethodAction, PaymentMethodActionType } from './payment-method-actions';\nimport PaymentMethodMeta from './payment-method-meta';\nimport PaymentMethodState, {\n DEFAULT_STATE,\n PaymentMethodErrorsState,\n PaymentMethodStatusesState,\n} from './payment-method-state';\n\nexport default function paymentMethodReducer(\n state: PaymentMethodState = DEFAULT_STATE,\n action: Action,\n): PaymentMethodState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n meta: metaReducer,\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: PaymentMethod[] | undefined,\n action: PaymentMethodAction,\n): PaymentMethod[] | undefined {\n switch (action.type) {\n case PaymentMethodActionType.LoadPaymentMethodSucceeded:\n return mergeOrPush(\n data || [],\n action.payload,\n action.payload && {\n id: action.payload.id,\n gateway: action.payload.gateway,\n },\n );\n\n case PaymentMethodActionType.LoadPaymentMethodsSucceeded:\n return arrayReplace(data, action.payload, {\n matchObject: (methodA, methodB) =>\n methodA.id === methodB.id && methodA.gateway === methodB.gateway,\n });\n\n default:\n return data;\n }\n}\n\nfunction metaReducer(\n meta: PaymentMethodMeta | undefined,\n action: PaymentMethodAction,\n): PaymentMethodMeta | undefined {\n switch (action.type) {\n case PaymentMethodActionType.LoadPaymentMethodsSucceeded:\n return objectMerge(meta, action.meta);\n\n default:\n return meta;\n }\n}\n\nfunction errorsReducer(\n errors: PaymentMethodErrorsState = DEFAULT_STATE.errors,\n action: PaymentMethodAction,\n): PaymentMethodErrorsState {\n switch (action.type) {\n case PaymentMethodActionType.LoadPaymentMethodsRequested:\n case PaymentMethodActionType.LoadPaymentMethodsSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case PaymentMethodActionType.LoadPaymentMethodsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n case PaymentMethodActionType.LoadPaymentMethodRequested:\n case PaymentMethodActionType.LoadPaymentMethodSucceeded:\n return objectMerge(errors, {\n loadMethodId: undefined,\n loadMethodError: undefined,\n });\n\n case PaymentMethodActionType.LoadPaymentMethodFailed:\n return objectMerge(errors, {\n loadMethodId: action.meta.methodId,\n loadMethodError: action.payload,\n });\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: PaymentMethodStatusesState = DEFAULT_STATE.statuses,\n action: PaymentMethodAction,\n): PaymentMethodStatusesState {\n switch (action.type) {\n case PaymentMethodActionType.LoadPaymentMethodsRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case PaymentMethodActionType.LoadPaymentMethodsSucceeded:\n case PaymentMethodActionType.LoadPaymentMethodsFailed:\n return objectSet(statuses, 'isLoading', false);\n\n case PaymentMethodActionType.LoadPaymentMethodRequested:\n return objectMerge(statuses, {\n isLoadingMethod: true,\n loadMethodId: action.meta.methodId,\n });\n\n case PaymentMethodActionType.LoadPaymentMethodSucceeded:\n case PaymentMethodActionType.LoadPaymentMethodFailed:\n return objectMerge(statuses, {\n isLoadingMethod: false,\n loadMethodId: undefined,\n });\n\n default:\n return statuses;\n }\n}\n","import { findIndex, pick, pickBy, ValueKeyIteratee } from 'lodash';\n\nimport isPlainObject from './is-plain-object';\nimport objectMerge from './object-merge';\n\n/**\n * Push an item to an array if it doesn't exist in the array. Otherwise, merge\n * with the existing item in the array. This function always returns a new array.\n */\nexport default function mergeOrPush(array: T[], item?: T, predicate?: ValueKeyIteratee): T[] {\n if (!item) {\n return array;\n }\n\n const defaultPredicate = pick(item, 'id');\n const index = findIndex(\n array,\n typeof predicate === 'object' ? pickBy(predicate) : predicate || defaultPredicate,\n );\n const newArray = [...array];\n\n if (index === -1) {\n newArray.push(item);\n } else {\n const existingItem = array[index];\n\n newArray[index] =\n isPlainObject(existingItem) && isPlainObject(item)\n ? objectMerge(existingItem, item)\n : item;\n }\n\n return newArray;\n}\n","export default interface PaymentStrategyState {\n data: PaymentStrategyDataState;\n errors: PaymentStrategyErrorsState;\n statuses: PaymentStrategyStatusesState;\n}\n\nexport interface PaymentStrategyDataState {\n [key: string]: {\n isInitialized: boolean;\n };\n}\n\nexport interface PaymentStrategyErrorsState {\n deinitializeError?: Error;\n deinitializeMethodId?: string;\n executeError?: Error;\n executeMethodId?: string;\n finalizeError?: Error;\n finalizeMethodId?: string;\n initializeError?: Error;\n initializeMethodId?: string;\n widgetInteractionError?: Error;\n widgetInteractionMethodId?: string;\n}\n\nexport interface PaymentStrategyStatusesState {\n deinitializeMethodId?: string;\n executeMethodId?: string;\n finalizeMethodId?: string;\n initializeMethodId?: string;\n isDeinitializing?: boolean;\n isExecuting?: boolean;\n isFinalizing?: boolean;\n isInitializing?: boolean;\n isWidgetInteracting?: boolean;\n widgetInteractionMethodId?: string;\n}\n\nexport const DEFAULT_STATE: PaymentStrategyState = {\n data: {},\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge } from '../common/utility';\n\nimport { PaymentStrategyAction, PaymentStrategyActionType } from './payment-strategy-actions';\nimport PaymentStrategyState, {\n DEFAULT_STATE,\n PaymentStrategyDataState,\n PaymentStrategyErrorsState,\n PaymentStrategyStatusesState,\n} from './payment-strategy-state';\n\nexport default function paymentStrategyReducer(\n state: PaymentStrategyState = DEFAULT_STATE,\n action: Action,\n): PaymentStrategyState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: PaymentStrategyDataState = DEFAULT_STATE.data,\n action: PaymentStrategyAction,\n): PaymentStrategyDataState {\n switch (action.type) {\n case PaymentStrategyActionType.InitializeSucceeded: {\n if (action.meta) {\n const { methodId, gatewayId } = action.meta;\n const initializeMethodId = gatewayId ? `${methodId}.${gatewayId}` : methodId;\n\n return objectMerge(data, {\n [initializeMethodId]: {\n isInitialized: true,\n },\n });\n }\n\n break;\n }\n\n case PaymentStrategyActionType.DeinitializeSucceeded: {\n if (action.meta) {\n const { methodId, gatewayId } = action.meta;\n const initializeMethodId = gatewayId ? `${methodId}.${gatewayId}` : methodId;\n\n return objectMerge(data, {\n [initializeMethodId]: {\n isInitialized: false,\n },\n });\n }\n }\n }\n\n return data;\n}\n\nfunction errorsReducer(\n errors: PaymentStrategyErrorsState = DEFAULT_STATE.errors,\n action: PaymentStrategyAction,\n): PaymentStrategyErrorsState {\n switch (action.type) {\n case PaymentStrategyActionType.InitializeRequested:\n case PaymentStrategyActionType.InitializeSucceeded:\n return objectMerge(errors, {\n initializeError: undefined,\n initializeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.InitializeFailed: {\n let initializeMethodId = action.meta && action.meta.methodId;\n\n if (action.meta) {\n const { methodId, gatewayId } = action.meta;\n\n initializeMethodId = gatewayId ? `${methodId}.${gatewayId}` : methodId;\n }\n\n return objectMerge(errors, {\n initializeError: action.payload,\n initializeMethodId,\n });\n }\n\n case PaymentStrategyActionType.DeinitializeRequested:\n case PaymentStrategyActionType.DeinitializeSucceeded:\n return objectMerge(errors, {\n deinitializeError: undefined,\n deinitializeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.DeinitializeFailed: {\n let deinitializeMethodId = action.meta && action.meta.methodId;\n\n if (action.meta) {\n const { methodId, gatewayId } = action.meta;\n\n deinitializeMethodId = gatewayId ? `${methodId}.${gatewayId}` : methodId;\n }\n\n return objectMerge(errors, {\n deinitializeError: action.payload,\n deinitializeMethodId,\n });\n }\n\n case PaymentStrategyActionType.ExecuteRequested:\n case PaymentStrategyActionType.ExecuteSucceeded:\n return objectMerge(errors, {\n executeError: undefined,\n executeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.ExecuteFailed:\n return objectMerge(errors, {\n executeError: action.payload,\n executeMethodId: action.meta && action.meta.methodId,\n });\n\n case PaymentStrategyActionType.FinalizeRequested:\n case PaymentStrategyActionType.FinalizeSucceeded:\n return objectMerge(errors, {\n finalizeError: undefined,\n finalizeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.FinalizeFailed:\n return objectMerge(errors, {\n finalizeError: action.payload,\n finalizeMethodId: action.meta && action.meta.methodId,\n });\n\n case PaymentStrategyActionType.WidgetInteractionStarted:\n case PaymentStrategyActionType.WidgetInteractionFinished:\n return objectMerge(errors, {\n widgetInteractionError: undefined,\n widgetInteractionMethodId: undefined,\n });\n\n case PaymentStrategyActionType.WidgetInteractionFailed:\n return objectMerge(errors, {\n widgetInteractionError: action.payload,\n widgetInteractionMethodId: action.meta.methodId,\n });\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: PaymentStrategyStatusesState = DEFAULT_STATE.statuses,\n action: PaymentStrategyAction,\n): PaymentStrategyStatusesState {\n switch (action.type) {\n case PaymentStrategyActionType.InitializeRequested: {\n let initializeMethodId = action.meta && action.meta.methodId;\n\n if (action.meta) {\n const { methodId, gatewayId } = action.meta;\n\n initializeMethodId = gatewayId ? `${methodId}.${gatewayId}` : methodId;\n }\n\n return objectMerge(statuses, {\n isInitializing: true,\n initializeMethodId,\n });\n }\n\n case PaymentStrategyActionType.InitializeFailed:\n case PaymentStrategyActionType.InitializeSucceeded:\n return objectMerge(statuses, {\n isInitializing: false,\n initializeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.DeinitializeRequested: {\n let deinitializeMethodId = action.meta && action.meta.methodId;\n\n if (action.meta) {\n const { methodId, gatewayId } = action.meta;\n\n deinitializeMethodId = gatewayId ? `${methodId}.${gatewayId}` : methodId;\n }\n\n return objectMerge(statuses, {\n isDeinitializing: true,\n deinitializeMethodId,\n });\n }\n\n case PaymentStrategyActionType.DeinitializeFailed:\n case PaymentStrategyActionType.DeinitializeSucceeded:\n return objectMerge(statuses, {\n isDeinitializing: false,\n deinitializeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.ExecuteRequested:\n return objectMerge(statuses, {\n isExecuting: true,\n executeMethodId: action.meta && action.meta.methodId,\n });\n\n case PaymentStrategyActionType.ExecuteFailed:\n case PaymentStrategyActionType.ExecuteSucceeded:\n return objectMerge(statuses, {\n isExecuting: false,\n executeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.FinalizeRequested:\n return objectMerge(statuses, {\n isFinalizing: true,\n finalizeMethodId: action.meta && action.meta.methodId,\n });\n\n case PaymentStrategyActionType.FinalizeFailed:\n case PaymentStrategyActionType.FinalizeSucceeded:\n return objectMerge(statuses, {\n isFinalizing: false,\n finalizeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.WidgetInteractionStarted:\n return objectMerge(statuses, {\n isWidgetInteracting: true,\n widgetInteractionMethodId: action.meta.methodId,\n });\n\n case PaymentStrategyActionType.WidgetInteractionFinished:\n case PaymentStrategyActionType.WidgetInteractionFailed:\n return objectMerge(statuses, {\n isWidgetInteracting: false,\n widgetInteractionMethodId: undefined,\n });\n\n default:\n return statuses;\n }\n}\n","import PaymentInstrument, { VaultAccessToken } from './instrument';\n\nexport default interface InstrumentState {\n data?: PaymentInstrument[];\n meta?: InstrumentMeta;\n errors: InstrumentErrorState;\n statuses: InstrumentStatusState;\n}\n\nexport interface InstrumentErrorState {\n deleteError?: Error;\n failedInstrument?: string;\n loadError?: Error;\n vaultError?: Error;\n}\n\nexport interface InstrumentStatusState {\n isDeleting?: boolean;\n isLoading?: boolean;\n isVaulting?: boolean;\n deletingInstrument?: string;\n}\n\nexport type InstrumentMeta = VaultAccessToken;\n\nexport const DEFAULT_STATE = {\n data: [],\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../../common/error';\nimport { arrayReplace, objectMerge, objectSet } from '../../common/utility';\n\nimport PaymentInstrument from './instrument';\nimport { InstrumentAction, InstrumentActionType } from './instrument-actions';\nimport InstrumentState, {\n DEFAULT_STATE,\n InstrumentErrorState,\n InstrumentMeta,\n InstrumentStatusState,\n} from './instrument-state';\n\nexport default function instrumentReducer(\n state: InstrumentState = DEFAULT_STATE,\n action: Action,\n): InstrumentState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n meta: metaReducer,\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: PaymentInstrument[] = DEFAULT_STATE.data,\n action: InstrumentAction,\n): PaymentInstrument[] {\n switch (action.type) {\n case InstrumentActionType.LoadInstrumentsSucceeded:\n return arrayReplace(data, (action.payload && action.payload.vaultedInstruments) || []);\n\n default:\n return data;\n }\n}\n\nfunction metaReducer(\n meta: InstrumentMeta | undefined,\n action: InstrumentAction,\n): InstrumentMeta | undefined {\n switch (action.type) {\n case InstrumentActionType.LoadInstrumentsSucceeded:\n case InstrumentActionType.DeleteInstrumentSucceeded:\n return objectMerge(meta, action.meta);\n\n default:\n return meta;\n }\n}\n\nfunction errorsReducer(\n errors: InstrumentErrorState = DEFAULT_STATE.errors,\n action: InstrumentAction,\n): InstrumentErrorState {\n switch (action.type) {\n case InstrumentActionType.LoadInstrumentsRequested:\n case InstrumentActionType.LoadInstrumentsSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case InstrumentActionType.DeleteInstrumentRequested:\n case InstrumentActionType.DeleteInstrumentSucceeded:\n return objectMerge(errors, {\n deleteError: undefined,\n failedInstrument: undefined,\n });\n\n case InstrumentActionType.LoadInstrumentsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n case InstrumentActionType.DeleteInstrumentFailed:\n return objectMerge(errors, {\n deleteError: action.payload,\n failedInstrument: action.meta.instrumentId,\n });\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: InstrumentStatusState = DEFAULT_STATE.statuses,\n action: InstrumentAction,\n): InstrumentStatusState {\n switch (action.type) {\n case InstrumentActionType.LoadInstrumentsRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case InstrumentActionType.DeleteInstrumentRequested:\n return objectMerge(statuses, {\n isDeleting: true,\n deletingInstrument: action.meta.instrumentId,\n });\n\n case InstrumentActionType.LoadInstrumentsSucceeded:\n case InstrumentActionType.LoadInstrumentsFailed:\n return objectSet(statuses, 'isLoading', false);\n\n case InstrumentActionType.DeleteInstrumentSucceeded:\n case InstrumentActionType.DeleteInstrumentFailed:\n return objectMerge(statuses, {\n isDeleting: false,\n deletingInstrument: undefined,\n });\n\n default:\n return statuses;\n }\n}\n","import { AmazonPayRemoteCheckout } from './methods';\n\nexport default interface RemoteCheckoutState {\n data: RemoteCheckoutStateData;\n}\n\nexport interface RemoteCheckoutStateData {\n amazon?: AmazonPayRemoteCheckout;\n}\n\nexport const DEFAULT_STATE: RemoteCheckoutState = {\n data: {},\n};\n","import { combineReducers } from '@bigcommerce/data-store';\n\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport RemoteCheckout from './remote-checkout';\nimport { RemoteCheckoutAction, RemoteCheckoutActionType } from './remote-checkout-actions';\nimport RemoteCheckoutState, {\n DEFAULT_STATE,\n RemoteCheckoutStateData,\n} from './remote-checkout-state';\n\nexport default function remoteCheckoutReducer(\n state: RemoteCheckoutState = DEFAULT_STATE,\n action: RemoteCheckoutAction,\n): RemoteCheckoutState {\n if (!action.meta || !action.meta.methodId) {\n return state;\n }\n\n const reducer = combineReducers({\n data: combineReducers({\n [action.meta.methodId]: dataReducer,\n }),\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(data: RemoteCheckout, action: RemoteCheckoutAction): RemoteCheckout {\n switch (action.type) {\n case RemoteCheckoutActionType.InitializeRemoteBillingSucceeded:\n return objectSet(data, 'billing' as any, action.payload && action.payload.billing);\n\n case RemoteCheckoutActionType.InitializeRemoteShippingSucceeded:\n return objectSet(data, 'shipping' as any, action.payload && action.payload.shipping);\n\n case RemoteCheckoutActionType.LoadRemoteSettingsSucceeded:\n return objectSet(data, 'settings', action.payload);\n\n case RemoteCheckoutActionType.UpdateRemoteCheckout:\n return objectMerge(data, action.payload);\n\n default:\n return data;\n }\n}\n","import Consignment from './consignment';\n\nexport default interface ConsignmentState {\n data?: Consignment[];\n errors: ConsignmentErrorsState;\n statuses: ConsignmentStatusesState;\n}\n\nexport interface ConsignmentErrorsState {\n loadError?: Error;\n loadShippingOptionsError?: Error;\n createError?: Error;\n updateError: { [key: string]: Error | undefined };\n deleteError: { [key: string]: Error | undefined };\n updateShippingOptionError: { [key: string]: Error | undefined };\n}\n\nexport interface ConsignmentStatusesState {\n isLoading?: boolean;\n isLoadingShippingOptions?: boolean;\n isCreating?: boolean;\n isUpdating: { [key: string]: boolean };\n isDeleting: { [key: string]: boolean };\n isUpdatingShippingOption: { [key: string]: boolean };\n}\n\nexport const DEFAULT_STATE: ConsignmentState = {\n errors: {\n updateShippingOptionError: {},\n updateError: {},\n deleteError: {},\n },\n statuses: {\n isUpdating: {},\n isUpdatingShippingOption: {},\n isDeleting: {},\n },\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectMerge, objectSet } from '../common/utility';\nimport { CouponAction, CouponActionType } from '../coupon';\nimport { CustomerAction, CustomerActionType } from '../customer';\n\nimport Consignment from './consignment';\nimport { ConsignmentAction, ConsignmentActionType } from './consignment-actions';\nimport ConsignmentState, {\n ConsignmentErrorsState,\n ConsignmentStatusesState,\n DEFAULT_STATE,\n} from './consignment-state';\n\nexport default function consignmentReducer(\n state: ConsignmentState = DEFAULT_STATE,\n action: Action,\n): ConsignmentState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: Consignment[] | undefined,\n action: ConsignmentAction | CheckoutAction | CouponAction | CustomerAction,\n): Consignment[] | undefined {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutSucceeded:\n case ConsignmentActionType.LoadShippingOptionsSucceeded:\n case ConsignmentActionType.CreateConsignmentsSucceeded:\n case ConsignmentActionType.UpdateConsignmentSucceeded:\n case ConsignmentActionType.DeleteConsignmentSucceeded:\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n case CouponActionType.ApplyCouponSucceeded:\n case CouponActionType.RemoveCouponSucceeded:\n return arrayReplace(data, action.payload && action.payload.consignments);\n\n case CustomerActionType.SignOutCustomerSucceeded:\n return arrayReplace(data, []);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: ConsignmentErrorsState = DEFAULT_STATE.errors,\n action: ConsignmentAction | CheckoutAction,\n): ConsignmentErrorsState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n case CheckoutActionType.LoadCheckoutSucceeded:\n case ConsignmentActionType.LoadShippingOptionsSucceeded:\n case ConsignmentActionType.LoadShippingOptionsRequested:\n return objectSet(errors, 'loadError', undefined);\n\n case CheckoutActionType.LoadCheckoutFailed:\n case ConsignmentActionType.LoadShippingOptionsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n case ConsignmentActionType.CreateConsignmentsRequested:\n case ConsignmentActionType.CreateConsignmentsSucceeded:\n return objectSet(errors, 'createError', undefined);\n\n case ConsignmentActionType.CreateConsignmentsFailed:\n return objectSet(errors, 'createError', action.payload);\n\n case ConsignmentActionType.UpdateConsignmentSucceeded:\n case ConsignmentActionType.UpdateConsignmentRequested:\n if (action.meta) {\n return objectMerge(errors, {\n updateError: {\n [action.meta.id]: undefined,\n },\n });\n }\n\n return errors;\n\n case ConsignmentActionType.UpdateConsignmentFailed:\n if (action.meta) {\n return objectMerge(errors, {\n updateError: {\n [action.meta.id]: action.payload,\n },\n });\n }\n\n return errors;\n\n case ConsignmentActionType.DeleteConsignmentSucceeded:\n case ConsignmentActionType.DeleteConsignmentRequested:\n if (action.meta) {\n return objectMerge(errors, {\n deleteError: {\n [action.meta.id]: undefined,\n },\n });\n }\n\n return errors;\n\n case ConsignmentActionType.DeleteConsignmentFailed:\n if (action.meta) {\n return objectMerge(errors, {\n deleteError: {\n [action.meta.id]: action.payload,\n },\n });\n }\n\n return errors;\n\n case ConsignmentActionType.UpdateShippingOptionRequested:\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n if (action.meta) {\n return objectMerge(errors, {\n updateShippingOptionError: {\n [action.meta.id]: undefined,\n },\n });\n }\n\n return errors;\n\n case ConsignmentActionType.UpdateShippingOptionFailed:\n if (action.meta) {\n return objectMerge(errors, {\n updateShippingOptionError: {\n [action.meta.id]: action.payload,\n },\n });\n }\n\n return errors;\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: ConsignmentStatusesState = DEFAULT_STATE.statuses,\n action: ConsignmentAction | CheckoutAction,\n): ConsignmentStatusesState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case ConsignmentActionType.LoadShippingOptionsRequested:\n return objectSet(statuses, 'isLoadingShippingOptions', true);\n\n case CheckoutActionType.LoadCheckoutSucceeded:\n case CheckoutActionType.LoadCheckoutFailed:\n return objectSet(statuses, 'isLoading', false);\n\n case ConsignmentActionType.LoadShippingOptionsSucceeded:\n case ConsignmentActionType.LoadShippingOptionsFailed:\n return objectSet(statuses, 'isLoadingShippingOptions', false);\n\n case ConsignmentActionType.CreateConsignmentsRequested:\n return objectSet(statuses, 'isCreating', true);\n\n case ConsignmentActionType.CreateConsignmentsSucceeded:\n case ConsignmentActionType.CreateConsignmentsFailed:\n return objectSet(statuses, 'isCreating', false);\n\n case ConsignmentActionType.UpdateConsignmentRequested:\n if (action.meta) {\n return objectMerge(statuses, {\n isUpdating: {\n [action.meta.id]: true,\n },\n });\n }\n\n return statuses;\n\n case ConsignmentActionType.UpdateConsignmentSucceeded:\n case ConsignmentActionType.UpdateConsignmentFailed:\n if (action.meta) {\n return objectMerge(statuses, {\n isUpdating: {\n [action.meta.id]: false,\n },\n });\n }\n\n return statuses;\n\n case ConsignmentActionType.DeleteConsignmentRequested:\n if (action.meta) {\n return objectMerge(statuses, {\n isDeleting: {\n [action.meta.id]: true,\n },\n });\n }\n\n return statuses;\n\n case ConsignmentActionType.DeleteConsignmentSucceeded:\n case ConsignmentActionType.DeleteConsignmentFailed:\n if (action.meta) {\n return objectMerge(statuses, {\n isDeleting: {\n [action.meta.id]: false,\n },\n });\n }\n\n return statuses;\n\n case ConsignmentActionType.UpdateShippingOptionRequested:\n if (action.meta) {\n return objectMerge(statuses, {\n isUpdatingShippingOption: {\n [action.meta.id]: true,\n },\n });\n }\n\n return statuses;\n\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n case ConsignmentActionType.UpdateShippingOptionFailed:\n if (action.meta) {\n return objectMerge(statuses, {\n isUpdatingShippingOption: {\n [action.meta.id]: false,\n },\n });\n }\n\n return statuses;\n\n default:\n return statuses;\n }\n}\n","/**\n * Takes a nested object and flattens it.\n */\nexport default function objectFlatten(\n object: { [key: string]: any },\n parent?: string,\n): { [key: string]: any } {\n const flattened: { [key: string]: any } = {};\n\n Object.keys(object).forEach((key: string) => {\n const value = object[key];\n const keyString = parent ? `${parent}.${key}` : key;\n\n if (typeof value === 'object') {\n Object.assign(flattened, objectFlatten(value, keyString));\n } else {\n flattened[keyString] = value;\n }\n });\n\n return flattened;\n}\n","export default function objectWithSortedKeys(object: { [key: string]: any }) {\n const keys = Object.keys(object);\n const sortedKeys = keys.sort();\n\n const sortedArray = sortedKeys.reduce(\n (previous, current) => ({\n ...previous,\n [current]: object[current],\n }),\n {},\n );\n\n return sortedArray;\n}\n","import { PickupOptionQueryMap } from './pickup-option';\n\nexport default interface PickupOptionState {\n data?: PickupOptionQueryMap;\n errors: PickupOptionErrorsState;\n statuses: PickupOptionStatusesState;\n}\n\nexport interface PickupOptionErrorsState {\n loadError?: Error;\n}\n\nexport interface PickupOptionStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: PickupOptionState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectFlatten, objectSet, objectWithSortedKeys } from '../common/utility';\n\nimport { PickupOptionQueryMap } from './pickup-option';\nimport { LoadPickupOptionsAction, PickupOptionActionType } from './pickup-option-actions';\nimport PickupOptionState, {\n DEFAULT_STATE,\n PickupOptionErrorsState,\n PickupOptionStatusesState,\n} from './pickup-option-state';\n\nexport default function pickupOptionReducer(\n state: PickupOptionState = DEFAULT_STATE,\n action: Action,\n): PickupOptionState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: PickupOptionQueryMap | undefined,\n action: LoadPickupOptionsAction,\n): PickupOptionQueryMap | undefined {\n switch (action.type) {\n case PickupOptionActionType.LoadPickupOptionsSucceeded:\n if (action.meta) {\n const optionQuery = {\n consignmentId: action.meta.consignmentId,\n searchArea: action.meta.searchArea,\n };\n const flattenedMeta = objectFlatten(optionQuery);\n const sortedflattenedMeta = objectWithSortedKeys(flattenedMeta);\n const keyString = btoa(`${JSON.stringify(sortedflattenedMeta)}`);\n\n return objectSet(data, keyString, action.payload);\n }\n\n break;\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(errors: PickupOptionErrorsState = DEFAULT_STATE.errors, action: Action) {\n switch (action.type) {\n case PickupOptionActionType.LoadPickupOptionsRequested:\n case PickupOptionActionType.LoadPickupOptionsSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case PickupOptionActionType.LoadPickupOptionsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: PickupOptionStatusesState = DEFAULT_STATE.statuses,\n action: Action,\n) {\n switch (action.type) {\n case PickupOptionActionType.LoadPickupOptionsRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case PickupOptionActionType.LoadPickupOptionsSucceeded:\n case PickupOptionActionType.LoadPickupOptionsFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","import { Country } from '../geography';\n\nexport default interface ShippingCountryState {\n data?: Country[];\n errors: ShippingCountryErrorsState;\n statuses: ShippingCountryStatusesState;\n}\n\nexport interface ShippingCountryErrorsState {\n loadError?: Error;\n}\n\nexport interface ShippingCountryStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: ShippingCountryState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectSet } from '../common/utility';\nimport { Country } from '../geography';\n\nimport { LoadShippingCountriesAction, ShippingCountryActionType } from './shipping-country-actions';\nimport ShippingCountryState, {\n DEFAULT_STATE,\n ShippingCountryErrorsState,\n ShippingCountryStatusesState,\n} from './shipping-country-state';\n\nexport default function shippingCountryReducer(\n state: ShippingCountryState = DEFAULT_STATE,\n action: Action,\n): ShippingCountryState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: Country[] | undefined,\n action: LoadShippingCountriesAction,\n): Country[] | undefined {\n switch (action.type) {\n case ShippingCountryActionType.LoadShippingCountriesSucceeded:\n return arrayReplace(data, action.payload);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: ShippingCountryErrorsState = DEFAULT_STATE.errors,\n action: LoadShippingCountriesAction,\n): ShippingCountryErrorsState {\n switch (action.type) {\n case ShippingCountryActionType.LoadShippingCountriesRequested:\n case ShippingCountryActionType.LoadShippingCountriesSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case ShippingCountryActionType.LoadShippingCountriesFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: ShippingCountryStatusesState = DEFAULT_STATE.statuses,\n action: LoadShippingCountriesAction,\n): ShippingCountryStatusesState {\n switch (action.type) {\n case ShippingCountryActionType.LoadShippingCountriesRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case ShippingCountryActionType.LoadShippingCountriesSucceeded:\n case ShippingCountryActionType.LoadShippingCountriesFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","export default interface ShippingStrategyState {\n data: ShippingStrategyDataState;\n errors: ShippingStrategyErrorsState;\n statuses: ShippingStrategyStatusesState;\n}\n\nexport interface ShippingStrategyDataState {\n [key: string]: {\n isInitialized: boolean;\n };\n}\n\nexport interface ShippingStrategyErrorsState {\n deinitializeError?: Error;\n deinitializeMethodId?: string;\n initializeError?: Error;\n initializeMethodId?: string;\n updateAddressError?: Error;\n updateAddressMethodId?: string;\n selectOptionError?: Error;\n selectOptionMethodId?: string;\n widgetInteractionError?: Error;\n widgetInteractionMethodId?: string;\n}\n\nexport interface ShippingStrategyStatusesState {\n deinitializeMethodId?: string;\n initializeMethodId?: string;\n isDeinitializing?: boolean;\n isInitializing?: boolean;\n isUpdatingAddress?: boolean;\n isSelectingOption?: boolean;\n updateAddressMethodId?: string;\n selectOptionMethodId?: string;\n isWidgetInteracting?: boolean;\n widgetInteractionMethodId?: string;\n}\n\nexport const DEFAULT_STATE: ShippingStrategyState = {\n data: {},\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge } from '../common/utility';\n\nimport { ShippingStrategyAction, ShippingStrategyActionType } from './shipping-strategy-actions';\nimport ShippingStrategyState, {\n DEFAULT_STATE,\n ShippingStrategyDataState,\n ShippingStrategyErrorsState,\n ShippingStrategyStatusesState,\n} from './shipping-strategy-state';\n\nexport default function shippingStrategyReducer(\n state: ShippingStrategyState = DEFAULT_STATE,\n action: Action,\n): ShippingStrategyState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: ShippingStrategyDataState = DEFAULT_STATE.data,\n action: ShippingStrategyAction,\n): ShippingStrategyDataState {\n switch (action.type) {\n case ShippingStrategyActionType.InitializeSucceeded:\n return objectMerge(data, {\n [action.meta && action.meta.methodId]: {\n isInitialized: true,\n },\n });\n\n case ShippingStrategyActionType.DeinitializeSucceeded:\n return objectMerge(data, {\n [action.meta && action.meta.methodId]: {\n isInitialized: false,\n },\n });\n }\n\n return data;\n}\n\nfunction errorsReducer(\n errors: ShippingStrategyErrorsState = DEFAULT_STATE.errors,\n action: ShippingStrategyAction,\n): ShippingStrategyErrorsState {\n switch (action.type) {\n case ShippingStrategyActionType.InitializeRequested:\n case ShippingStrategyActionType.InitializeSucceeded:\n return objectMerge(errors, {\n initializeError: undefined,\n initializeMethodId: undefined,\n });\n\n case ShippingStrategyActionType.InitializeFailed:\n return objectMerge(errors, {\n initializeError: action.payload,\n initializeMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.DeinitializeRequested:\n case ShippingStrategyActionType.DeinitializeSucceeded:\n return objectMerge(errors, {\n deinitializeError: undefined,\n deinitializeMethodId: undefined,\n });\n\n case ShippingStrategyActionType.DeinitializeFailed:\n return objectMerge(errors, {\n deinitializeError: action.payload,\n deinitializeMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.UpdateAddressRequested:\n case ShippingStrategyActionType.UpdateAddressSucceeded:\n return objectMerge(errors, {\n updateAddressError: undefined,\n updateAddressMethodId: undefined,\n });\n\n case ShippingStrategyActionType.UpdateAddressFailed:\n return objectMerge(errors, {\n updateAddressError: action.payload,\n updateAddressMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.SelectOptionRequested:\n case ShippingStrategyActionType.SelectOptionSucceeded:\n return objectMerge(errors, {\n selectOptionError: undefined,\n selectOptionMethodId: undefined,\n });\n\n case ShippingStrategyActionType.SelectOptionFailed:\n return objectMerge(errors, {\n selectOptionError: action.payload,\n selectOptionMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.WidgetInteractionStarted:\n case ShippingStrategyActionType.WidgetInteractionFinished:\n return objectMerge(errors, {\n widgetInteractionError: undefined,\n widgetInteractionMethodId: undefined,\n });\n\n case ShippingStrategyActionType.WidgetInteractionFailed:\n return objectMerge(errors, {\n widgetInteractionError: action.payload,\n widgetInteractionMethodId: action.meta && action.meta.methodId,\n });\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: ShippingStrategyStatusesState = DEFAULT_STATE.statuses,\n action: ShippingStrategyAction,\n): ShippingStrategyStatusesState {\n switch (action.type) {\n case ShippingStrategyActionType.InitializeRequested:\n return objectMerge(statuses, {\n isInitializing: true,\n initializeMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.InitializeFailed:\n case ShippingStrategyActionType.InitializeSucceeded:\n return objectMerge(statuses, {\n isInitializing: false,\n initializeMethodId: undefined,\n });\n\n case ShippingStrategyActionType.DeinitializeRequested:\n return objectMerge(statuses, {\n isDeinitializing: true,\n deinitializeMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.DeinitializeFailed:\n case ShippingStrategyActionType.DeinitializeSucceeded:\n return objectMerge(statuses, {\n isDeinitializing: false,\n deinitializeMethodId: undefined,\n });\n\n case ShippingStrategyActionType.UpdateAddressRequested:\n return objectMerge(statuses, {\n isUpdatingAddress: true,\n updateAddressMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.UpdateAddressFailed:\n case ShippingStrategyActionType.UpdateAddressSucceeded:\n return objectMerge(statuses, {\n isUpdatingAddress: false,\n updateAddressMethodId: undefined,\n });\n\n case ShippingStrategyActionType.SelectOptionRequested:\n return objectMerge(statuses, {\n isSelectingOption: true,\n selectOptionMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.SelectOptionFailed:\n case ShippingStrategyActionType.SelectOptionSucceeded:\n return objectMerge(statuses, {\n isSelectingOption: false,\n selectOptionMethodId: undefined,\n });\n\n case ShippingStrategyActionType.WidgetInteractionStarted:\n return objectMerge(statuses, {\n isWidgetInteracting: true,\n widgetInteractionMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.WidgetInteractionFinished:\n case ShippingStrategyActionType.WidgetInteractionFailed:\n return objectMerge(statuses, {\n isWidgetInteracting: false,\n widgetInteractionMethodId: undefined,\n });\n\n default:\n return statuses;\n }\n}\n","import { SignInEmail } from './signin-email';\n\nexport default interface SignInEmailState {\n data?: SignInEmail;\n errors: SignInEmailErrorsState;\n statuses: SignInEmailStatusesState;\n}\n\nexport interface SignInEmailErrorsState {\n sendError?: Error;\n}\n\nexport interface SignInEmailStatusesState {\n isSending?: boolean;\n}\n\nexport const DEFAULT_STATE: SignInEmailState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport { SignInEmail } from './signin-email';\nimport { SendSignInEmailAction, SignInEmailActionType } from './signin-email-actions';\nimport SignInEmailState, {\n DEFAULT_STATE,\n SignInEmailErrorsState,\n SignInEmailStatusesState,\n} from './signin-email-state';\n\nexport default function signInEmailReducer(\n state: SignInEmailState = DEFAULT_STATE,\n action: Action,\n): SignInEmailState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: SignInEmail | undefined,\n action: SendSignInEmailAction,\n): SignInEmail | undefined {\n switch (action.type) {\n case SignInEmailActionType.SendSignInEmailSucceeded:\n return objectMerge(data, action.payload);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: SignInEmailErrorsState = DEFAULT_STATE.errors,\n action: SendSignInEmailAction,\n): SignInEmailErrorsState {\n switch (action.type) {\n case SignInEmailActionType.SendSignInEmailRequested:\n case SignInEmailActionType.SendSignInEmailSucceeded:\n return objectSet(errors, 'sendError', undefined);\n\n case SignInEmailActionType.SendSignInEmailFailed:\n return objectSet(errors, 'sendError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: SignInEmailStatusesState = DEFAULT_STATE.statuses,\n action: SendSignInEmailAction,\n): SignInEmailStatusesState {\n switch (action.type) {\n case SignInEmailActionType.SendSignInEmailRequested:\n return objectSet(statuses, 'isSending', true);\n\n case SignInEmailActionType.SendSignInEmailFailed:\n case SignInEmailActionType.SendSignInEmailSucceeded:\n return objectSet(statuses, 'isSending', false);\n\n default:\n return statuses;\n }\n}\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectSet } from '../common/utility';\n\nimport { StoreCreditAction, StoreCreditActionType } from './store-credit-actions';\nimport StoreCreditState, {\n StoreCreditErrorsState,\n StoreCreditStatusesState,\n} from './store-credit-state';\n\nconst DEFAULT_STATE: StoreCreditState = {\n errors: {},\n statuses: {},\n};\n\nexport default function storeCreditReducer(\n state: StoreCreditState = DEFAULT_STATE,\n action: Action,\n): StoreCreditState {\n const reducer = combineReducers({\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction errorsReducer(\n errors: StoreCreditErrorsState = DEFAULT_STATE.errors,\n action: StoreCreditAction,\n): StoreCreditErrorsState {\n switch (action.type) {\n case StoreCreditActionType.ApplyStoreCreditRequested:\n case StoreCreditActionType.ApplyStoreCreditSucceeded:\n return objectSet(errors, 'applyError', undefined);\n\n case StoreCreditActionType.ApplyStoreCreditFailed:\n return objectSet(errors, 'applyError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: StoreCreditStatusesState = DEFAULT_STATE.statuses,\n action: StoreCreditAction,\n): StoreCreditStatusesState {\n switch (action.type) {\n case StoreCreditActionType.ApplyStoreCreditRequested:\n return objectSet(statuses, 'isApplying', true);\n\n case StoreCreditActionType.ApplyStoreCreditSucceeded:\n case StoreCreditActionType.ApplyStoreCreditFailed:\n return objectSet(statuses, 'isApplying', false);\n\n default:\n return statuses;\n }\n}\n","export default interface SubscriptionsState {\n errors: SubscriptionsErrorsState;\n statuses: SubscriptionsStatusesState;\n}\n\nexport interface SubscriptionsErrorsState {\n updateError?: Error;\n}\n\nexport interface SubscriptionsStatusesState {\n isUpdating?: boolean;\n}\n\nexport const DEFAULT_STATE: SubscriptionsState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectSet } from '../common/utility';\nimport { SubscriptionsActionType, UpdateSubscriptionsAction } from '../subscription';\n\nimport SubscriptionsState, {\n DEFAULT_STATE,\n SubscriptionsErrorsState,\n SubscriptionsStatusesState,\n} from './subscriptions-state';\n\nexport default function subscriptionsReducer(\n state: SubscriptionsState = DEFAULT_STATE,\n action: Action,\n): SubscriptionsState {\n const reducer = combineReducers({\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction errorsReducer(\n errors: SubscriptionsErrorsState = DEFAULT_STATE.errors,\n action: UpdateSubscriptionsAction,\n): SubscriptionsErrorsState {\n switch (action.type) {\n case SubscriptionsActionType.UpdateSubscriptionsRequested:\n case SubscriptionsActionType.UpdateSubscriptionsSucceeded:\n return objectSet(errors, 'updateError', undefined);\n\n case SubscriptionsActionType.UpdateSubscriptionsFailed:\n return objectSet(errors, 'updateError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: SubscriptionsStatusesState = DEFAULT_STATE.statuses,\n action: UpdateSubscriptionsAction,\n): SubscriptionsStatusesState {\n switch (action.type) {\n case SubscriptionsActionType.UpdateSubscriptionsRequested:\n return objectSet(statuses, 'isUpdating', true);\n\n case SubscriptionsActionType.UpdateSubscriptionsFailed:\n case SubscriptionsActionType.UpdateSubscriptionsSucceeded:\n return objectSet(statuses, 'isUpdating', false);\n\n default:\n return statuses;\n }\n}\n","import { Omit } from '../common/types';\n\nimport Checkout from './checkout';\n\nexport default interface CheckoutState {\n data?: CheckoutDataState;\n errors: CheckoutErrorsState;\n statuses: CheckoutStatusesState;\n}\n\nexport type CheckoutDataState = Omit<\n Checkout,\n 'billingAddress' | 'cart' | 'consignments' | 'coupons' | 'giftCertificates'\n>;\n\nexport interface CheckoutErrorsState {\n loadError?: Error;\n updateError?: Error;\n}\n\nexport interface CheckoutStatusesState {\n isExecutingSpamCheck?: boolean;\n isLoading?: boolean;\n isUpdating?: boolean;\n}\n\nexport const DEFAULT_STATE: CheckoutState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\nimport { omit } from 'lodash';\n\nimport { BillingAddressAction, BillingAddressActionType } from '../billing';\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\nimport {\n CouponAction,\n CouponActionType,\n GiftCertificateAction,\n GiftCertificateActionType,\n} from '../coupon';\nimport { OrderAction, OrderActionType } from '../order';\nimport { ConsignmentAction, ConsignmentActionType } from '../shipping';\nimport { SpamProtectionAction, SpamProtectionActionType } from '../spam-protection';\nimport { StoreCreditAction, StoreCreditActionType } from '../store-credit';\n\nimport { CheckoutAction, CheckoutActionType } from './checkout-actions';\nimport CheckoutState, {\n CheckoutDataState,\n CheckoutErrorsState,\n CheckoutStatusesState,\n DEFAULT_STATE,\n} from './checkout-state';\n\nexport default function checkoutReducer(\n state: CheckoutState = DEFAULT_STATE,\n action: Action,\n): CheckoutState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: CheckoutDataState | undefined,\n action:\n | CheckoutAction\n | BillingAddressAction\n | ConsignmentAction\n | CouponAction\n | GiftCertificateAction\n | OrderAction\n | SpamProtectionAction\n | StoreCreditAction,\n): CheckoutDataState | undefined {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutSucceeded:\n case CheckoutActionType.UpdateCheckoutSucceeded:\n case StoreCreditActionType.ApplyStoreCreditSucceeded:\n case BillingAddressActionType.UpdateBillingAddressSucceeded:\n case CouponActionType.ApplyCouponSucceeded:\n case CouponActionType.RemoveCouponSucceeded:\n case ConsignmentActionType.CreateConsignmentsSucceeded:\n case ConsignmentActionType.UpdateConsignmentSucceeded:\n case ConsignmentActionType.DeleteConsignmentSucceeded:\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n case ConsignmentActionType.LoadShippingOptionsSucceeded:\n case GiftCertificateActionType.ApplyGiftCertificateSucceeded:\n case GiftCertificateActionType.RemoveGiftCertificateSucceeded:\n case SpamProtectionActionType.VerifyCheckoutSucceeded:\n return objectMerge(\n data,\n omit(action.payload, [\n 'billingAddress',\n 'cart',\n 'consignments',\n 'customer',\n 'coupons',\n 'giftCertificates',\n ]),\n ) as CheckoutDataState;\n\n case OrderActionType.SubmitOrderSucceeded:\n return objectSet(data, 'orderId', action.payload && action.payload.order.orderId);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: CheckoutErrorsState = DEFAULT_STATE.errors,\n action: CheckoutAction | OrderAction,\n): CheckoutErrorsState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case CheckoutActionType.LoadCheckoutFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n case CheckoutActionType.UpdateCheckoutRequested:\n case CheckoutActionType.UpdateCheckoutSucceeded:\n return objectSet(errors, 'updateError', undefined);\n\n case CheckoutActionType.UpdateCheckoutFailed:\n return objectSet(errors, 'updateError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: CheckoutStatusesState = DEFAULT_STATE.statuses,\n action: CheckoutAction | OrderAction | SpamProtectionAction,\n): CheckoutStatusesState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case CheckoutActionType.LoadCheckoutFailed:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return objectSet(statuses, 'isLoading', false);\n\n case CheckoutActionType.UpdateCheckoutRequested:\n return objectSet(statuses, 'isUpdating', true);\n\n case CheckoutActionType.UpdateCheckoutFailed:\n case CheckoutActionType.UpdateCheckoutSucceeded:\n return objectSet(statuses, 'isUpdating', false);\n\n case SpamProtectionActionType.ExecuteRequested:\n return objectSet(statuses, 'isExecutingSpamCheck', true);\n\n case SpamProtectionActionType.ExecuteFailed:\n case SpamProtectionActionType.ExecuteSucceeded:\n return objectSet(statuses, 'isExecutingSpamCheck', false);\n\n default:\n return statuses;\n }\n}\n","import { deepFreeze } from '@bigcommerce/data-store';\n\n// tslint:disable-next-line:ban-types\ntype FunctionProperties = { [K in keyof T]: T[K] extends Function ? T[K] : never };\n\nexport default function createFreezeProxy(target: T): T {\n return createProxy(\n target,\n (target, name) =>\n (...args: any[]) =>\n deepFreeze(target[name].call(target, ...args)),\n );\n}\n\nexport function createFreezeProxies(\n map: TMap,\n): TMap {\n return Object.keys(map).reduce((result, key) => {\n result[key] = createFreezeProxy(map[key]);\n\n return result;\n }, {} as { [key: string]: T }) as TMap;\n}\n\nfunction createProxy(\n target: T,\n trap: (target: FunctionProperties, name: keyof FunctionProperties, proxy: T) => any,\n): T {\n const proxy = Object.create(target);\n\n traversePrototypeOf(target, (prototype) => {\n Object.getOwnPropertyNames(prototype).forEach((name) => {\n if (\n name === 'constructor' ||\n typeof proxy[name] !== 'function' ||\n name.charAt(0) === '_'\n ) {\n return;\n }\n\n proxy[name] = trap(target as FunctionProperties, name as keyof T, proxy);\n });\n });\n\n return proxy;\n}\n\nfunction traversePrototypeOf(target: object, iteratee: (prototype: object) => void): void {\n let prototype = Object.getPrototypeOf(target);\n\n while (prototype) {\n iteratee(prototype);\n\n prototype = Object.getPrototypeOf(prototype);\n }\n}\n","import PaymentInstrument from './instrument';\n\ninterface SupportedInstruments {\n [key: string]: Pick;\n}\n\nconst supportedInstruments: SupportedInstruments = {\n 'mollie.credit_card': {\n provider: 'mollie',\n method: 'credit_card',\n },\n 'adyenv2.scheme': {\n provider: 'adyenv2',\n method: 'scheme',\n },\n 'adyenv3.scheme': {\n provider: 'adyenv3',\n method: 'scheme',\n },\n 'adyenv2.bcmc': {\n provider: 'adyenv2',\n method: 'bcmc',\n },\n 'adyenv2.ideal': {\n provider: 'adyenv2',\n method: 'ideal',\n },\n 'adyenv2.sepadirectdebit': {\n provider: 'adyenv2',\n method: 'sepadirectdebit',\n },\n 'adyenv2.directEbanking': {\n provider: 'adyenv2',\n method: 'directEbanking',\n },\n 'adyenv2.giropay': {\n provider: 'adyenv2',\n method: 'giropay',\n },\n barclays: {\n provider: 'barclays',\n method: 'credit_card',\n },\n braintree: {\n provider: 'braintree',\n method: 'credit_card',\n },\n braintreepaypal: {\n provider: 'braintree',\n method: 'paypal',\n },\n braintreeach: {\n provider: 'braintree',\n method: 'ach',\n },\n authorizenet: {\n provider: 'authorizenet',\n method: 'credit_card',\n },\n elavon: {\n provider: 'elavon',\n method: 'credit_card',\n },\n checkoutcom: {\n provider: 'checkoutcom',\n method: 'credit_card',\n },\n 'checkoutcom.credit_card': {\n provider: 'checkoutcom',\n method: 'credit_card',\n },\n 'checkoutcom.card': {\n provider: 'checkoutcom',\n method: 'card',\n },\n sagepay: {\n provider: 'sagepay',\n method: 'credit_card',\n },\n stripe: {\n provider: 'stripe',\n method: 'credit_card',\n },\n 'stripev3.card': {\n provider: 'stripev3',\n method: 'card',\n },\n 'stripeupe.card': {\n provider: 'stripeupe',\n method: 'card',\n },\n cybersource: {\n provider: 'cybersource',\n method: 'credit_card',\n },\n cybersourcev2: {\n provider: 'cybersourcev2',\n method: 'credit_card',\n },\n bnz: {\n provider: 'bnz',\n method: 'credit_card',\n },\n converge: {\n provider: 'converge',\n method: 'credit_card',\n },\n bluesnapv2: {\n provider: 'bluesnapv2',\n method: 'credit_card',\n },\n 'bluesnapdirect.credit_card': {\n provider: 'bluesnapdirect',\n method: 'credit_card',\n },\n orbital: {\n provider: 'orbital',\n method: 'credit_card',\n },\n paymetric: {\n provider: 'paymetric',\n method: 'credit_card',\n },\n bolt: {\n provider: 'bolt',\n method: 'credit_card',\n },\n 'barclaycard.credit_card': {\n provider: 'barclaycard',\n method: 'credit_card',\n },\n digitalriver: {\n provider: 'digitalriver',\n method: 'credit_card',\n },\n moneris: {\n provider: 'moneris',\n method: 'credit_card',\n },\n cba_mpgs: {\n provider: 'cba_mpgs',\n method: 'credit_card',\n },\n worldpayaccess: {\n provider: 'worldpayaccess',\n method: 'credit_card',\n },\n};\n\nexport default supportedInstruments;\n","import { identity, isEqual, pickBy } from 'lodash';\n\nimport Address from './address';\n\nexport default function isAddressEqual(\n addressA: Partial
,\n addressB: Partial
,\n): boolean {\n return isEqual(normalize(addressA), normalize(addressB));\n}\n\nfunction normalize(address: Partial
): Partial
{\n return pickBy(\n {\n firstName: address.firstName,\n lastName: address.lastName,\n company: address.company,\n address1: address.address1,\n address2: address.address2,\n city: address.city,\n stateOrProvince: address.stateOrProvince,\n countryCode: address.countryCode,\n postalCode: address.postalCode,\n phone: address.phone,\n customFields: address.customFields,\n },\n identity,\n );\n}\n","import { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RequestError } from '../common/error/errors';\n\nexport default interface StoreCreditState {\n errors: StoreCreditErrorsState;\n statuses: StoreCreditStatusesState;\n}\n\nexport interface StoreCreditErrorsState {\n applyError?: RequestError;\n}\n\nexport interface StoreCreditStatusesState {\n isApplying?: boolean;\n}\n\nexport const DEFAULT_STATE: StoreCreditState = {\n errors: {},\n statuses: {},\n};\n","import { createBillingAddressSelectorFactory } from '../billing';\nimport { createCartSelectorFactory } from '../cart';\nimport { createCheckoutButtonSelectorFactory } from '../checkout-buttons';\nimport { createFreezeProxies } from '../common/utility';\nimport { createConfigSelectorFactory } from '../config';\nimport { createCouponSelectorFactory, createGiftCertificateSelectorFactory } from '../coupon';\nimport { createCustomerSelectorFactory, createCustomerStrategySelectorFactory } from '../customer';\nimport { createExtensionSelectorFactory } from '../extension';\nimport { createFormSelectorFactory } from '../form';\nimport { createCountrySelectorFactory } from '../geography';\nimport { createOrderSelectorFactory } from '../order';\nimport { createOrderBillingAddressSelectorFactory } from '../order-billing-address';\nimport {\n createPaymentMethodSelectorFactory,\n createPaymentSelectorFactory,\n createPaymentStrategySelectorFactory,\n} from '../payment';\nimport { createInstrumentSelectorFactory } from '../payment/instrument';\nimport { createRemoteCheckoutSelectorFactory } from '../remote-checkout';\nimport {\n createConsignmentSelectorFactory,\n createPickupOptionSelectorFactory,\n createShippingAddressSelectorFactory,\n createShippingCountrySelectorFactory,\n createShippingStrategySelectorFactory,\n} from '../shipping';\nimport { createSignInEmailSelectorFactory } from '../signin-email';\nimport { createStoreCreditSelectorFactory } from '../store-credit';\nimport { createSubscriptionsSelectorFactory } from '../subscription';\n\nimport { createCheckoutSelectorFactory } from './checkout-selector';\nimport { CheckoutStoreOptions } from './checkout-store';\nimport CheckoutStoreState from './checkout-store-state';\nimport InternalCheckoutSelectors from './internal-checkout-selectors';\n\nexport type InternalCheckoutSelectorsFactory = (\n state: CheckoutStoreState,\n options?: CheckoutStoreOptions,\n) => InternalCheckoutSelectors;\n\nexport function createInternalCheckoutSelectorsFactory(): InternalCheckoutSelectorsFactory {\n const createBillingAddressSelector = createBillingAddressSelectorFactory();\n const createCartSelector = createCartSelectorFactory();\n const createCheckoutButtonSelector = createCheckoutButtonSelectorFactory();\n const createConfigSelector = createConfigSelectorFactory();\n const createCountrySelector = createCountrySelectorFactory();\n const createCouponSelector = createCouponSelectorFactory();\n const createCustomerSelector = createCustomerSelectorFactory();\n const createCustomerStrategySelector = createCustomerStrategySelectorFactory();\n const createGiftCertificateSelector = createGiftCertificateSelectorFactory();\n const createInstrumentSelector = createInstrumentSelectorFactory();\n const createFormSelector = createFormSelectorFactory();\n const createPaymentMethodSelector = createPaymentMethodSelectorFactory();\n const createPaymentStrategySelector = createPaymentStrategySelectorFactory();\n const createPickupOptionSelector = createPickupOptionSelectorFactory();\n const createRemoteCheckoutSelector = createRemoteCheckoutSelectorFactory();\n const createShippingAddressSelector = createShippingAddressSelectorFactory();\n const createShippingCountrySelector = createShippingCountrySelectorFactory();\n const createShippingStrategySelector = createShippingStrategySelectorFactory();\n const createConsignmentSelector = createConsignmentSelectorFactory();\n const createCheckoutSelector = createCheckoutSelectorFactory();\n const createOrderSelector = createOrderSelectorFactory();\n const createOrderBillingAddressSelector = createOrderBillingAddressSelectorFactory();\n const createPaymentSelector = createPaymentSelectorFactory();\n const createStoreCreditSelector = createStoreCreditSelectorFactory();\n const createSubscriptionsSelector = createSubscriptionsSelectorFactory();\n const createSignInEmailSelector = createSignInEmailSelectorFactory();\n const createExtensionSelector = createExtensionSelectorFactory();\n\n return (state, options = {}) => {\n const billingAddress = createBillingAddressSelector(state.billingAddress);\n const cart = createCartSelector(state.cart);\n const checkoutButton = createCheckoutButtonSelector(state.checkoutButton);\n const countries = createCountrySelector(state.countries);\n const coupons = createCouponSelector(state.coupons);\n const customer = createCustomerSelector(state.customer);\n const customerStrategies = createCustomerStrategySelector(state.customerStrategies);\n const extensions = createExtensionSelector(state.extensions);\n const form = createFormSelector(state.formFields);\n const giftCertificates = createGiftCertificateSelector(state.giftCertificates);\n const instruments = createInstrumentSelector(state.instruments);\n const orderBillingAddress = createOrderBillingAddressSelector(state.orderBillingAddress);\n const paymentMethods = createPaymentMethodSelector(state.paymentMethods);\n const paymentStrategies = createPaymentStrategySelector(state.paymentStrategies);\n const pickupOptions = createPickupOptionSelector(state.pickupOptions);\n const remoteCheckout = createRemoteCheckoutSelector(state.remoteCheckout);\n const shippingAddress = createShippingAddressSelector(state.consignments);\n const shippingCountries = createShippingCountrySelector(state.shippingCountries);\n const shippingStrategies = createShippingStrategySelector(state.shippingStrategies);\n const subscriptions = createSubscriptionsSelector(state.subscriptions);\n const storeCredit = createStoreCreditSelector(state.storeCredit);\n const signInEmail = createSignInEmailSelector(state.signInEmail);\n\n // Compose selectors\n const consignments = createConsignmentSelector(state.consignments, cart);\n const checkout = createCheckoutSelector(\n state.checkout,\n billingAddress,\n cart,\n consignments,\n coupons,\n customer,\n giftCertificates,\n );\n const order = createOrderSelector(state.order, orderBillingAddress, coupons);\n const payment = createPaymentSelector(checkout, order);\n const config = createConfigSelector(state.config, state.formFields);\n\n const selectors = {\n billingAddress,\n cart,\n checkout,\n checkoutButton,\n config,\n consignments,\n countries,\n coupons,\n customer,\n customerStrategies,\n extensions,\n form,\n giftCertificates,\n instruments,\n order,\n orderBillingAddress,\n payment,\n paymentMethods,\n paymentStrategies,\n pickupOptions,\n remoteCheckout,\n shippingAddress,\n shippingCountries,\n shippingStrategies,\n signInEmail,\n subscriptions,\n storeCredit,\n };\n\n return options.shouldWarnMutation ? createFreezeProxies(selectors) : selectors;\n };\n}\n\nexport default function createInternalCheckoutSelectors(\n state: CheckoutStoreState,\n options?: CheckoutStoreOptions,\n): InternalCheckoutSelectors {\n return createInternalCheckoutSelectorsFactory()(state, options);\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport BillingAddress from './billing-address';\nimport BillingAddressState, { DEFAULT_STATE } from './billing-address-state';\n\nexport default interface BillingAddressSelector {\n getBillingAddress(): BillingAddress | undefined;\n getBillingAddressOrThrow(): BillingAddress;\n getUpdateError(): Error | undefined;\n getContinueAsGuestError(): Error | undefined;\n getLoadError(): Error | undefined;\n isUpdating(): boolean;\n isContinuingAsGuest(): boolean;\n isLoading(): boolean;\n}\n\nexport type BillingAddressSelectorFactory = (state: BillingAddressState) => BillingAddressSelector;\n\nexport function createBillingAddressSelectorFactory(): BillingAddressSelectorFactory {\n const getBillingAddress = createSelector(\n (state: BillingAddressState) => state.data,\n (data) => () => data,\n );\n\n const getBillingAddressOrThrow = createSelector(\n getBillingAddress,\n (getBillingAddress) => () => {\n return guard(\n getBillingAddress(),\n () => new MissingDataError(MissingDataErrorType.MissingBillingAddress),\n );\n },\n );\n\n const getUpdateError = createSelector(\n (state: BillingAddressState) => state.errors.updateError,\n (error) => () => error,\n );\n\n const getContinueAsGuestError = createSelector(\n (state: BillingAddressState) => state.errors.continueAsGuestError,\n (error) => () => error,\n );\n\n const getLoadError = createSelector(\n (state: BillingAddressState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isUpdating = createSelector(\n (state: BillingAddressState) => !!state.statuses.isUpdating,\n (status) => () => status,\n );\n\n const isContinuingAsGuest = createSelector(\n (state: BillingAddressState) => !!state.statuses.isContinuingAsGuest,\n (status) => () => status,\n );\n\n const isLoading = createSelector(\n (state: BillingAddressState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne((state: BillingAddressState = DEFAULT_STATE): BillingAddressSelector => {\n return {\n getBillingAddress: getBillingAddress(state),\n getBillingAddressOrThrow: getBillingAddressOrThrow(state),\n getUpdateError: getUpdateError(state),\n getContinueAsGuestError: getContinueAsGuestError(state),\n getLoadError: getLoadError(state),\n isUpdating: isUpdating(state),\n isContinuingAsGuest: isContinuingAsGuest(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { memoize, memoizeOne } from '@bigcommerce/memoize';\nimport { find, some, values } from 'lodash';\n\nimport { createSelector } from '../common/selector';\n\nimport CheckoutButtonState, { DEFAULT_STATE } from './checkout-button-state';\nimport { CheckoutButtonMethodType } from './strategies';\n\nexport default interface CheckoutButtonSelector {\n getState(): CheckoutButtonState;\n isInitializing(methodId?: CheckoutButtonMethodType): boolean;\n isInitialized(methodId: CheckoutButtonMethodType, containerId?: string): boolean;\n isDeinitializing(methodId?: CheckoutButtonMethodType): boolean;\n getInitializeError(methodId?: CheckoutButtonMethodType): Error | undefined;\n getDeinitializeError(methodId?: CheckoutButtonMethodType): Error | undefined;\n}\n\nexport type CheckoutButtonSelectorFactory = (state: CheckoutButtonState) => CheckoutButtonSelector;\n\nexport function createCheckoutButtonSelectorFactory(): CheckoutButtonSelectorFactory {\n const getState = createSelector(\n (state: CheckoutButtonState) => state,\n (state) => () => state,\n );\n\n const isInitializing = createSelector(\n (state: CheckoutButtonState) => state.statuses,\n (statuses) =>\n memoize((methodId?: CheckoutButtonMethodType) => {\n if (methodId) {\n const method = statuses[methodId];\n\n return (method && method.isInitializing) === true;\n }\n\n return some(statuses, { isInitializing: true });\n }),\n );\n\n const isInitialized = createSelector(\n (state: CheckoutButtonState) => state.data,\n (data) =>\n memoize((methodId: CheckoutButtonMethodType, containerId?: string) => {\n const method = data[methodId];\n\n if (!method) {\n return false;\n }\n\n if (!containerId) {\n return some(\n method.initializedContainers,\n (isInitialized) => isInitialized === true,\n );\n }\n\n return method.initializedContainers[containerId] === true;\n }),\n );\n\n const isDeinitializing = createSelector(\n (state: CheckoutButtonState) => state.statuses,\n (statuses) =>\n memoize((methodId?: CheckoutButtonMethodType) => {\n if (methodId) {\n const method = statuses[methodId];\n\n return (method && method.isDeinitializing) === true;\n }\n\n return some(statuses, { isDeinitializing: true });\n }),\n );\n\n const getInitializeError = createSelector(\n (state: CheckoutButtonState) => state.errors,\n (errors) =>\n memoize((methodId?: CheckoutButtonMethodType) => {\n const method = methodId\n ? errors[methodId]\n : find(values(errors), (method) => !!(method && method.initializeError));\n\n return method && method.initializeError;\n }),\n );\n\n const getDeinitializeError = createSelector(\n (state: CheckoutButtonState) => state.errors,\n (errors) =>\n memoize((methodId?: CheckoutButtonMethodType) => {\n const method = methodId\n ? errors[methodId]\n : find(values(errors), (method) => !!(method && method.deinitializeError));\n\n return method && method.deinitializeError;\n }),\n );\n\n return memoizeOne((state: CheckoutButtonState = DEFAULT_STATE): CheckoutButtonSelector => {\n return {\n getState: getState(state),\n isInitializing: isInitializing(state),\n isInitialized: isInitialized(state),\n isDeinitializing: isDeinitializing(state),\n getInitializeError: getInitializeError(state),\n getDeinitializeError: getDeinitializeError(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { RequestError } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\n\nimport Coupon from './coupon';\nimport CouponState, { DEFAULT_STATE } from './coupon-state';\n\nexport default interface CouponSelector {\n getCoupons(): Coupon[] | undefined;\n getRemoveError(): RequestError | undefined;\n getApplyError(): RequestError | undefined;\n isApplying(): boolean;\n isRemoving(): boolean;\n}\n\nexport type CouponSelectorFactory = (state: CouponState) => CouponSelector;\n\nexport function createCouponSelectorFactory(): CouponSelectorFactory {\n const getCoupons = createSelector(\n (state: CouponState) => state.data,\n (data) => () => data,\n );\n\n const getRemoveError = createSelector(\n (state: CouponState) => state.errors.removeCouponError,\n (error) => () => error,\n );\n\n const getApplyError = createSelector(\n (state: CouponState) => state.errors.applyCouponError,\n (error) => () => error,\n );\n\n const isApplying = createSelector(\n (state: CouponState) => !!state.statuses.isApplyingCoupon,\n (status) => () => status,\n );\n\n const isRemoving = createSelector(\n (state: CouponState) => !!state.statuses.isRemovingCoupon,\n (status) => () => status,\n );\n\n return memoizeOne((state: CouponState = DEFAULT_STATE): CouponSelector => {\n return {\n getCoupons: getCoupons(state),\n getRemoveError: getRemoveError(state),\n getApplyError: getApplyError(state),\n isApplying: isApplying(state),\n isRemoving: isRemoving(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport Customer from './customer';\nimport CustomerState, { DEFAULT_STATE } from './customer-state';\n\nexport default interface CustomerSelector {\n getCustomer(): Customer | undefined;\n getCustomerOrThrow(): Customer;\n getCreateAccountError(): Error | undefined;\n isCreatingCustomerAccount(): boolean;\n getCreateAddressError(): Error | undefined;\n isCreatingCustomerAddress(): boolean;\n}\n\nexport type CustomerSelectorFactory = (state: CustomerState) => CustomerSelector;\n\nexport function createCustomerSelectorFactory(): CustomerSelectorFactory {\n const getCustomer = createSelector(\n (state: CustomerState) => state.data,\n (customer) => () => customer,\n );\n\n const getCustomerOrThrow = createSelector(getCustomer, (getCustomer) => () => {\n return guard(\n getCustomer(),\n () => new MissingDataError(MissingDataErrorType.MissingCustomer),\n );\n });\n\n const getCreateAccountError = createSelector(\n (state: CustomerState) => state.errors.createError,\n (error) => () => error,\n );\n\n const isCreatingCustomerAccount = createSelector(\n (state: CustomerState) => !!state.statuses.isCreating,\n (status) => () => status,\n );\n\n const getCreateAddressError = createSelector(\n (state: CustomerState) => state.errors.createAddressError,\n (error) => () => error,\n );\n\n const isCreatingCustomerAddress = createSelector(\n (state: CustomerState) => !!state.statuses.isCreatingAddress,\n (status) => () => status,\n );\n\n return memoizeOne((state: CustomerState = DEFAULT_STATE): CustomerSelector => {\n return {\n getCustomer: getCustomer(state),\n getCustomerOrThrow: getCustomerOrThrow(state),\n getCreateAccountError: getCreateAccountError(state),\n isCreatingCustomerAccount: isCreatingCustomerAccount(state),\n getCreateAddressError: getCreateAddressError(state),\n isCreatingCustomerAddress: isCreatingCustomerAddress(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport RemoteCheckoutState, {\n DEFAULT_STATE,\n RemoteCheckoutStateData,\n} from './remote-checkout-state';\n\nexport default interface RemoteCheckoutSelector {\n getCheckout(\n methodId: TMethodId,\n ): RemoteCheckoutStateData[TMethodId] | undefined;\n}\n\nexport type RemoteCheckoutSelectorFactory = (state: RemoteCheckoutState) => RemoteCheckoutSelector;\n\nexport function createRemoteCheckoutSelectorFactory(): RemoteCheckoutSelectorFactory {\n const getCheckout = createSelector(\n (state: RemoteCheckoutState) => state.data,\n (data) =>\n (methodId: TMethodId) => {\n return data[methodId];\n },\n );\n\n return memoizeOne((state: RemoteCheckoutState = DEFAULT_STATE): RemoteCheckoutSelector => {\n return {\n getCheckout: getCheckout(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { Address } from '../address';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport ConsignmentState, { DEFAULT_STATE } from './consignment-state';\n\nexport default interface ShippingAddressSelector {\n getShippingAddress(): Address | undefined;\n getShippingAddressOrThrow(): Address;\n getShippingAddresses(): Address[];\n getShippingAddressesOrThrow(): Address[];\n}\n\nexport type ShippingAddressSelectorFactory = (state: ConsignmentState) => ShippingAddressSelector;\n\nexport function createShippingAddressSelectorFactory(): ShippingAddressSelectorFactory {\n const getShippingAddress = createSelector(\n (state: ConsignmentState) => state.data,\n (consignments) => () => {\n const shippingConsignment = consignments?.find(\n (consignment) => !consignment.selectedPickupOption,\n );\n\n return shippingConsignment?.shippingAddress;\n },\n );\n\n const getShippingAddressOrThrow = createSelector(\n getShippingAddress,\n (getShippingAddress) => () => {\n return guard(\n getShippingAddress(),\n () => new MissingDataError(MissingDataErrorType.MissingShippingAddress),\n );\n },\n );\n\n const getShippingAddresses = createSelector(\n (state: ConsignmentState) => state.data,\n (consignments) => () => {\n const shippingConsignments = consignments?.filter(\n (consignment) => !consignment.selectedPickupOption,\n );\n\n return shippingConsignments\n ? shippingConsignments.map((consignment) => consignment.shippingAddress)\n : [];\n },\n );\n\n const getShippingAddressesOrThrow = createSelector(\n getShippingAddresses,\n (getShippingAddresses) => () => {\n return guard(\n getShippingAddresses(),\n () => new MissingDataError(MissingDataErrorType.MissingShippingAddress),\n );\n },\n );\n\n return memoizeOne((state: ConsignmentState = DEFAULT_STATE): ShippingAddressSelector => {\n return {\n getShippingAddress: getShippingAddress(state),\n getShippingAddressOrThrow: getShippingAddressOrThrow(state),\n getShippingAddresses: getShippingAddresses(state),\n getShippingAddressesOrThrow: getShippingAddressesOrThrow(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport OrderBillingAddressState, {\n DEFAULT_STATE,\n OrderBillingAddress,\n} from './order-billing-address-state';\n\nexport default interface OrderBillingAddressSelector {\n getOrderBillingAddress(): OrderBillingAddress | undefined;\n}\n\nexport type OrderBillingAddressSelectorFactory = (\n state: OrderBillingAddressState,\n) => OrderBillingAddressSelector;\n\nexport function createOrderBillingAddressSelectorFactory(): OrderBillingAddressSelectorFactory {\n const getOrderBillingAddress = createSelector(\n (state: OrderBillingAddressState) => state.data,\n (data) => () => data,\n );\n\n return memoizeOne(\n (state: OrderBillingAddressState = DEFAULT_STATE): OrderBillingAddressSelector => {\n return {\n getOrderBillingAddress: getOrderBillingAddress(state),\n };\n },\n );\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { find } from 'lodash';\n\nimport { CheckoutSelector } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\nimport { GatewayOrderPayment, OrderSelector } from '../order';\n\nimport PaymentMethod from './payment-method';\nimport { HOSTED } from './payment-method-types';\nimport { ACKNOWLEDGE, FINALIZE } from './payment-status-types';\n\nexport default interface PaymentSelector {\n getPaymentId(): { providerId: string; gatewayId?: string } | undefined;\n getPaymentIdOrThrow(): { providerId: string; gatewayId?: string };\n getPaymentStatus(): string | undefined;\n getPaymentStatusOrThrow(): string;\n getPaymentToken(): string | undefined;\n getPaymentTokenOrThrow(): string;\n getPaymentRedirectUrl(): string | undefined;\n getPaymentRedirectUrlOrThrow(): string;\n isPaymentDataRequired(useStoreCredit?: boolean): boolean;\n isPaymentDataSubmitted(paymentMethod?: PaymentMethod): boolean;\n}\n\nexport type PaymentSelectorFactory = (\n checkout: CheckoutSelector,\n order: OrderSelector,\n) => PaymentSelector;\n\ninterface PaymentSelectorDependencies {\n checkout: CheckoutSelector;\n order: OrderSelector;\n}\n\nexport function createPaymentSelectorFactory(): PaymentSelectorFactory {\n const getInternalPayment = createSelector(\n ({ order }: PaymentSelectorDependencies) => order.getOrderMeta,\n (getOrderMeta) => () => {\n const meta = getOrderMeta();\n\n return meta && meta.payment;\n },\n );\n\n const getGatewayPayment = createSelector(\n ({ order }: PaymentSelectorDependencies) => order.getOrder,\n (getOrder) => () => {\n const order = getOrder();\n\n return find(\n order && order.payments,\n ({ providerId }) =>\n providerId !== 'giftcertificate' && providerId !== 'storecredit',\n ) as GatewayOrderPayment;\n },\n );\n\n const getHostedPayment = createSelector(\n ({ checkout }: PaymentSelectorDependencies) => checkout.getCheckout,\n (getCheckout) => () => {\n const checkout = getCheckout();\n\n return find(\n checkout && checkout.payments,\n ({ providerType }) => providerType === HOSTED,\n );\n },\n );\n\n const getPaymentId = createSelector(\n getInternalPayment,\n getHostedPayment,\n getGatewayPayment,\n (getInternalPayment, getHostedPayment, getGatewayPayment) => () => {\n const internalPayment = getInternalPayment();\n\n if (internalPayment && internalPayment.id) {\n return {\n providerId: internalPayment.id,\n gatewayId: internalPayment.gateway,\n };\n }\n\n const payment = getHostedPayment() || getGatewayPayment();\n\n if (payment && payment.providerId) {\n return {\n providerId: payment.providerId,\n gatewayId: payment.gatewayId,\n };\n }\n },\n );\n\n const getPaymentIdOrThrow = createSelector(getPaymentId, (getPaymentId) => () => {\n return guard(\n getPaymentId(),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentId),\n );\n });\n\n const getPaymentStatus = createSelector(\n getInternalPayment,\n getHostedPayment,\n getGatewayPayment,\n (getInternalPayment, getHostedPayment, getGatewayPayment) => () => {\n const internalPayment = getInternalPayment();\n\n if (internalPayment && internalPayment.status) {\n return internalPayment.status.replace('PAYMENT_STATUS_', '');\n }\n\n const payment = getHostedPayment() || getGatewayPayment();\n\n if (payment) {\n return payment.detail.step;\n }\n },\n );\n\n const getPaymentStatusOrThrow = createSelector(getPaymentStatus, (getPaymentStatus) => () => {\n return guard(\n getPaymentStatus(),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentStatus),\n );\n });\n\n const getPaymentToken = createSelector(\n ({ order }: PaymentSelectorDependencies) => order.getOrderMeta,\n (getOrderMeta) => () => {\n const meta = getOrderMeta();\n\n return meta && meta.token;\n },\n );\n\n const getPaymentTokenOrThrow = createSelector(getPaymentToken, (getPaymentToken) => () => {\n return guard(\n getPaymentToken(),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentToken),\n );\n });\n\n const getPaymentRedirectUrl = createSelector(getInternalPayment, (getInternalPayment) => () => {\n const payment = getInternalPayment();\n\n return payment && payment.redirectUrl;\n });\n\n const getPaymentRedirectUrlOrThrow = createSelector(\n getPaymentRedirectUrl,\n (getPaymentRedirectUrl) => () => {\n return guard(\n getPaymentRedirectUrl(),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentRedirectUrl),\n );\n },\n );\n\n const isPaymentDataRequired = createSelector(\n ({ checkout }: PaymentSelectorDependencies) => checkout.getOutstandingBalance,\n (getOutstandingBalance) =>\n (useStoreCredit = false) => {\n const grandTotal = getOutstandingBalance(useStoreCredit);\n\n return grandTotal ? grandTotal > 0 : false;\n },\n );\n\n const isPaymentDataSubmitted = createSelector(\n getPaymentStatus,\n (getPaymentStatus) => (paymentMethod?: PaymentMethod) => {\n if (paymentMethod && paymentMethod.nonce) {\n return true;\n }\n\n return getPaymentStatus() === ACKNOWLEDGE || getPaymentStatus() === FINALIZE;\n },\n );\n\n return memoizeOne((checkout: CheckoutSelector, order: OrderSelector): PaymentSelector => {\n return {\n getPaymentId: getPaymentId({ checkout, order }),\n getPaymentIdOrThrow: getPaymentIdOrThrow({ checkout, order }),\n getPaymentStatus: getPaymentStatus({ checkout, order }),\n getPaymentStatusOrThrow: getPaymentStatusOrThrow({ checkout, order }),\n getPaymentToken: getPaymentToken({ checkout, order }),\n getPaymentTokenOrThrow: getPaymentTokenOrThrow({ checkout, order }),\n getPaymentRedirectUrl: getPaymentRedirectUrl({ checkout, order }),\n getPaymentRedirectUrlOrThrow: getPaymentRedirectUrlOrThrow({ checkout, order }),\n isPaymentDataRequired: isPaymentDataRequired({ checkout, order }),\n isPaymentDataSubmitted: isPaymentDataSubmitted({ checkout, order }),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport { SignInEmail } from './signin-email';\nimport SignInEmailState, { DEFAULT_STATE } from './signin-email-state';\n\nexport default interface SignInEmailSelector {\n getEmail(): SignInEmail | undefined;\n getSendError(): Error | undefined;\n isSending(): boolean;\n}\n\nexport type SignInEmailSelectorFactory = (state: SignInEmailState) => SignInEmailSelector;\n\nexport function createSignInEmailSelectorFactory(): SignInEmailSelectorFactory {\n const getEmail = createSelector(\n (state: SignInEmailState) => state.data,\n (signInEmail) => () => signInEmail,\n );\n\n const getSendError = createSelector(\n (state: SignInEmailState) => state.errors.sendError,\n (error) => () => error,\n );\n\n const isSending = createSelector(\n (state: SignInEmailState) => !!state.statuses.isSending,\n (status) => () => status,\n );\n\n return memoizeOne((state: SignInEmailState = DEFAULT_STATE): SignInEmailSelector => {\n return {\n getEmail: getEmail(state),\n getSendError: getSendError(state),\n isSending: isSending(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport Cart from './cart';\nimport CartState, { DEFAULT_STATE } from './cart-state';\n\nexport default interface CartSelector {\n getCart(): Cart | undefined;\n getCartOrThrow(): Cart;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type CartSelectorFactory = (state: CartState) => CartSelector;\n\nexport function createCartSelectorFactory() {\n const getCart = createSelector(\n (state: CartState) => state.data,\n (cart) => () => cart,\n );\n\n const getCartOrThrow = createSelector(getCart, (getCart) => () => {\n return guard(getCart(), () => new MissingDataError(MissingDataErrorType.MissingCart));\n });\n\n const getLoadError = createSelector(\n (state: CartState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: CartState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne((state: CartState = DEFAULT_STATE): CartSelector => {\n return {\n getCart: getCart(state),\n getCartOrThrow: getCartOrThrow(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\nimport { FormFieldsState } from '../form';\n\nimport Config, { ContextConfig, FlashMessage, FlashMessageType, StoreConfig } from './config';\nimport ConfigState, { DEFAULT_STATE } from './config-state';\n\nexport default interface ConfigSelector {\n getConfig(): Config | undefined;\n getFlashMessages(type?: FlashMessageType): FlashMessage[] | undefined;\n getStoreConfig(): StoreConfig | undefined;\n getStoreConfigOrThrow(): StoreConfig;\n getContextConfig(): ContextConfig | undefined;\n getExternalSource(): string | undefined;\n getHost(): string | undefined;\n getLocale(): string | undefined;\n getVariantIdentificationToken(): string | undefined;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type ConfigSelectorFactory = (\n state: ConfigState,\n formState: FormFieldsState,\n) => ConfigSelector;\n\ninterface ConfigSelectorDependencies {\n formState: FormFieldsState;\n}\n\nexport function createConfigSelectorFactory(): ConfigSelectorFactory {\n const getConfig = createSelector(\n (state: ConfigState) => state.data,\n (data) => () => data,\n );\n\n const getFlashMessages = createSelector(\n (state: ConfigState) => state.data,\n (data) => (filterType?: FlashMessageType) => {\n if (!data) {\n return;\n }\n\n const { flashMessages } = data.context;\n\n if (!flashMessages) {\n return;\n }\n\n return filterType !== undefined\n ? flashMessages.filter(({ type }) => filterType === type)\n : flashMessages;\n },\n );\n\n const getStoreConfig = createSelector(\n (state: ConfigState) => state.data,\n (_: ConfigState, { formState }: ConfigSelectorDependencies) => formState && formState.data,\n (data, formFields) => () =>\n data && formFields\n ? {\n ...data.storeConfig,\n formFields,\n }\n : undefined,\n );\n\n const getStoreConfigOrThrow = createSelector(getStoreConfig, (getStoreConfig) => () => {\n return guard(\n getStoreConfig(),\n () => new MissingDataError(MissingDataErrorType.MissingCheckoutConfig),\n );\n });\n\n const getContextConfig = createSelector(\n (state: ConfigState) => state.data && state.data.context,\n (data) => () => data,\n );\n\n const getExternalSource = createSelector(\n (state: ConfigState) => state.meta && state.meta.externalSource,\n (data) => () => data,\n );\n\n const getHost = createSelector(\n (state: ConfigState) => state.meta?.host,\n (data) => () => data,\n );\n\n const getLocale = createSelector(\n (state: ConfigState) => state.meta?.locale,\n (data) => () => data,\n );\n\n const getVariantIdentificationToken = createSelector(\n (state: ConfigState) => state.meta && state.meta.variantIdentificationToken,\n (data) => () => data,\n );\n\n const getLoadError = createSelector(\n (state: ConfigState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: ConfigState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne(\n (state: ConfigState = DEFAULT_STATE, formState: FormFieldsState): ConfigSelector => {\n return {\n getConfig: getConfig(state),\n getFlashMessages: getFlashMessages(state),\n getStoreConfig: getStoreConfig(state, { formState }),\n getStoreConfigOrThrow: getStoreConfigOrThrow(state, { formState }),\n getContextConfig: getContextConfig(state),\n getExternalSource: getExternalSource(state),\n getHost: getHost(state),\n getLocale: getLocale(state),\n getVariantIdentificationToken: getVariantIdentificationToken(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n },\n );\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport Country from './country';\nimport CountryState, { DEFAULT_STATE } from './country-state';\n\nexport default interface CountrySelector {\n getCountries(): Country[] | undefined;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type CountrySelectorFactory = (state: CountryState) => CountrySelector;\n\nexport function createCountrySelectorFactory(): CountrySelectorFactory {\n const getCountries = createSelector(\n (state: CountryState) => state.data,\n (countries) => () => countries,\n );\n\n const getLoadError = createSelector(\n (state: CountryState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: CountryState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne((state: CountryState = DEFAULT_STATE): CountrySelector => {\n return {\n getCountries: getCountries(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport CustomerStrategyState, { DEFAULT_STATE } from './customer-strategy-state';\n\nexport default interface CustomerStrategySelector {\n getSignInError(methodId?: string): Error | undefined;\n getSignOutError(methodId?: string): Error | undefined;\n getExecutePaymentMethodCheckoutError(methodId?: string): Error | undefined;\n getInitializeError(methodId?: string): Error | undefined;\n getWidgetInteractionError(methodId?: string): Error | undefined;\n isSigningIn(methodId?: string): boolean;\n isSigningOut(methodId?: string): boolean;\n isExecutingPaymentMethodCheckout(methodId?: string): boolean;\n isInitializing(methodId?: string): boolean;\n isInitialized(methodId: string): boolean;\n isWidgetInteracting(methodId?: string): boolean;\n}\n\nexport type CustomerStrategySelectorFactory = (\n state: CustomerStrategyState,\n) => CustomerStrategySelector;\n\nexport function createCustomerStrategySelectorFactory(): CustomerStrategySelectorFactory {\n const getSignInError = createSelector(\n (state: CustomerStrategyState) => state.errors.signInMethodId,\n (state: CustomerStrategyState) => state.errors.signInError,\n (signInMethodId, signInError) => (methodId?: string) => {\n if (methodId && signInMethodId !== methodId) {\n return;\n }\n\n return signInError;\n },\n );\n\n const getSignOutError = createSelector(\n (state: CustomerStrategyState) => state.errors.signOutMethodId,\n (state: CustomerStrategyState) => state.errors.signOutError,\n (signOutMethodId, signOutError) => (methodId?: string) => {\n if (methodId && signOutMethodId !== methodId) {\n return;\n }\n\n return signOutError;\n },\n );\n\n const getExecutePaymentMethodCheckoutError = createSelector(\n (state: CustomerStrategyState) => state.errors.executePaymentMethodCheckoutMethodId,\n (state: CustomerStrategyState) => state.errors.executePaymentMethodCheckoutError,\n (executePaymentMethodCheckoutMethodId, executePaymentMethodCheckoutError) =>\n (methodId?: string) => {\n if (methodId && executePaymentMethodCheckoutMethodId !== methodId) {\n return;\n }\n\n return executePaymentMethodCheckoutError;\n },\n );\n\n const getInitializeError = createSelector(\n (state: CustomerStrategyState) => state.errors.initializeMethodId,\n (state: CustomerStrategyState) => state.errors.initializeErrors,\n (initializeMethodId, initializeErrors) => (methodId?: string) => {\n if (!initializeMethodId || !initializeErrors) {\n return;\n }\n\n if (methodId) {\n return initializeErrors[methodId];\n }\n\n return initializeErrors[initializeMethodId];\n },\n );\n\n const getWidgetInteractionError = createSelector(\n (state: CustomerStrategyState) => state.errors.widgetInteractionMethodId,\n (state: CustomerStrategyState) => state.errors.widgetInteractionError,\n (widgetInteractionMethodId, widgetInteractionError) => (methodId?: string) => {\n if (methodId && widgetInteractionMethodId !== methodId) {\n return;\n }\n\n return widgetInteractionError;\n },\n );\n\n const isSigningIn = createSelector(\n (state: CustomerStrategyState) => state.statuses.signInMethodId,\n (state: CustomerStrategyState) => state.statuses.isSigningIn,\n (signInMethodId, isSigningIn) => (methodId?: string) => {\n if (methodId && signInMethodId !== methodId) {\n return false;\n }\n\n return !!isSigningIn;\n },\n );\n\n const isSigningOut = createSelector(\n (state: CustomerStrategyState) => state.statuses.signOutMethodId,\n (state: CustomerStrategyState) => state.statuses.isSigningOut,\n (signOutMethodId, isSigningOut) => (methodId?: string) => {\n if (methodId && signOutMethodId !== methodId) {\n return false;\n }\n\n return !!isSigningOut;\n },\n );\n\n const isExecutingPaymentMethodCheckout = createSelector(\n (state: CustomerStrategyState) => state.statuses.executePaymentMethodCheckoutMethodId,\n (state: CustomerStrategyState) => state.statuses.isExecutingPaymentMethodCheckout,\n (executePaymentMethodCheckoutMethodId, isExecutingPaymentMethodCheckout) =>\n (methodId?: string) => {\n if (methodId && executePaymentMethodCheckoutMethodId !== methodId) {\n return false;\n }\n\n return !!isExecutingPaymentMethodCheckout;\n },\n );\n\n const isInitializing = createSelector(\n (state: CustomerStrategyState) => state.statuses.initializeMethodId,\n (state: CustomerStrategyState) => state.statuses.isInitializing,\n (initializeMethodId, isInitializing) => (methodId?: string) => {\n if (methodId && initializeMethodId !== methodId) {\n return false;\n }\n\n return !!isInitializing;\n },\n );\n\n const isInitialized = createSelector(\n (state: CustomerStrategyState) => state.data,\n (data) => (methodId: string) => {\n return !!(data[methodId] && data[methodId].isInitialized);\n },\n );\n\n const isWidgetInteracting = createSelector(\n (state: CustomerStrategyState) => state.statuses.widgetInteractionMethodId,\n (state: CustomerStrategyState) => state.statuses.isWidgetInteracting,\n (widgetInteractionMethodId, isWidgetInteracting) => (methodId?: string) => {\n if (methodId && widgetInteractionMethodId !== methodId) {\n return false;\n }\n\n return !!isWidgetInteracting;\n },\n );\n\n return memoizeOne((state: CustomerStrategyState = DEFAULT_STATE): CustomerStrategySelector => {\n return {\n getSignInError: getSignInError(state),\n getSignOutError: getSignOutError(state),\n getExecutePaymentMethodCheckoutError: getExecutePaymentMethodCheckoutError(state),\n getInitializeError: getInitializeError(state),\n getWidgetInteractionError: getWidgetInteractionError(state),\n isSigningIn: isSigningIn(state),\n isSigningOut: isSigningOut(state),\n isExecutingPaymentMethodCheckout: isExecutingPaymentMethodCheckout(state),\n isInitializing: isInitializing(state),\n isInitialized: isInitialized(state),\n isWidgetInteracting: isWidgetInteracting(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RequestError } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\n\nimport GiftCertificate from './gift-certificate';\nimport GiftCertificateState, { DEFAULT_STATE } from './gift-certificate-state';\n\nexport default interface GiftCertificateSelector {\n getGiftCertificates(): GiftCertificate[] | undefined;\n getRemoveError(): RequestError | undefined;\n getApplyError(): RequestError | undefined;\n isApplying(): boolean;\n isRemoving(): boolean;\n}\n\nexport type GiftCertificateSelectorFactory = (\n state: GiftCertificateState,\n) => GiftCertificateSelector;\n\nexport function createGiftCertificateSelectorFactory(): GiftCertificateSelectorFactory {\n const getGiftCertificates = createSelector(\n (state: GiftCertificateState) => state.data,\n (data) => () => data,\n );\n\n const getRemoveError = createSelector(\n (state: GiftCertificateState) => state.errors.removeGiftCertificateError,\n (error) => () => error,\n );\n\n const getApplyError = createSelector(\n (state: GiftCertificateState) => state.errors.applyGiftCertificateError,\n (error) => () => error,\n );\n\n const isApplying = createSelector(\n (state: GiftCertificateState) => !!state.statuses.isApplyingGiftCertificate,\n (status) => () => status,\n );\n\n const isRemoving = createSelector(\n (state: GiftCertificateState) => !!state.statuses.isRemovingGiftCertificate,\n (status) => () => status,\n );\n\n return memoizeOne((state: GiftCertificateState = DEFAULT_STATE): GiftCertificateSelector => {\n return {\n getGiftCertificates: getGiftCertificates(state),\n getRemoveError: getRemoveError(state),\n getApplyError: getApplyError(state),\n isApplying: isApplying(state),\n isRemoving: isRemoving(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { filter, flatMap, isMatch, values } from 'lodash';\n\nimport { MissingDataError, MissingDataErrorType } from '../../common/error/errors';\nimport { createSelector } from '../../common/selector';\nimport { guard } from '../../common/utility';\nimport PaymentMethod from '../payment-method';\n\nimport PaymentInstrument, { CardInstrument } from './instrument';\nimport InstrumentState, { DEFAULT_STATE, InstrumentMeta } from './instrument-state';\nimport supportedInstruments from './supported-payment-instruments';\n\nexport default interface InstrumentSelector {\n getCardInstrument(instrumentId: string): CardInstrument | undefined;\n getCardInstrumentOrThrow(instrumentId: string): CardInstrument;\n getInstruments(): PaymentInstrument[] | undefined;\n getInstrumentsByPaymentMethod(paymentMethod: PaymentMethod): PaymentInstrument[] | undefined;\n getInstrumentsMeta(): InstrumentMeta | undefined;\n getLoadError(): Error | undefined;\n getDeleteError(instrumentId?: string): Error | undefined;\n isLoading(): boolean;\n isDeleting(instrumentId?: string): boolean;\n}\n\nexport type InstrumentSelectorFactory = (state: InstrumentState) => InstrumentSelector;\n\nexport function createInstrumentSelectorFactory(): InstrumentSelectorFactory {\n const getInstrumentsByPaymentMethod = createSelector(\n (state: InstrumentState) => state.data,\n (instruments) => (paymentMethod: PaymentMethod) => {\n if (!instruments) {\n return;\n }\n\n const paymentMethodKey = paymentMethod.gateway\n ? `${paymentMethod.gateway}.${paymentMethod.id}`\n : paymentMethod.id;\n\n const currentMethod = supportedInstruments[paymentMethodKey];\n\n if (!currentMethod) {\n return [];\n }\n\n return filter(instruments, currentMethod);\n },\n );\n\n const getCardInstrument = createSelector(\n (state: InstrumentState) => state.data,\n (instruments = []) =>\n (instrumentId: string) => {\n const cards = values(supportedInstruments);\n\n return instruments.find(\n (instrument): instrument is CardInstrument =>\n instrument.bigpayToken === instrumentId &&\n instrument.type === 'card' &&\n cards.some((card) => isMatch(instrument, card)),\n );\n },\n );\n\n const getCardInstrumentOrThrow = createSelector(\n getCardInstrument,\n (getCardInstrument) => (instrumentId: string) => {\n return guard(\n getCardInstrument(instrumentId),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentInstrument),\n );\n },\n );\n\n const getInstruments = createSelector(\n (state: InstrumentState) => state.data,\n (instruments) => () => {\n if (!instruments) {\n return;\n }\n\n const allSupportedInstruments = flatMap(supportedInstruments, (supportedProvider) =>\n filter(\n instruments,\n (instrument: PaymentInstrument): instrument is PaymentInstrument => {\n return isMatch(instrument, supportedProvider);\n },\n ),\n );\n\n return allSupportedInstruments;\n },\n );\n\n const getInstrumentsMeta = createSelector(\n (state: InstrumentState) => state.meta,\n (meta) => () => meta,\n );\n\n const getLoadError = createSelector(\n (state: InstrumentState) => state.errors.loadError,\n (loadError) => () => loadError,\n );\n\n const getDeleteError = createSelector(\n (state: InstrumentState) => state.errors.failedInstrument,\n (state: InstrumentState) => state.errors.deleteError,\n (failedInstrument, deleteError) => (instrumentId?: string) => {\n if (instrumentId && failedInstrument !== instrumentId) {\n return;\n }\n\n return deleteError;\n },\n );\n\n const isLoading = createSelector(\n (state: InstrumentState) => state.statuses.isLoading,\n (isLoading) => () => !!isLoading,\n );\n\n const isDeleting = createSelector(\n (state: InstrumentState) => state.statuses.deletingInstrument,\n (state: InstrumentState) => state.statuses.isDeleting,\n (deletingInstrument, isDeleting) => (instrumentId?: string) => {\n if (instrumentId && deletingInstrument !== instrumentId) {\n return false;\n }\n\n return !!isDeleting;\n },\n );\n\n return memoizeOne((state: InstrumentState = DEFAULT_STATE): InstrumentSelector => {\n return {\n getCardInstrument: getCardInstrument(state),\n getCardInstrumentOrThrow: getCardInstrumentOrThrow(state),\n getInstruments: getInstruments(state),\n getInstrumentsByPaymentMethod: getInstrumentsByPaymentMethod(state),\n getInstrumentsMeta: getInstrumentsMeta(state),\n getLoadError: getLoadError(state),\n getDeleteError: getDeleteError(state),\n isLoading: isLoading(state),\n isDeleting: isDeleting(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { find } from 'lodash';\n\nimport { createSelector } from '../common/selector';\nimport { Country } from '../geography';\n\nimport FormField from './form-field';\nimport FormFieldsState, { DEFAULT_STATE } from './form-fields-state';\n\nexport default interface FormSelector {\n getShippingAddressFields(countries: Country[] | undefined, countryCode: string): FormField[];\n getBillingAddressFields(countries: Country[] | undefined, countryCode: string): FormField[];\n getCustomerAccountFields(): FormField[];\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type FormSelectorFactory = (state: FormFieldsState) => FormSelector;\n\nexport function createFormSelectorFactory(): FormSelectorFactory {\n const getShippingAddressFields = createSelector(\n (state: FormFieldsState) => state.data,\n (formFields) =>\n (countries: Country[] = [], countryCode: string) => {\n const selectedCountry = find(countries, { code: countryCode });\n const fields = formFields ? formFields.shippingAddress : [];\n\n return fields.map((field: any) => processField(field, countries, selectedCountry));\n },\n );\n\n const getBillingAddressFields = createSelector(\n (state: FormFieldsState) => state.data,\n (formFields) =>\n (countries: Country[] = [], countryCode: string) => {\n const selectedCountry = find(countries, { code: countryCode });\n const fields = formFields ? formFields.billingAddress : [];\n\n return fields.map((field: any) => processField(field, countries, selectedCountry));\n },\n );\n\n const getCustomerAccountFields = createSelector(\n (state: FormFieldsState) => state.data,\n (formFields) => () => formFields ? formFields.customerAccount : [],\n );\n\n const getLoadError = createSelector(\n (state: FormFieldsState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: FormFieldsState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n function processField(\n field: FormField,\n countries: Country[],\n selectedCountry?: Country,\n ): FormField {\n if (field.name === 'countryCode') {\n return processCountry(field, countries, selectedCountry);\n }\n\n if (field.name === 'stateOrProvince') {\n return processProvince(field, selectedCountry);\n }\n\n if (field.name === 'postalCode') {\n return processsPostCode(field, selectedCountry);\n }\n\n return field;\n }\n\n function processCountry(\n field: FormField,\n countries: Country[] = [],\n country?: Country,\n ): FormField {\n if (!countries.length) {\n return field;\n }\n\n const { code = '' } = country || {};\n const items = countries.map(({ code, name }: any) => ({\n value: code,\n label: name,\n }));\n\n return {\n ...field,\n options: { items },\n default: code,\n type: 'array',\n fieldType: 'dropdown',\n itemtype: 'string',\n };\n }\n\n function processProvince(field: FormField, country?: Country): FormField {\n const { subdivisions = [], requiresState } = country || {};\n\n if (!subdivisions.length) {\n return {\n ...field,\n required: requiresState == null ? false : requiresState,\n };\n }\n\n const items = subdivisions.map(({ code, name }: any) => ({\n value: code,\n label: name,\n }));\n\n return {\n ...field,\n name: 'stateOrProvinceCode',\n options: { items },\n required: requiresState == null ? true : requiresState,\n type: 'array',\n fieldType: 'dropdown',\n itemtype: 'string',\n };\n }\n\n function processsPostCode(field: FormField, country?: Country): FormField {\n const { hasPostalCodes = [] } = country || {};\n\n if (hasPostalCodes === undefined) {\n return field;\n }\n\n return { ...field, required: Boolean(hasPostalCodes) };\n }\n\n return memoizeOne((state: FormFieldsState = DEFAULT_STATE): FormSelector => {\n return {\n getShippingAddressFields: getShippingAddressFields(state),\n getBillingAddressFields: getBillingAddressFields(state),\n getCustomerAccountFields: getCustomerAccountFields(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { find } from 'lodash';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport PaymentMethod from './payment-method';\nimport PaymentMethodMeta from './payment-method-meta';\nimport PaymentMethodState, { DEFAULT_STATE } from './payment-method-state';\n\nexport default interface PaymentMethodSelector {\n getPaymentMethods(): PaymentMethod[] | undefined;\n getPaymentMethodsMeta(): PaymentMethodMeta | undefined;\n getPaymentMethod(methodId: string, gatewayId?: string): PaymentMethod | undefined;\n getPaymentMethodOrThrow(methodId: string, gatewayId?: string): PaymentMethod;\n getLoadError(): Error | undefined;\n getLoadMethodError(methodId?: string): Error | undefined;\n isLoading(): boolean;\n isLoadingMethod(methodId?: string): boolean;\n}\n\nexport type PaymentMethodSelectorFactory = (state: PaymentMethodState) => PaymentMethodSelector;\n\nexport function createPaymentMethodSelectorFactory(): PaymentMethodSelectorFactory {\n const getPaymentMethods = createSelector(\n (state: PaymentMethodState) => state.data,\n (paymentMethods) => () => paymentMethods,\n );\n\n const getPaymentMethodsMeta = createSelector(\n (state: PaymentMethodState) => state.meta,\n (meta) => () => meta,\n );\n\n const getPaymentMethod = createSelector(\n (state: PaymentMethodState) => state.data,\n (paymentMethods) => (methodId: string, gatewayId?: string) => {\n return gatewayId\n ? find(paymentMethods, { id: methodId, gateway: gatewayId })\n : find(paymentMethods, { id: methodId });\n },\n );\n\n const getPaymentMethodOrThrow = createSelector(\n getPaymentMethod,\n (getPaymentMethod) => (methodId: string, gatewayId?: string) => {\n return guard(\n getPaymentMethod(methodId, gatewayId),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentMethod),\n );\n },\n );\n\n const getLoadError = createSelector(\n (state: PaymentMethodState) => state.errors.loadError,\n (loadError) => () => loadError,\n );\n\n const getLoadMethodError = createSelector(\n (state: PaymentMethodState) => state.errors.loadMethodId,\n (state: PaymentMethodState) => state.errors.loadMethodError,\n (loadMethodId, loadMethodError) => (methodId?: string) => {\n if (methodId && loadMethodId !== methodId) {\n return;\n }\n\n return loadMethodError;\n },\n );\n\n const isLoading = createSelector(\n (state: PaymentMethodState) => state.statuses.isLoading,\n (isLoading) => () => !!isLoading,\n );\n\n const isLoadingMethod = createSelector(\n (state: PaymentMethodState) => state.statuses.loadMethodId,\n (state: PaymentMethodState) => state.statuses.isLoadingMethod,\n (loadMethodId, isLoadingMethod) => (methodId?: string) => {\n if (methodId && loadMethodId !== methodId) {\n return false;\n }\n\n return !!isLoadingMethod;\n },\n );\n\n return memoizeOne((state: PaymentMethodState = DEFAULT_STATE): PaymentMethodSelector => {\n return {\n getPaymentMethods: getPaymentMethods(state),\n getPaymentMethodsMeta: getPaymentMethodsMeta(state),\n getPaymentMethod: getPaymentMethod(state),\n getPaymentMethodOrThrow: getPaymentMethodOrThrow(state),\n getLoadError: getLoadError(state),\n getLoadMethodError: getLoadMethodError(state),\n isLoading: isLoading(state),\n isLoadingMethod: isLoadingMethod(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport PaymentStrategyState, { DEFAULT_STATE } from './payment-strategy-state';\n\ninterface InitiaizedQuery {\n methodId: string;\n gatewayId?: string;\n}\n\nexport default interface PaymentStrategySelector {\n getInitializeError(methodId?: string): Error | undefined;\n getExecuteError(methodId?: string): Error | undefined;\n getFinalizeError(methodId?: string): Error | undefined;\n getWidgetInteractingError(methodId?: string): Error | undefined;\n isInitializing(methodId?: string): boolean;\n isInitialized(query: InitiaizedQuery): boolean;\n isExecuting(methodId?: string): boolean;\n isFinalizing(methodId?: string): boolean;\n isWidgetInteracting(methodId?: string): boolean;\n}\n\nexport type PaymentStrategySelectorFactory = (\n state: PaymentStrategyState,\n) => PaymentStrategySelector;\n\nexport function createPaymentStrategySelectorFactory(): PaymentStrategySelectorFactory {\n const getInitializeError = createSelector(\n (state: PaymentStrategyState) => state.errors.initializeMethodId,\n (state: PaymentStrategyState) => state.errors.initializeError,\n (initializeMethodId, initializeError) => (methodId?: string) => {\n if (methodId && initializeMethodId !== methodId) {\n return;\n }\n\n return initializeError;\n },\n );\n\n const getExecuteError = createSelector(\n (state: PaymentStrategyState) => state.errors.executeMethodId,\n (state: PaymentStrategyState) => state.errors.executeError,\n (executeMethodId, executeError) => (methodId?: string) => {\n if (methodId && executeMethodId !== methodId) {\n return;\n }\n\n return executeError;\n },\n );\n\n const getFinalizeError = createSelector(\n (state: PaymentStrategyState) => state.errors.finalizeMethodId,\n (state: PaymentStrategyState) => state.errors.finalizeError,\n (finalizeMethodId, finalizeError) => (methodId?: string) => {\n if (methodId && finalizeMethodId !== methodId) {\n return;\n }\n\n return finalizeError;\n },\n );\n\n const getWidgetInteractingError = createSelector(\n (state: PaymentStrategyState) => state.errors.widgetInteractionMethodId,\n (state: PaymentStrategyState) => state.errors.widgetInteractionError,\n (widgetInteractionMethodId, widgetInteractionError) => (methodId?: string) => {\n if (methodId && widgetInteractionMethodId !== methodId) {\n return;\n }\n\n return widgetInteractionError;\n },\n );\n\n const isInitializing = createSelector(\n (state: PaymentStrategyState) => state.statuses.initializeMethodId,\n (state: PaymentStrategyState) => state.statuses.isInitializing,\n (initializeMethodId, isInitializing) => (key?: string) => {\n if (key && initializeMethodId !== key) {\n return false;\n }\n\n return !!isInitializing;\n },\n );\n\n const isInitialized = createSelector(\n (state: PaymentStrategyState) => state.data,\n (data) => (query: InitiaizedQuery) => {\n const key = query.gatewayId ? `${query.methodId}.${query.gatewayId}` : query.methodId;\n\n return !!(data[key] && data[key].isInitialized);\n },\n );\n\n const isExecuting = createSelector(\n (state: PaymentStrategyState) => state.statuses.executeMethodId,\n (state: PaymentStrategyState) => state.statuses.isExecuting,\n (executeMethodId, isExecuting) => (methodId?: string) => {\n if (methodId && executeMethodId !== methodId) {\n return false;\n }\n\n return !!isExecuting;\n },\n );\n\n const isFinalizing = createSelector(\n (state: PaymentStrategyState) => state.statuses.finalizeMethodId,\n (state: PaymentStrategyState) => state.statuses.isFinalizing,\n (finalizeMethodId, isFinalizing) => (methodId?: string) => {\n if (methodId && finalizeMethodId !== methodId) {\n return false;\n }\n\n return !!isFinalizing;\n },\n );\n\n const isWidgetInteracting = createSelector(\n (state: PaymentStrategyState) => state.statuses.widgetInteractionMethodId,\n (state: PaymentStrategyState) => state.statuses.isWidgetInteracting,\n (widgetInteractionMethodId, isWidgetInteracting) => (methodId?: string) => {\n if (methodId && widgetInteractionMethodId !== methodId) {\n return false;\n }\n\n return !!isWidgetInteracting;\n },\n );\n\n return memoizeOne((state: PaymentStrategyState = DEFAULT_STATE): PaymentStrategySelector => {\n return {\n getInitializeError: getInitializeError(state),\n getExecuteError: getExecuteError(state),\n getFinalizeError: getFinalizeError(state),\n getWidgetInteractingError: getWidgetInteractingError(state),\n isInitializing: isInitializing(state),\n isInitialized: isInitialized(state),\n isExecuting: isExecuting(state),\n isFinalizing: isFinalizing(state),\n isWidgetInteracting: isWidgetInteracting(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\nimport { objectFlatten, objectWithSortedKeys } from '../common/utility';\n\nimport { PickupOptionResult, SearchArea } from './pickup-option';\nimport PickupOptionState, { DEFAULT_STATE } from './pickup-option-state';\n\nexport default interface PickupOptionSelector {\n getPickupOptions(\n consignmentId: string,\n searchArea: SearchArea,\n ): PickupOptionResult[] | undefined;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type PickupOptionSelectorFactory = (state: PickupOptionState) => PickupOptionSelector;\n\nexport function createPickupOptionSelectorFactory(): PickupOptionSelectorFactory {\n const getPickupOptions = createSelector(\n (state: PickupOptionState) => state.data,\n (pickupOptions) => (consignmentId: string, searchArea: SearchArea) => {\n if (!pickupOptions) {\n return;\n }\n\n const flattenedParams = objectFlatten({ consignmentId, searchArea });\n const sortedFlattenedParams = objectWithSortedKeys(flattenedParams);\n const keyString = btoa(`${JSON.stringify(sortedFlattenedParams)}`);\n\n return pickupOptions[keyString];\n },\n );\n\n const getLoadError = createSelector(\n (state: PickupOptionState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: PickupOptionState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne((state: PickupOptionState = DEFAULT_STATE): PickupOptionSelector => {\n return {\n getPickupOptions: getPickupOptions(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\nimport { Country } from '../geography';\n\nimport ShippingCountryState, { DEFAULT_STATE } from './shipping-country-state';\n\nexport default interface ShippingCountrySelector {\n getShippingCountries(): Country[] | undefined;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type ShippingCountrySelectorFactory = (\n state: ShippingCountryState,\n) => ShippingCountrySelector;\n\nexport function createShippingCountrySelectorFactory(): ShippingCountrySelectorFactory {\n const getShippingCountries = createSelector(\n (state: ShippingCountryState) => state.data,\n (data) => () => data,\n );\n\n const getLoadError = createSelector(\n (state: ShippingCountryState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: ShippingCountryState) => state.statuses.isLoading,\n (status) => () => !!status,\n );\n\n return memoizeOne((state: ShippingCountryState = DEFAULT_STATE): ShippingCountrySelector => {\n return {\n getShippingCountries: getShippingCountries(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport ShippingStrategyState, { DEFAULT_STATE } from './shipping-strategy-state';\n\nexport default interface ShippingStrategySelector {\n getUpdateAddressError(methodId?: string): Error | undefined;\n getSelectOptionError(methodId?: string): Error | undefined;\n getInitializeError(methodId?: string): Error | undefined;\n getWidgetInteractionError(methodId?: string): Error | undefined;\n isUpdatingAddress(methodId?: string): boolean;\n isSelectingOption(methodId?: string): boolean;\n isInitializing(methodId?: string): boolean;\n isInitialized(methodId: string): boolean;\n isWidgetInteracting(methodId?: string): boolean;\n}\n\nexport type ShippingStrategySelectorFactory = (\n state: ShippingStrategyState,\n) => ShippingStrategySelector;\n\nexport function createShippingStrategySelectorFactory(): ShippingStrategySelectorFactory {\n const getUpdateAddressError = createSelector(\n (state: ShippingStrategyState) => state.errors.updateAddressMethodId,\n (state: ShippingStrategyState) => state.errors.updateAddressError,\n (updateAddressMethodId, updateAddressError) => (methodId?: string) => {\n if (methodId && updateAddressMethodId !== methodId) {\n return;\n }\n\n return updateAddressError;\n },\n );\n\n const getSelectOptionError = createSelector(\n (state: ShippingStrategyState) => state.errors.selectOptionMethodId,\n (state: ShippingStrategyState) => state.errors.selectOptionError,\n (selectOptionMethodId, selectOptionError) => (methodId?: string) => {\n if (methodId && selectOptionMethodId !== methodId) {\n return;\n }\n\n return selectOptionError;\n },\n );\n\n const getInitializeError = createSelector(\n (state: ShippingStrategyState) => state.errors.initializeMethodId,\n (state: ShippingStrategyState) => state.errors.initializeError,\n (initializeMethodId, initializeError) => (methodId?: string) => {\n if (methodId && initializeMethodId !== methodId) {\n return;\n }\n\n return initializeError;\n },\n );\n\n const getWidgetInteractionError = createSelector(\n (state: ShippingStrategyState) => state.errors.widgetInteractionMethodId,\n (state: ShippingStrategyState) => state.errors.widgetInteractionError,\n (widgetInteractionMethodId, widgetInteractionError) => (methodId?: string) => {\n if (methodId && widgetInteractionMethodId !== methodId) {\n return;\n }\n\n return widgetInteractionError;\n },\n );\n\n const isUpdatingAddress = createSelector(\n (state: ShippingStrategyState) => state.statuses.updateAddressMethodId,\n (state: ShippingStrategyState) => state.statuses.isUpdatingAddress,\n (updateAddressMethodId, isUpdatingAddress) => (methodId?: string) => {\n if (methodId && updateAddressMethodId !== methodId) {\n return false;\n }\n\n return !!isUpdatingAddress;\n },\n );\n\n const isSelectingOption = createSelector(\n (state: ShippingStrategyState) => state.statuses.selectOptionMethodId,\n (state: ShippingStrategyState) => state.statuses.isSelectingOption,\n (selectOptionMethodId, isSelectingOption) => (methodId?: string) => {\n if (methodId && selectOptionMethodId !== methodId) {\n return false;\n }\n\n return !!isSelectingOption;\n },\n );\n\n const isInitializing = createSelector(\n (state: ShippingStrategyState) => state.statuses.initializeMethodId,\n (state: ShippingStrategyState) => state.statuses.isInitializing,\n (initializeMethodId, isInitializing) => (methodId?: string) => {\n if (methodId && initializeMethodId !== methodId) {\n return false;\n }\n\n return !!isInitializing;\n },\n );\n\n const isInitialized = createSelector(\n (state: ShippingStrategyState) => state.data,\n (data) => (methodId: string) => {\n return !!(data[methodId] && data[methodId].isInitialized);\n },\n );\n\n const isWidgetInteracting = createSelector(\n (state: ShippingStrategyState) => state.statuses.widgetInteractionMethodId,\n (state: ShippingStrategyState) => state.statuses.isWidgetInteracting,\n (widgetInteractionMethodId, isWidgetInteracting) => (methodId?: string) => {\n if (methodId && widgetInteractionMethodId !== methodId) {\n return false;\n }\n\n return !!isWidgetInteracting;\n },\n );\n\n return memoizeOne((state: ShippingStrategyState = DEFAULT_STATE): ShippingStrategySelector => {\n return {\n getUpdateAddressError: getUpdateAddressError(state),\n getSelectOptionError: getSelectOptionError(state),\n getInitializeError: getInitializeError(state),\n getWidgetInteractionError: getWidgetInteractionError(state),\n isUpdatingAddress: isUpdatingAddress(state),\n isSelectingOption: isSelectingOption(state),\n isInitializing: isInitializing(state),\n isInitialized: isInitialized(state),\n isWidgetInteracting: isWidgetInteracting(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { find } from 'lodash';\n\nimport { AddressRequestBody, isAddressEqual } from '../address';\nimport { CartSelector, PhysicalItem } from '../cart';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport Consignment from './consignment';\nimport ConsignmentState, { DEFAULT_STATE } from './consignment-state';\nimport ShippingOption from './shipping-option';\n\nexport default interface ConsignmentSelector {\n getConsignments(): Consignment[] | undefined;\n getConsignmentsOrThrow(): Consignment[];\n getConsignmentById(id: string): Consignment | undefined;\n getConsignmentByAddress(address: AddressRequestBody): Consignment | undefined;\n getShippingOption(): ShippingOption | undefined;\n getLoadError(): Error | undefined;\n getCreateError(): Error | undefined;\n getLoadShippingOptionsError(): Error | undefined;\n getUnassignedItems(): PhysicalItem[];\n getUpdateError(consignmentId?: string): Error | undefined;\n getDeleteError(consignmentId?: string): Error | undefined;\n getItemAssignmentError(address: AddressRequestBody): Error | undefined;\n getUpdateShippingOptionError(consignmentId?: string): Error | undefined;\n isLoading(): boolean;\n isLoadingShippingOptions(): boolean;\n isCreating(): boolean;\n isUpdating(consignmentId?: string): boolean;\n isDeleting(consignmentId?: string): boolean;\n isAssigningItems(address: AddressRequestBody): boolean;\n isUpdatingShippingOption(consignmentId?: string): boolean;\n}\n\nexport type ConsignmentSelectorFactory = (\n state: ConsignmentState,\n cart: CartSelector,\n) => ConsignmentSelector;\n\ninterface ConsignmentSelectorDependencies {\n cart: CartSelector;\n}\n\nexport function createConsignmentSelectorFactory(): ConsignmentSelectorFactory {\n const getConsignments = createSelector(\n (state: ConsignmentState) => state.data,\n (consignments) => () => consignments,\n );\n\n const getConsignmentsOrThrow = createSelector(getConsignments, (getConsignments) => () => {\n return guard(\n getConsignments(),\n () => new MissingDataError(MissingDataErrorType.MissingConsignments),\n );\n });\n\n const getConsignmentById = createSelector(\n (state: ConsignmentState) => state.data,\n (consignments) => (id: string) => {\n if (!consignments || !consignments.length) {\n return;\n }\n\n return find(consignments, { id });\n },\n );\n\n const getConsignmentByAddress = createSelector(\n (state: ConsignmentState) => state.data,\n (consignments) => (address: AddressRequestBody) => {\n if (!consignments || !consignments.length) {\n return;\n }\n\n return find(consignments, (consignment) =>\n isAddressEqual(consignment.shippingAddress, address),\n );\n },\n );\n\n const getShippingOption = createSelector(\n (state: ConsignmentState) => state.data,\n (consignments) => () => {\n if (consignments && consignments.length) {\n return consignments[0].selectedShippingOption;\n }\n },\n );\n\n const getLoadError = createSelector(\n (state: ConsignmentState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const getCreateError = createSelector(\n (state: ConsignmentState) => state.errors.createError,\n (error) => () => error,\n );\n\n const getLoadShippingOptionsError = createSelector(\n (state: ConsignmentState) => state.errors.loadShippingOptionsError,\n (error) => () => error,\n );\n\n const getUnassignedItems = createSelector(\n getConsignments,\n (_: ConsignmentState, { cart }: ConsignmentSelectorDependencies) => cart.getCart,\n (getConsignments, getCart) => () => {\n const cart = getCart();\n\n if (!cart) {\n return [];\n }\n\n const assignedLineItemIds = (getConsignments() || []).reduce(\n (itemIds, consignment) => itemIds.concat(consignment.lineItemIds),\n [] as string[],\n );\n\n return (cart.lineItems.physicalItems || []).filter(\n (item) => assignedLineItemIds.indexOf(item.id as string) < 0,\n );\n },\n );\n\n const getUpdateError = createSelector(\n (state: ConsignmentState) => state.errors.updateError,\n (updateError) => (consignmentId?: string) => {\n if (consignmentId) {\n return updateError[consignmentId];\n }\n\n return find(updateError);\n },\n );\n\n const getDeleteError = createSelector(\n (state: ConsignmentState) => state.errors.deleteError,\n (deleteError) => (consignmentId?: string) => {\n if (consignmentId) {\n return deleteError[consignmentId];\n }\n\n return find(deleteError);\n },\n );\n\n const getItemAssignmentError = createSelector(\n getConsignmentByAddress,\n getUpdateError,\n getCreateError,\n (getConsignmentByAddress, getUpdateError, getCreateError) =>\n (address: AddressRequestBody) => {\n const consignment = getConsignmentByAddress(address);\n\n return consignment ? getUpdateError(consignment.id) : getCreateError();\n },\n );\n\n const getUpdateShippingOptionError = createSelector(\n (state: ConsignmentState) => state.errors.updateShippingOptionError,\n (updateShippingOptionError) => (consignmentId?: string) => {\n if (consignmentId) {\n return updateShippingOptionError[consignmentId];\n }\n\n return find(updateShippingOptionError);\n },\n );\n\n const isLoading = createSelector(\n (state: ConsignmentState) => state.statuses.isLoading,\n (isLoading) => () => isLoading === true,\n );\n\n const isLoadingShippingOptions = createSelector(\n (state: ConsignmentState) => state.statuses.isLoadingShippingOptions,\n (isLoadingShippingOptions) => () => isLoadingShippingOptions === true,\n );\n\n const isCreating = createSelector(\n (state: ConsignmentState) => state.statuses.isCreating,\n (isCreating) => () => isCreating === true,\n );\n\n const isUpdating = createSelector(\n (state: ConsignmentState) => state.statuses.isUpdating,\n (isUpdating) => (consignmentId?: string) => {\n if (consignmentId) {\n return isUpdating[consignmentId] === true;\n }\n\n return find(isUpdating) === true;\n },\n );\n\n const isDeleting = createSelector(\n (state: ConsignmentState) => state.statuses.isDeleting,\n (isDeleting) => (consignmentId?: string) => {\n if (consignmentId) {\n return isDeleting[consignmentId] === true;\n }\n\n return find(isDeleting) === true;\n },\n );\n\n const isAssigningItems = createSelector(\n getConsignmentByAddress,\n isUpdating,\n isCreating,\n (getConsignmentByAddress, isUpdating, isCreating) => (address: AddressRequestBody) => {\n const consignment = getConsignmentByAddress(address);\n\n return consignment ? isUpdating(consignment.id) : isCreating();\n },\n );\n\n const isUpdatingShippingOption = createSelector(\n (state: ConsignmentState) => state.statuses.isUpdatingShippingOption,\n (isUpdatingShippingOption) => (consignmentId?: string) => {\n if (consignmentId) {\n return isUpdatingShippingOption[consignmentId] === true;\n }\n\n return find(isUpdatingShippingOption) === true;\n },\n );\n\n return memoizeOne(\n (state: ConsignmentState = DEFAULT_STATE, cart: CartSelector): ConsignmentSelector => {\n return {\n getConsignments: getConsignments(state),\n getConsignmentsOrThrow: getConsignmentsOrThrow(state),\n getConsignmentById: getConsignmentById(state),\n getConsignmentByAddress: getConsignmentByAddress(state),\n getShippingOption: getShippingOption(state),\n getLoadError: getLoadError(state),\n getCreateError: getCreateError(state),\n getLoadShippingOptionsError: getLoadShippingOptionsError(state),\n getUnassignedItems: getUnassignedItems(state, { cart }),\n getUpdateError: getUpdateError(state),\n getDeleteError: getDeleteError(state),\n getItemAssignmentError: getItemAssignmentError(state),\n getUpdateShippingOptionError: getUpdateShippingOptionError(state),\n isLoading: isLoading(state),\n isLoadingShippingOptions: isLoadingShippingOptions(state),\n isCreating: isCreating(state),\n isUpdating: isUpdating(state),\n isDeleting: isDeleting(state),\n isAssigningItems: isAssigningItems(state),\n isUpdatingShippingOption: isUpdatingShippingOption(state),\n };\n },\n );\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { BillingAddressSelector } from '../billing';\nimport { CartSelector } from '../cart';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\nimport { CouponSelector, GiftCertificateSelector } from '../coupon';\nimport { CustomerSelector } from '../customer';\nimport { ConsignmentSelector } from '../shipping';\n\nimport Checkout from './checkout';\nimport CheckoutState, { DEFAULT_STATE } from './checkout-state';\n\nexport default interface CheckoutSelector {\n getCheckout(): Checkout | undefined;\n getCheckoutOrThrow(): Checkout;\n getOutstandingBalance(useStoreCredit?: boolean): number | undefined;\n getLoadError(): Error | undefined;\n getUpdateError(): Error | undefined;\n isExecutingSpamCheck(): boolean;\n isLoading(): boolean;\n isUpdating(): boolean;\n}\n\nexport type CheckoutSelectorFactory = (\n state: CheckoutState,\n billingAddress: BillingAddressSelector,\n cart: CartSelector,\n consignments: ConsignmentSelector,\n coupons: CouponSelector,\n customer: CustomerSelector,\n giftCertificates: GiftCertificateSelector,\n) => CheckoutSelector;\n\ninterface CheckoutSelectorDependencies {\n billingAddress: BillingAddressSelector;\n cart: CartSelector;\n consignments: ConsignmentSelector;\n coupons: CouponSelector;\n customer: CustomerSelector;\n giftCertificates: GiftCertificateSelector;\n}\n\nexport function createCheckoutSelectorFactory(): CheckoutSelectorFactory {\n const getCheckout = createSelector(\n (state: CheckoutState) => state.data,\n (_: CheckoutState, { billingAddress }: CheckoutSelectorDependencies) =>\n billingAddress.getBillingAddress,\n (_: CheckoutState, { cart }: CheckoutSelectorDependencies) => cart.getCart,\n (_: CheckoutState, { customer }: CheckoutSelectorDependencies) => customer.getCustomer,\n (_: CheckoutState, { consignments }: CheckoutSelectorDependencies) =>\n consignments.getConsignments,\n (_: CheckoutState, { coupons }: CheckoutSelectorDependencies) => coupons.getCoupons,\n (_: CheckoutState, { giftCertificates }: CheckoutSelectorDependencies) =>\n giftCertificates.getGiftCertificates,\n (\n data,\n getBillingAddress,\n getCart,\n getCustomer,\n getConsignments,\n getCoupons,\n getGiftCertificates,\n ) =>\n () => {\n const billingAddress = getBillingAddress();\n const cart = getCart();\n const customer = getCustomer();\n const consignments = getConsignments() || [];\n const coupons = getCoupons() || [];\n const giftCertificates = getGiftCertificates() || [];\n\n if (!data || !cart || !customer) {\n return;\n }\n\n return {\n ...data,\n billingAddress,\n cart,\n customer,\n consignments,\n coupons,\n giftCertificates,\n };\n },\n );\n\n const getCheckoutOrThrow = createSelector(getCheckout, (getCheckout) => () => {\n return guard(\n getCheckout(),\n () => new MissingDataError(MissingDataErrorType.MissingCheckout),\n );\n });\n\n const getOutstandingBalance = createSelector(\n getCheckout,\n (getCheckout) => (useStoreCredit?: boolean) => {\n const checkout = getCheckout();\n\n if (!checkout) {\n return;\n }\n\n const grandTotal = checkout.grandTotal || 0;\n const storeCredit = checkout.customer.storeCredit || 0;\n\n return useStoreCredit\n ? Math.max(grandTotal - storeCredit, 0)\n : checkout.outstandingBalance;\n },\n );\n\n const getLoadError = createSelector(\n (state: CheckoutState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const getUpdateError = createSelector(\n (state: CheckoutState) => state.errors.updateError,\n (error) => () => error,\n );\n\n const isExecutingSpamCheck = createSelector(\n (state: CheckoutState) => state.statuses.isExecutingSpamCheck,\n (isExecutingSpamCheck) => () => isExecutingSpamCheck === true,\n );\n\n const isLoading = createSelector(\n (state: CheckoutState) => state.statuses.isLoading,\n (isLoading) => () => isLoading === true,\n );\n\n const isUpdating = createSelector(\n (state: CheckoutState) => state.statuses.isUpdating,\n (isUpdating) => () => isUpdating === true,\n );\n\n return memoizeOne(\n (\n state: CheckoutState = DEFAULT_STATE,\n billingAddress: BillingAddressSelector,\n cart: CartSelector,\n consignments: ConsignmentSelector,\n coupons: CouponSelector,\n customer: CustomerSelector,\n giftCertificates: GiftCertificateSelector,\n ): CheckoutSelector => {\n return {\n getCheckout: getCheckout(state, {\n billingAddress,\n cart,\n consignments,\n coupons,\n customer,\n giftCertificates,\n }),\n getCheckoutOrThrow: getCheckoutOrThrow(state, {\n billingAddress,\n cart,\n consignments,\n coupons,\n customer,\n giftCertificates,\n }),\n getOutstandingBalance: getOutstandingBalance(state, {\n billingAddress,\n cart,\n consignments,\n coupons,\n customer,\n giftCertificates,\n }),\n getLoadError: getLoadError(state),\n getUpdateError: getUpdateError(state),\n isExecutingSpamCheck: isExecutingSpamCheck(state),\n isLoading: isLoading(state),\n isUpdating: isUpdating(state),\n };\n },\n );\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\nimport { CouponSelector } from '../coupon';\nimport OrderBillingAddressSelector from '../order-billing-address/order-billing-address-selector';\n\nimport Order from './order';\nimport OrderState, { DEFAULT_STATE, OrderMetaState } from './order-state';\n\nexport default interface OrderSelector {\n getOrder(): Order | undefined;\n getOrderOrThrow(): Order;\n getOrderMeta(): OrderMetaState | undefined;\n getLoadError(): Error | undefined;\n getPaymentId(methodId: string): string | undefined;\n isLoading(): boolean;\n}\n\nexport type OrderSelectorFactory = (\n state: OrderState,\n billingAddress: OrderBillingAddressSelector,\n coupons: CouponSelector,\n) => OrderSelector;\n\ninterface OrderSelectorDependencies {\n billingAddress: OrderBillingAddressSelector;\n coupons: CouponSelector;\n}\n\nexport function createOrderSelectorFactory(): OrderSelectorFactory {\n const getOrder = createSelector(\n (state: OrderState) => state.data,\n (_: OrderState, { billingAddress }: OrderSelectorDependencies) =>\n billingAddress.getOrderBillingAddress(),\n (_: OrderState, { coupons }: OrderSelectorDependencies) => coupons.getCoupons(),\n (data, billingAddress, coupons = []) =>\n () => {\n if (!data || !billingAddress) {\n return;\n }\n\n return {\n ...data,\n billingAddress,\n coupons,\n };\n },\n );\n\n const getOrderOrThrow = createSelector(getOrder, (getOrder) => () => {\n return guard(getOrder(), () => new MissingDataError(MissingDataErrorType.MissingOrder));\n });\n\n const getOrderMeta = createSelector(\n (state: OrderState) => state.meta,\n (meta) => () => meta,\n );\n\n const getLoadError = createSelector(\n (state: OrderState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const getPaymentId = createSelector(\n (state: OrderState) => state.data?.payments,\n (payments = []) =>\n (methodId: string) => {\n const currentPayment = payments.find(({ providerId }) => providerId === methodId);\n\n return currentPayment?.paymentId;\n },\n );\n\n const isLoading = createSelector(\n (state: OrderState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne(\n (\n state: OrderState = DEFAULT_STATE,\n billingAddress: OrderBillingAddressSelector,\n coupons: CouponSelector,\n ): OrderSelector => {\n return {\n getOrder: getOrder(state, { billingAddress, coupons }),\n getOrderOrThrow: getOrderOrThrow(state, { billingAddress, coupons }),\n getOrderMeta: getOrderMeta(state),\n getLoadError: getLoadError(state),\n getPaymentId: getPaymentId(state),\n isLoading: isLoading(state),\n };\n },\n );\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { RequestError } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\n\nimport StoreCreditState, { DEFAULT_STATE } from './store-credit-state';\n\nexport default interface StoreCreditSelector {\n getApplyError(): RequestError | undefined;\n isApplying(): boolean;\n}\n\nexport type StoreCreditSelectorFactory = (state: StoreCreditState) => StoreCreditSelector;\n\nexport function createStoreCreditSelectorFactory(): StoreCreditSelectorFactory {\n const getApplyError = createSelector(\n (state: StoreCreditState) => state.errors.applyError,\n (error) => () => error,\n );\n\n const isApplying = createSelector(\n (state: StoreCreditState) => !!state.statuses.isApplying,\n (status) => () => status,\n );\n\n return memoizeOne((state: StoreCreditState = DEFAULT_STATE): StoreCreditSelector => {\n return {\n getApplyError: getApplyError(state),\n isApplying: isApplying(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport SubscriptionsState, { DEFAULT_STATE } from './subscriptions-state';\n\nexport default interface SubscriptionsSelector {\n getUpdateError(): Error | undefined;\n isUpdating(): boolean;\n}\n\nexport type SubscriptionsSelectorFactory = (state: SubscriptionsState) => SubscriptionsSelector;\n\nexport function createSubscriptionsSelectorFactory(): SubscriptionsSelectorFactory {\n const getUpdateError = createSelector(\n (state: SubscriptionsState) => state.errors.updateError,\n (error) => () => error,\n );\n\n const isUpdating = createSelector(\n (state: SubscriptionsState) => !!state.statuses.isUpdating,\n (status) => () => status,\n );\n\n return memoizeOne((state: SubscriptionsState = DEFAULT_STATE): SubscriptionsSelector => {\n return {\n getUpdateError: getUpdateError(state),\n isUpdating: isUpdating(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport { Extension, ExtensionRegion } from './extension';\nimport { DEFAULT_STATE, ExtensionState } from './extension-state';\n\nexport interface ExtensionSelector {\n getExtensions(): Extension[] | undefined;\n getExtensionByRegion(region: ExtensionRegion): Extension | undefined;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type ExtensionSelectorFactory = (state: ExtensionState) => ExtensionSelector;\n\nexport function createExtensionSelectorFactory(): ExtensionSelectorFactory {\n const getExtensions = createSelector(\n (state: ExtensionState) => state.data,\n (data) => () => data,\n );\n\n const getExtensionByRegion = createSelector(\n (state: ExtensionState) => state.data,\n (data) => (region: ExtensionRegion) => data?.find((e) => e.region === region),\n );\n\n const getLoadError = createSelector(\n (state: ExtensionState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: ExtensionState) => state.statuses.isLoading,\n (isLoading) => () => !!isLoading,\n );\n\n return memoizeOne((state: ExtensionState = DEFAULT_STATE): ExtensionSelector => {\n return {\n getExtensions: getExtensions(state),\n getExtensionByRegion: getExtensionByRegion(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { createDataStore } from '@bigcommerce/data-store';\n\nimport { createRequestErrorFactory } from '../common/error';\n\nimport CheckoutStore, { CheckoutStoreOptions } from './checkout-store';\nimport CheckoutStoreState from './checkout-store-state';\nimport createActionTransformer from './create-action-transformer';\nimport createCheckoutStoreReducer from './create-checkout-store-reducer';\nimport { createInternalCheckoutSelectorsFactory } from './create-internal-checkout-selectors';\n\nexport default function createCheckoutStore(\n initialState: Partial = {},\n options?: CheckoutStoreOptions,\n): CheckoutStore {\n const actionTransformer = createActionTransformer(createRequestErrorFactory());\n const createInternalCheckoutSelectors = createInternalCheckoutSelectorsFactory();\n const stateTransformer = (state: CheckoutStoreState) => createInternalCheckoutSelectors(state);\n\n return createDataStore(createCheckoutStoreReducer(), initialState, {\n actionTransformer,\n stateTransformer,\n ...options,\n });\n}\n","import { PaymentMethodInvalidError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { UnrecoverableError } from './errors';\nimport RequestErrorFactory from './request-error-factory';\n\nexport default function createRequestErrorFactory(): RequestErrorFactory {\n const factory = new RequestErrorFactory();\n\n const unrecoverableErrorTypes = [\n 'catalog_only',\n 'empty_cart',\n 'invalid_order_id',\n 'invalid_order_token',\n 'missing_order_token',\n 'missing_provider_token',\n 'missing_shipping_method',\n 'order_completion_error',\n 'order_could_not_be_finalized_error',\n 'order_create_failed',\n 'provider_fatal_error',\n 'provider_setup_error',\n 'stock_too_low',\n ];\n\n unrecoverableErrorTypes.forEach((type) => {\n factory.register(type, (response, message) => new UnrecoverableError(response, message));\n });\n\n factory.register(\n 'invalid_payment_provider',\n (response) => new PaymentMethodInvalidError(response),\n );\n factory.register(\n 'payment_config_not_found',\n (response) => new PaymentMethodInvalidError(response),\n );\n\n return factory;\n}\n","import { Action } from '@bigcommerce/data-store';\nimport { from, Observable, Subscribable } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { RequestErrorFactory } from '../common/error';\n\nexport default function createActionTransformer(\n requestErrorFactory: RequestErrorFactory,\n): (action: Subscribable) => Observable {\n return (action$) =>\n from(action$).pipe(\n catchError((action) => {\n if (action instanceof Error || action.payload instanceof Error) {\n throw action;\n }\n\n if (isResponse(action.payload)) {\n const message = action.payload.body && action.payload.body.detail;\n\n throw {\n ...action,\n payload: requestErrorFactory.createError(action.payload, message),\n };\n }\n\n throw action;\n }),\n );\n}\n\nfunction isResponse(object: any) {\n if (!object || typeof object !== 'object') {\n return false;\n }\n\n return ['body', 'headers', 'status', 'statusText'].every((key) =>\n Object.prototype.hasOwnProperty.call(object, key),\n );\n}\n","import { Action, combineReducers, Reducer } from '@bigcommerce/data-store';\n\nimport { billingAddressReducer } from '../billing';\nimport { cartReducer } from '../cart';\nimport { checkoutButtonReducer } from '../checkout-buttons';\nimport { configReducer } from '../config';\nimport { couponReducer, giftCertificateReducer } from '../coupon';\nimport { customerReducer, customerStrategyReducer } from '../customer';\nimport { extensionReducer } from '../extension';\nimport { formFieldsReducer } from '../form';\nimport { countryReducer } from '../geography';\nimport { orderReducer } from '../order';\nimport { orderBillingAddressReducer } from '../order-billing-address';\nimport { paymentMethodReducer, paymentReducer, paymentStrategyReducer } from '../payment';\nimport { instrumentReducer } from '../payment/instrument';\nimport { remoteCheckoutReducer } from '../remote-checkout';\nimport {\n consignmentReducer,\n pickupOptionReducer,\n shippingCountryReducer,\n shippingStrategyReducer,\n} from '../shipping';\nimport { signInEmailReducer } from '../signin-email';\nimport { storeCreditReducer } from '../store-credit';\nimport { subscriptionsReducer } from '../subscription';\n\nimport checkoutReducer from './checkout-reducer';\nimport CheckoutStoreState from './checkout-store-state';\n\nexport default function createCheckoutStoreReducer(): Reducer {\n return combineReducers({\n billingAddress: billingAddressReducer,\n cart: cartReducer,\n checkout: checkoutReducer,\n checkoutButton: checkoutButtonReducer,\n config: configReducer,\n consignments: consignmentReducer,\n countries: countryReducer,\n coupons: couponReducer,\n customer: customerReducer,\n customerStrategies: customerStrategyReducer,\n extensions: extensionReducer,\n formFields: formFieldsReducer,\n giftCertificates: giftCertificateReducer,\n instruments: instrumentReducer,\n orderBillingAddress: orderBillingAddressReducer,\n order: orderReducer,\n payment: paymentReducer,\n paymentMethods: paymentMethodReducer,\n paymentStrategies: paymentStrategyReducer,\n pickupOptions: pickupOptionReducer,\n remoteCheckout: remoteCheckoutReducer,\n shippingCountries: shippingCountryReducer,\n shippingStrategies: shippingStrategyReducer,\n signInEmail: signInEmailReducer,\n subscriptions: subscriptionsReducer,\n storeCredit: storeCreditReducer,\n });\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { createScriptLoader } from '@bigcommerce/script-loader';\n\nimport { BillingAddressActionCreator, BillingAddressRequestSender } from '../billing';\nimport { ErrorActionCreator } from '../common/error';\nimport { getDefaultLogger } from '../common/log';\nimport { getEnvironment } from '../common/utility';\nimport { ConfigActionCreator, ConfigRequestSender, ConfigState, ConfigWindow } from '../config';\nimport {\n CouponActionCreator,\n CouponRequestSender,\n GiftCertificateActionCreator,\n GiftCertificateRequestSender,\n} from '../coupon';\nimport {\n createCustomerStrategyRegistry,\n createCustomerStrategyRegistryV2,\n CustomerActionCreator,\n CustomerRequestSender,\n CustomerStrategyActionCreator,\n} from '../customer';\nimport { ExtensionActionCreator, ExtensionRequestSender } from '../extension';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport * as defaultPaymentStrategyFactories from '../generated/payment-strategies';\nimport { CountryActionCreator, CountryRequestSender } from '../geography';\nimport { OrderActionCreator, OrderRequestSender } from '../order';\nimport {\n createPaymentClient,\n createPaymentStrategyRegistry,\n createPaymentStrategyRegistryV2,\n PaymentMethodActionCreator,\n PaymentMethodRequestSender,\n PaymentStrategyActionCreator,\n} from '../payment';\nimport { createPaymentIntegrationService } from '../payment-integration';\nimport { InstrumentActionCreator, InstrumentRequestSender } from '../payment/instrument';\nimport {\n ConsignmentActionCreator,\n ConsignmentRequestSender,\n createShippingStrategyRegistry,\n PickupOptionActionCreator,\n PickupOptionRequestSender,\n ShippingCountryActionCreator,\n ShippingCountryRequestSender,\n ShippingStrategyActionCreator,\n} from '../shipping';\nimport { SignInEmailActionCreator, SignInEmailRequestSender } from '../signin-email';\nimport {\n createSpamProtection,\n SpamProtectionActionCreator,\n SpamProtectionRequestSender,\n} from '../spam-protection';\nimport { StoreCreditActionCreator, StoreCreditRequestSender } from '../store-credit';\nimport { SubscriptionsActionCreator, SubscriptionsRequestSender } from '../subscription';\n\nimport CheckoutActionCreator from './checkout-action-creator';\nimport CheckoutRequestSender from './checkout-request-sender';\nimport CheckoutService from './checkout-service';\nimport CheckoutValidator from './checkout-validator';\nimport createCheckoutStore from './create-checkout-store';\n\n/**\n * Creates an instance of `CheckoutService`.\n *\n * @remarks\n * ```js\n * const service = createCheckoutService();\n *\n * service.subscribe(state => {\n * console.log(state);\n * });\n *\n * service.loadCheckout();\n * ```\n *\n * @param options - A set of construction options.\n * @returns an instance of `CheckoutService`.\n */\nexport default function createCheckoutService(options?: CheckoutServiceOptions): CheckoutService {\n if (document.location.protocol !== 'https:') {\n getDefaultLogger().warn(\n 'The BigCommerce Checkout SDK should not be used on a non-HTTPS page',\n );\n }\n\n if (getEnvironment() !== 'production') {\n getDefaultLogger().warn(\n 'Note that the development build is not optimized. To create a production build, set process.env.NODE_ENV to `production`.',\n );\n }\n\n const config: ConfigState = {\n meta: {\n externalSource: options && options.externalSource,\n host: options?.host,\n locale: options?.locale,\n variantIdentificationToken: (window as ConfigWindow).checkoutVariantIdentificationToken,\n },\n errors: {},\n statuses: {},\n };\n const { locale = '', shouldWarnMutation = true } = options || {};\n const requestSender = createRequestSender({ host: options && options.host });\n const store = createCheckoutStore({ config }, { shouldWarnMutation });\n const paymentClient = createPaymentClient(store);\n const orderRequestSender = new OrderRequestSender(requestSender);\n const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n const configActionCreator = new ConfigActionCreator(new ConfigRequestSender(requestSender));\n const spamProtection = createSpamProtection(createScriptLoader());\n const spamProtectionRequestSender = new SpamProtectionRequestSender(requestSender);\n const spamProtectionActionCreator = new SpamProtectionActionCreator(\n spamProtection,\n spamProtectionRequestSender,\n );\n const orderActionCreator = new OrderActionCreator(\n orderRequestSender,\n new CheckoutValidator(checkoutRequestSender),\n );\n const subscriptionsActionCreator = new SubscriptionsActionCreator(\n new SubscriptionsRequestSender(requestSender),\n );\n const formFieldsActionCreator = new FormFieldsActionCreator(\n new FormFieldsRequestSender(requestSender),\n );\n const checkoutActionCreator = new CheckoutActionCreator(\n checkoutRequestSender,\n configActionCreator,\n formFieldsActionCreator,\n );\n const paymentIntegrationService = createPaymentIntegrationService(store);\n const registryV2 = createPaymentStrategyRegistryV2(\n paymentIntegrationService,\n defaultPaymentStrategyFactories,\n { useFallback: true },\n );\n const customerRegistryV2 = createCustomerStrategyRegistryV2(paymentIntegrationService);\n const extensionActionCreator = new ExtensionActionCreator(\n new ExtensionRequestSender(requestSender),\n );\n\n return new CheckoutService(\n store,\n new BillingAddressActionCreator(\n new BillingAddressRequestSender(requestSender),\n subscriptionsActionCreator,\n ),\n checkoutActionCreator,\n configActionCreator,\n new CustomerActionCreator(\n new CustomerRequestSender(requestSender),\n checkoutActionCreator,\n spamProtectionActionCreator,\n ),\n new ConsignmentActionCreator(\n new ConsignmentRequestSender(requestSender),\n checkoutRequestSender,\n ),\n new CountryActionCreator(new CountryRequestSender(requestSender, { locale })),\n new CouponActionCreator(new CouponRequestSender(requestSender)),\n new CustomerStrategyActionCreator(\n createCustomerStrategyRegistry(store, requestSender, locale),\n customerRegistryV2,\n ),\n new ErrorActionCreator(),\n new GiftCertificateActionCreator(new GiftCertificateRequestSender(requestSender)),\n new InstrumentActionCreator(new InstrumentRequestSender(paymentClient, requestSender)),\n orderActionCreator,\n new PaymentMethodActionCreator(new PaymentMethodRequestSender(requestSender)),\n new PaymentStrategyActionCreator(\n createPaymentStrategyRegistry(\n store,\n paymentClient,\n requestSender,\n spamProtection,\n locale,\n ),\n registryV2,\n orderActionCreator,\n spamProtectionActionCreator,\n ),\n new PickupOptionActionCreator(new PickupOptionRequestSender(requestSender)),\n new ShippingCountryActionCreator(\n new ShippingCountryRequestSender(requestSender, { locale }),\n ),\n new ShippingStrategyActionCreator(createShippingStrategyRegistry(store, requestSender)),\n new SignInEmailActionCreator(new SignInEmailRequestSender(requestSender)),\n spamProtectionActionCreator,\n new StoreCreditActionCreator(new StoreCreditRequestSender(requestSender)),\n subscriptionsActionCreator,\n formFieldsActionCreator,\n extensionActionCreator,\n );\n}\n\nexport interface CheckoutServiceOptions {\n locale?: string;\n host?: string;\n shouldWarnMutation?: boolean;\n externalSource?: string;\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { RequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { CheckoutActionCreator, CheckoutRequestSender, CheckoutStore } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { ConfigActionCreator, ConfigRequestSender } from '../config';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport { PaymentMethodActionCreator, PaymentMethodRequestSender } from '../payment';\nimport { createPaymentIntegrationService } from '../payment-integration';\nimport { createAmazonPayV2PaymentProcessor } from '../payment/strategies/amazon-pay-v2';\nimport {\n BraintreeScriptLoader,\n BraintreeSDKCreator,\n createBraintreeVisaCheckoutPaymentProcessor,\n VisaCheckoutScriptLoader,\n} from '../payment/strategies/braintree';\nimport { ChasePayScriptLoader } from '../payment/strategies/chasepay';\nimport {\n createGooglePayPaymentProcessor,\n GooglePayAdyenV2Initializer,\n GooglePayAdyenV3Initializer,\n GooglePayAuthorizeNetInitializer,\n GooglePayBNZInitializer,\n GooglePayBraintreeInitializer,\n GooglePayCheckoutcomInitializer,\n GooglePayCybersourceV2Initializer,\n GooglePayOrbitalInitializer,\n GooglePayStripeInitializer,\n GooglePayStripeUPEInitializer,\n GooglePayWorldpayAccessInitializer,\n} from '../payment/strategies/googlepay';\nimport { MasterpassScriptLoader } from '../payment/strategies/masterpass';\nimport { StripeScriptLoader } from '../payment/strategies/stripe-upe';\nimport { RemoteCheckoutActionCreator, RemoteCheckoutRequestSender } from '../remote-checkout';\nimport { ConsignmentActionCreator, ConsignmentRequestSender } from '../shipping';\nimport {\n createSpamProtection,\n SpamProtectionActionCreator,\n SpamProtectionRequestSender,\n} from '../spam-protection';\n\nimport createCustomerStrategyRegistryV2 from './create-customer-strategy-registry-v2';\nimport CustomerActionCreator from './customer-action-creator';\nimport CustomerRequestSender from './customer-request-sender';\nimport CustomerStrategyActionCreator from './customer-strategy-action-creator';\nimport { CustomerStrategy } from './strategies';\nimport { AmazonPayV2CustomerStrategy } from './strategies/amazon-pay-v2';\nimport {\n BraintreePaypalCreditCustomerStrategy,\n BraintreeVisaCheckoutCustomerStrategy,\n} from './strategies/braintree';\nimport { ChasePayCustomerStrategy } from './strategies/chasepay';\nimport { DefaultCustomerStrategy } from './strategies/default';\nimport { GooglePayCustomerStrategy } from './strategies/googlepay';\nimport { MasterpassCustomerStrategy } from './strategies/masterpass';\nimport { SquareCustomerStrategy } from './strategies/square';\nimport { StripeUPECustomerStrategy } from './strategies/stripe-upe';\n\nexport default function createCustomerStrategyRegistry(\n store: CheckoutStore,\n requestSender: RequestSender,\n locale: string,\n): Registry {\n const registry = new Registry();\n const scriptLoader = getScriptLoader();\n const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n const checkoutActionCreator = new CheckoutActionCreator(\n checkoutRequestSender,\n new ConfigActionCreator(new ConfigRequestSender(requestSender)),\n new FormFieldsActionCreator(new FormFieldsRequestSender(requestSender)),\n );\n const formPoster = createFormPoster();\n const paymentMethodActionCreator = new PaymentMethodActionCreator(\n new PaymentMethodRequestSender(requestSender),\n );\n const remoteCheckoutRequestSender = new RemoteCheckoutRequestSender(requestSender);\n const remoteCheckoutActionCreator = new RemoteCheckoutActionCreator(\n remoteCheckoutRequestSender,\n checkoutActionCreator,\n );\n const spamProtectionActionCreator = new SpamProtectionActionCreator(\n createSpamProtection(scriptLoader),\n new SpamProtectionRequestSender(requestSender),\n );\n const customerActionCreator = new CustomerActionCreator(\n new CustomerRequestSender(requestSender),\n checkoutActionCreator,\n spamProtectionActionCreator,\n );\n\n const braintreeSDKCreator = new BraintreeSDKCreator(new BraintreeScriptLoader(scriptLoader));\n const paymentIntegrationService = createPaymentIntegrationService(store);\n const customerRegistryV2 = createCustomerStrategyRegistryV2(paymentIntegrationService);\n\n registry.register(\n 'googlepayadyenv2',\n () =>\n new GooglePayCustomerStrategy(\n store,\n remoteCheckoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayAdyenV2Initializer()),\n formPoster,\n ),\n );\n\n registry.register(\n 'googlepayadyenv3',\n () =>\n new GooglePayCustomerStrategy(\n store,\n remoteCheckoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayAdyenV3Initializer()),\n formPoster,\n ),\n );\n\n registry.register(\n 'amazonpay',\n () =>\n new AmazonPayV2CustomerStrategy(\n store,\n paymentMethodActionCreator,\n remoteCheckoutActionCreator,\n createAmazonPayV2PaymentProcessor(),\n ),\n );\n\n registry.register(\n 'braintreevisacheckout',\n () =>\n new BraintreeVisaCheckoutCustomerStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n new CustomerStrategyActionCreator(registry, customerRegistryV2),\n remoteCheckoutActionCreator,\n createBraintreeVisaCheckoutPaymentProcessor(scriptLoader, requestSender),\n new VisaCheckoutScriptLoader(scriptLoader),\n formPoster,\n ),\n );\n\n registry.register(\n 'braintreepaypalcredit',\n () =>\n new BraintreePaypalCreditCustomerStrategy(\n store,\n checkoutActionCreator,\n customerActionCreator,\n paymentMethodActionCreator,\n braintreeSDKCreator,\n formPoster,\n window,\n ),\n );\n\n registry.register(\n 'chasepay',\n () =>\n new ChasePayCustomerStrategy(\n store,\n paymentMethodActionCreator,\n remoteCheckoutActionCreator,\n new ChasePayScriptLoader(scriptLoader),\n requestSender,\n formPoster,\n ),\n );\n\n registry.register(\n 'squarev2',\n () =>\n new SquareCustomerStrategy(\n store,\n new RemoteCheckoutActionCreator(remoteCheckoutRequestSender, checkoutActionCreator),\n ),\n );\n\n registry.register(\n 'masterpass',\n () =>\n new MasterpassCustomerStrategy(\n store,\n paymentMethodActionCreator,\n remoteCheckoutActionCreator,\n new MasterpassScriptLoader(scriptLoader),\n locale,\n ),\n );\n\n registry.register(\n 'googlepayauthorizenet',\n () =>\n new GooglePayCustomerStrategy(\n store,\n remoteCheckoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayAuthorizeNetInitializer()),\n formPoster,\n ),\n );\n\n registry.register(\n 'googlepaybnz',\n () =>\n new GooglePayCustomerStrategy(\n store,\n remoteCheckoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayBNZInitializer()),\n formPoster,\n ),\n );\n\n registry.register(\n 'googlepaybraintree',\n () =>\n new GooglePayCustomerStrategy(\n store,\n remoteCheckoutActionCreator,\n createGooglePayPaymentProcessor(\n store,\n new GooglePayBraintreeInitializer(braintreeSDKCreator),\n ),\n formPoster,\n ),\n );\n\n registry.register(\n 'googlepaycheckoutcom',\n () =>\n new GooglePayCustomerStrategy(\n store,\n remoteCheckoutActionCreator,\n createGooglePayPaymentProcessor(\n store,\n new GooglePayCheckoutcomInitializer(requestSender),\n ),\n formPoster,\n ),\n );\n\n registry.register(\n 'googlepaycybersourcev2',\n () =>\n new GooglePayCustomerStrategy(\n store,\n remoteCheckoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayCybersourceV2Initializer()),\n formPoster,\n ),\n );\n\n registry.register(\n 'googlepayorbital',\n () =>\n new GooglePayCustomerStrategy(\n store,\n remoteCheckoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayOrbitalInitializer()),\n formPoster,\n ),\n );\n\n registry.register(\n 'googlepaystripe',\n () =>\n new GooglePayCustomerStrategy(\n store,\n remoteCheckoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayStripeInitializer()),\n formPoster,\n ),\n );\n\n registry.register(\n 'googlepaystripeupe',\n () =>\n new GooglePayCustomerStrategy(\n store,\n remoteCheckoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayStripeUPEInitializer()),\n formPoster,\n ),\n );\n\n registry.register(\n 'googlepayworldpayaccess',\n () =>\n new GooglePayCustomerStrategy(\n store,\n remoteCheckoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayWorldpayAccessInitializer()),\n formPoster,\n ),\n );\n\n registry.register(\n 'stripeupe',\n () =>\n new StripeUPECustomerStrategy(\n store,\n new StripeScriptLoader(scriptLoader),\n customerActionCreator,\n paymentMethodActionCreator,\n new ConsignmentActionCreator(\n new ConsignmentRequestSender(requestSender),\n new CheckoutRequestSender(requestSender),\n ),\n ),\n );\n\n registry.register('default', () => new DefaultCustomerStrategy(store, customerActionCreator));\n\n return registry;\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { RequestSender } from '@bigcommerce/request-sender';\nimport {\n createScriptLoader,\n getScriptLoader,\n getStylesheetLoader,\n} from '@bigcommerce/script-loader';\n\nimport { BillingAddressActionCreator, BillingAddressRequestSender } from '../billing';\nimport {\n CheckoutActionCreator,\n CheckoutRequestSender,\n CheckoutStore,\n CheckoutValidator,\n} from '../checkout';\nimport { BrowserStorage } from '../common/storage';\nimport { ConfigActionCreator, ConfigRequestSender } from '../config';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport { HostedFormFactory } from '../hosted-form';\nimport { OrderActionCreator, OrderRequestSender } from '../order';\nimport { createPaymentIntegrationService } from '../payment-integration';\nimport { RemoteCheckoutActionCreator, RemoteCheckoutRequestSender } from '../remote-checkout';\nimport {\n createSpamProtection,\n GoogleRecaptcha,\n PaymentHumanVerificationHandler,\n SpamProtectionActionCreator,\n SpamProtectionRequestSender,\n} from '../spam-protection';\nimport { StoreCreditActionCreator, StoreCreditRequestSender } from '../store-credit';\nimport { SubscriptionsActionCreator, SubscriptionsRequestSender } from '../subscription';\n\nimport createPaymentStrategyRegistryV2 from './create-payment-strategy-registry-v2';\nimport PaymentActionCreator from './payment-action-creator';\nimport PaymentMethodActionCreator from './payment-method-action-creator';\nimport PaymentMethodRequestSender from './payment-method-request-sender';\nimport PaymentRequestSender from './payment-request-sender';\nimport PaymentRequestTransformer from './payment-request-transformer';\nimport PaymentStrategyActionCreator from './payment-strategy-action-creator';\nimport PaymentStrategyRegistry from './payment-strategy-registry';\nimport PaymentStrategyType from './payment-strategy-type';\nimport StorefrontPaymentRequestSender from './storefront-payment-request-sender';\nimport { AdyenV2ScriptLoader } from './strategies/adyenv2';\nimport { AdyenV3ScriptLoader } from './strategies/adyenv3';\nimport { AffirmPaymentStrategy, AffirmScriptLoader } from './strategies/affirm';\nimport { AfterpayPaymentStrategy, AfterpayScriptLoader } from './strategies/afterpay';\nimport {\n AmazonPayV2PaymentStrategy,\n createAmazonPayV2PaymentProcessor,\n} from './strategies/amazon-pay-v2';\nimport { BarclaysPaymentStrategy } from './strategies/barclays';\nimport { BlueSnapV2PaymentStrategy } from './strategies/bluesnapv2';\nimport { BNZPaymentStrategy } from './strategies/bnz';\nimport {\n BraintreeCreditCardPaymentStrategy,\n BraintreePaypalPaymentStrategy,\n BraintreeScriptLoader,\n BraintreeSDKCreator,\n BraintreeVenmoPaymentStrategy,\n BraintreeVisaCheckoutPaymentStrategy,\n createBraintreePaymentProcessor,\n createBraintreeVisaCheckoutPaymentProcessor,\n VisaCheckoutScriptLoader,\n} from './strategies/braintree';\nimport {\n CardinalClient,\n CardinalScriptLoader,\n CardinalThreeDSecureFlow,\n CardinalThreeDSecureFlowV2,\n} from './strategies/cardinal';\nimport { CBAMPGSPaymentStrategy, CBAMPGSScriptLoader } from './strategies/cba-mpgs';\nimport { ChasePayPaymentStrategy, ChasePayScriptLoader } from './strategies/chasepay';\nimport {\n CheckoutcomAPMPaymentStrategy,\n CheckoutcomFawryPaymentStrategy,\n CheckoutcomiDealPaymentStrategy,\n CheckoutcomSEPAPaymentStrategy,\n} from './strategies/checkoutcom-custom';\nimport { ClearpayPaymentStrategy, ClearpayScriptLoader } from './strategies/clearpay';\nimport { ConvergePaymentStrategy } from './strategies/converge';\nimport { CreditCardRedirectPaymentStrategy } from './strategies/credit-card-redirect';\nimport { CyberSourcePaymentStrategy } from './strategies/cybersource/index';\nimport { CyberSourceV2PaymentStrategy } from './strategies/cybersourcev2';\nimport { DigitalRiverPaymentStrategy, DigitalRiverScriptLoader } from './strategies/digitalriver';\nimport {\n createGooglePayPaymentProcessor,\n GooglePayAdyenV2Initializer,\n GooglePayAdyenV2PaymentProcessor,\n GooglePayAdyenV3Initializer,\n GooglePayAdyenV3PaymentProcessor,\n GooglePayAuthorizeNetInitializer,\n GooglePayBNZInitializer,\n GooglePayBraintreeInitializer,\n GooglePayCheckoutcomInitializer,\n GooglePayCheckoutcomPaymentProcessor,\n GooglePayCybersourceV2Initializer,\n GooglePayOrbitalInitializer,\n GooglePayPaymentStrategy,\n GooglePayStripeInitializer,\n GooglePayStripeUPEInitializer,\n GooglePayWorldpayAccessInitializer,\n} from './strategies/googlepay';\nimport { HummPaymentStrategy } from './strategies/humm';\nimport { KlarnaPaymentStrategy, KlarnaScriptLoader } from './strategies/klarna';\nimport {\n KlarnaV2PaymentStrategy,\n KlarnaV2ScriptLoader,\n KlarnaV2TokenUpdater,\n} from './strategies/klarnav2';\nimport { MasterpassPaymentStrategy, MasterpassScriptLoader } from './strategies/masterpass';\nimport { MolliePaymentStrategy, MollieScriptLoader } from './strategies/mollie';\nimport { MonerisPaymentStrategy } from './strategies/moneris';\nimport { OpyPaymentStrategy, OpyScriptLoader } from './strategies/opy';\nimport {\n PaypalExpressPaymentStrategy,\n PaypalProPaymentStrategy,\n PaypalScriptLoader,\n} from './strategies/paypal';\nimport {\n createStepHandler,\n createSubStrategyRegistry,\n PaymentResumer,\n PPSDKStrategy,\n} from './strategies/ppsdk';\nimport { QuadpayPaymentStrategy } from './strategies/quadpay';\nimport { SagePayPaymentStrategy } from './strategies/sage-pay';\nimport { SquarePaymentStrategy, SquareScriptLoader } from './strategies/square';\nimport {\n StripeUPEPaymentStrategy,\n StripeScriptLoader as StripeUPEScriptLoader,\n} from './strategies/stripe-upe';\nimport {\n StripeV3PaymentStrategy,\n StripeScriptLoader as StripeV3ScriptLoader,\n} from './strategies/stripev3';\nimport { WepayPaymentStrategy, WepayRiskClient } from './strategies/wepay';\nimport { WorldpayaccessPaymetStrategy } from './strategies/worldpayaccess';\nimport { ZipPaymentStrategy } from './strategies/zip';\n\nexport default function createPaymentStrategyRegistry(\n store: CheckoutStore,\n paymentClient: any,\n requestSender: RequestSender,\n spamProtection: GoogleRecaptcha,\n locale: string,\n) {\n const registry = new PaymentStrategyRegistry(store, {\n defaultToken: PaymentStrategyType.CREDIT_CARD,\n });\n const scriptLoader = getScriptLoader();\n const paymentRequestTransformer = new PaymentRequestTransformer();\n const paymentRequestSender = new PaymentRequestSender(paymentClient);\n const billingAddressActionCreator = new BillingAddressActionCreator(\n new BillingAddressRequestSender(requestSender),\n new SubscriptionsActionCreator(new SubscriptionsRequestSender(requestSender)),\n );\n const paymentIntegrationService = createPaymentIntegrationService(store);\n const registryV2 = createPaymentStrategyRegistryV2(paymentIntegrationService);\n const braintreePaymentProcessor = createBraintreePaymentProcessor(scriptLoader);\n const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n const checkoutValidator = new CheckoutValidator(checkoutRequestSender);\n const spamProtectionActionCreator = new SpamProtectionActionCreator(\n spamProtection,\n new SpamProtectionRequestSender(requestSender),\n );\n const orderActionCreator = new OrderActionCreator(\n new OrderRequestSender(requestSender),\n checkoutValidator,\n );\n const storeCreditActionCreator = new StoreCreditActionCreator(\n new StoreCreditRequestSender(requestSender),\n );\n const paymentHumanVerificationHandler = new PaymentHumanVerificationHandler(\n createSpamProtection(createScriptLoader()),\n );\n const paymentActionCreator = new PaymentActionCreator(\n paymentRequestSender,\n orderActionCreator,\n paymentRequestTransformer,\n paymentHumanVerificationHandler,\n );\n const paymentMethodActionCreator = new PaymentMethodActionCreator(\n new PaymentMethodRequestSender(requestSender),\n );\n const remoteCheckoutRequestSender = new RemoteCheckoutRequestSender(requestSender);\n const configActionCreator = new ConfigActionCreator(new ConfigRequestSender(requestSender));\n const formFieldsActionCreator = new FormFieldsActionCreator(\n new FormFieldsRequestSender(requestSender),\n );\n const checkoutActionCreator = new CheckoutActionCreator(\n checkoutRequestSender,\n configActionCreator,\n formFieldsActionCreator,\n );\n const remoteCheckoutActionCreator = new RemoteCheckoutActionCreator(\n remoteCheckoutRequestSender,\n checkoutActionCreator,\n );\n const paymentStrategyActionCreator = new PaymentStrategyActionCreator(\n registry,\n registryV2,\n orderActionCreator,\n spamProtectionActionCreator,\n );\n const formPoster = createFormPoster();\n const stepHandler = createStepHandler(formPoster, paymentHumanVerificationHandler);\n const hostedFormFactory = new HostedFormFactory(store);\n const storefrontPaymentRequestSender = new StorefrontPaymentRequestSender(requestSender);\n\n registry.register(\n PaymentStrategyType.ADYENV2_GOOGLEPAY,\n () =>\n new GooglePayPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayAdyenV2Initializer()),\n new GooglePayAdyenV2PaymentProcessor(\n store,\n paymentActionCreator,\n new AdyenV2ScriptLoader(scriptLoader, getStylesheetLoader()),\n ),\n ),\n );\n\n registry.register(\n PaymentStrategyType.ADYENV3_GOOGLEPAY,\n () =>\n new GooglePayPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayAdyenV3Initializer()),\n new GooglePayAdyenV3PaymentProcessor(\n store,\n paymentActionCreator,\n new AdyenV3ScriptLoader(scriptLoader, getStylesheetLoader()),\n ),\n ),\n );\n\n registry.register(\n PaymentStrategyType.AFFIRM,\n () =>\n new AffirmPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n paymentMethodActionCreator,\n new AffirmScriptLoader(),\n ),\n );\n\n registry.register(\n PaymentStrategyType.AFTERPAY,\n () =>\n new AfterpayPaymentStrategy(\n store,\n checkoutValidator,\n orderActionCreator,\n paymentActionCreator,\n paymentMethodActionCreator,\n remoteCheckoutRequestSender,\n storeCreditActionCreator,\n new AfterpayScriptLoader(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.AMAZONPAY,\n () =>\n new AmazonPayV2PaymentStrategy(\n store,\n paymentStrategyActionCreator,\n orderActionCreator,\n paymentActionCreator,\n createAmazonPayV2PaymentProcessor(),\n ),\n );\n\n registry.register(\n PaymentStrategyType.AUTHORIZENET_GOOGLE_PAY,\n () =>\n new GooglePayPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayAuthorizeNetInitializer()),\n ),\n );\n\n registry.register(\n PaymentStrategyType.BARCLAYS,\n () =>\n new BarclaysPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n new CardinalThreeDSecureFlowV2(\n store,\n paymentActionCreator,\n new CardinalClient(new CardinalScriptLoader(scriptLoader)),\n ),\n ),\n );\n\n registry.register(\n PaymentStrategyType.BLUESNAPV2,\n () => new BlueSnapV2PaymentStrategy(store, orderActionCreator, paymentActionCreator),\n );\n\n registry.register(\n PaymentStrategyType.BRAINTREE,\n () =>\n new BraintreeCreditCardPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n paymentMethodActionCreator,\n braintreePaymentProcessor,\n ),\n );\n\n registry.register(\n PaymentStrategyType.BRAINTREE_GOOGLE_PAY,\n () =>\n new GooglePayPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createGooglePayPaymentProcessor(\n store,\n new GooglePayBraintreeInitializer(\n new BraintreeSDKCreator(new BraintreeScriptLoader(scriptLoader)),\n ),\n ),\n undefined,\n new BraintreeSDKCreator(new BraintreeScriptLoader(scriptLoader)),\n ),\n );\n\n registry.register(\n PaymentStrategyType.BRAINTREE_PAYPAL,\n () =>\n new BraintreePaypalPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n paymentMethodActionCreator,\n braintreePaymentProcessor,\n ),\n );\n\n registry.register(\n PaymentStrategyType.BRAINTREE_VENMO,\n () =>\n new BraintreeVenmoPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n paymentMethodActionCreator,\n braintreePaymentProcessor,\n ),\n );\n\n registry.register(\n PaymentStrategyType.BRAINTREE_PAYPAL_CREDIT,\n () =>\n new BraintreePaypalPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n paymentMethodActionCreator,\n braintreePaymentProcessor,\n true,\n ),\n );\n\n registry.register(\n PaymentStrategyType.BRAINTREE_VISA_CHECKOUT,\n () =>\n new BraintreeVisaCheckoutPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createBraintreeVisaCheckoutPaymentProcessor(scriptLoader, requestSender),\n new VisaCheckoutScriptLoader(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.CBA_MPGS,\n () =>\n new CBAMPGSPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n paymentMethodActionCreator,\n new CBAMPGSScriptLoader(scriptLoader),\n locale,\n ),\n );\n\n registry.register(\n PaymentStrategyType.CONVERGE,\n () =>\n new ConvergePaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n formPoster,\n ),\n );\n\n registry.register(\n PaymentStrategyType.CLEARPAY,\n () =>\n new ClearpayPaymentStrategy(\n store,\n checkoutValidator,\n orderActionCreator,\n paymentActionCreator,\n paymentMethodActionCreator,\n remoteCheckoutRequestSender,\n storeCreditActionCreator,\n new ClearpayScriptLoader(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.CYBERSOURCE,\n () =>\n new CyberSourcePaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n new CardinalThreeDSecureFlow(\n store,\n paymentActionCreator,\n paymentMethodActionCreator,\n new CardinalClient(new CardinalScriptLoader(scriptLoader)),\n ),\n ),\n );\n\n registry.register(\n PaymentStrategyType.CYBERSOURCEV2,\n () =>\n new CyberSourceV2PaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n new CardinalThreeDSecureFlowV2(\n store,\n paymentActionCreator,\n new CardinalClient(new CardinalScriptLoader(scriptLoader)),\n ),\n ),\n );\n\n registry.register(\n PaymentStrategyType.BNZ,\n () =>\n new BNZPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n new CardinalThreeDSecureFlowV2(\n store,\n paymentActionCreator,\n new CardinalClient(new CardinalScriptLoader(scriptLoader)),\n ),\n ),\n );\n\n registry.register(\n PaymentStrategyType.CYBERSOURCEV2_GOOGLE_PAY,\n () =>\n new GooglePayPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayCybersourceV2Initializer()),\n ),\n );\n\n registry.register(\n PaymentStrategyType.BNZ_GOOGLEPAY,\n () =>\n new GooglePayPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayBNZInitializer()),\n ),\n );\n\n registry.register(\n PaymentStrategyType.CHECKOUTCOM,\n () =>\n new CreditCardRedirectPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n formPoster,\n ),\n );\n\n registry.register(\n PaymentStrategyType.CHECKOUTCOM_APM,\n () =>\n new CheckoutcomAPMPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n ),\n );\n\n registry.register(\n PaymentStrategyType.CHECKOUTCOM_FAWRY,\n () =>\n new CheckoutcomFawryPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n ),\n );\n\n registry.register(\n PaymentStrategyType.CHECKOUTCOM_GOOGLE_PAY,\n () =>\n new GooglePayPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createGooglePayPaymentProcessor(\n store,\n new GooglePayCheckoutcomInitializer(requestSender),\n ),\n new GooglePayCheckoutcomPaymentProcessor(),\n ),\n );\n\n registry.register(\n PaymentStrategyType.CHECKOUTCOM_IDEAL,\n () =>\n new CheckoutcomiDealPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n ),\n );\n\n registry.register(\n PaymentStrategyType.CHECKOUTCOM_SEPA,\n () =>\n new CheckoutcomSEPAPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n ),\n );\n\n registry.register(\n PaymentStrategyType.CHASE_PAY,\n () =>\n new ChasePayPaymentStrategy(\n store,\n checkoutActionCreator,\n orderActionCreator,\n paymentActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n requestSender,\n new ChasePayScriptLoader(scriptLoader),\n new WepayRiskClient(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.DIGITALRIVER,\n () =>\n new DigitalRiverPaymentStrategy(\n store,\n paymentMethodActionCreator,\n orderActionCreator,\n paymentActionCreator,\n storeCreditActionCreator,\n new DigitalRiverScriptLoader(scriptLoader, getStylesheetLoader()),\n billingAddressActionCreator,\n ),\n );\n\n registry.register(\n PaymentStrategyType.KLARNA,\n () =>\n new KlarnaPaymentStrategy(\n store,\n orderActionCreator,\n paymentMethodActionCreator,\n remoteCheckoutActionCreator,\n new KlarnaScriptLoader(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.KLARNAV2,\n () =>\n new KlarnaV2PaymentStrategy(\n store,\n orderActionCreator,\n remoteCheckoutActionCreator,\n new KlarnaV2ScriptLoader(scriptLoader),\n new KlarnaV2TokenUpdater(requestSender),\n ),\n );\n\n registry.register(\n PaymentStrategyType.HUMM,\n () =>\n new HummPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n formPoster,\n paymentMethodActionCreator,\n ),\n );\n\n registry.register(\n PaymentStrategyType.MASTERPASS,\n () =>\n new MasterpassPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n new MasterpassScriptLoader(scriptLoader),\n locale,\n ),\n );\n\n registry.register(\n PaymentStrategyType.MOLLIE,\n () =>\n new MolliePaymentStrategy(\n hostedFormFactory,\n store,\n new MollieScriptLoader(scriptLoader),\n orderActionCreator,\n paymentActionCreator,\n ),\n );\n\n registry.register(\n PaymentStrategyType.MONERIS,\n () =>\n new MonerisPaymentStrategy(\n hostedFormFactory,\n store,\n orderActionCreator,\n paymentActionCreator,\n storeCreditActionCreator,\n ),\n );\n\n registry.register(\n PaymentStrategyType.OPY,\n () =>\n new OpyPaymentStrategy(\n store,\n orderActionCreator,\n paymentMethodActionCreator,\n storefrontPaymentRequestSender,\n paymentActionCreator,\n new OpyScriptLoader(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.ORBITAL_GOOGLE_PAY,\n () =>\n new GooglePayPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayOrbitalInitializer()),\n ),\n );\n\n registry.register(\n PaymentStrategyType.PAYPAL,\n () =>\n new PaypalProPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n new CardinalThreeDSecureFlow(\n store,\n paymentActionCreator,\n paymentMethodActionCreator,\n new CardinalClient(new CardinalScriptLoader(scriptLoader)),\n ),\n ),\n );\n\n registry.register(\n PaymentStrategyType.PAYPAL_EXPRESS,\n () =>\n new PaypalExpressPaymentStrategy(\n store,\n orderActionCreator,\n new PaypalScriptLoader(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.PAYPAL_EXPRESS_CREDIT,\n () =>\n new PaypalExpressPaymentStrategy(\n store,\n orderActionCreator,\n new PaypalScriptLoader(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.PPSDK,\n () =>\n new PPSDKStrategy(\n store,\n orderActionCreator,\n createSubStrategyRegistry(\n store,\n orderActionCreator,\n requestSender,\n stepHandler,\n hostedFormFactory,\n ),\n new PaymentResumer(requestSender, stepHandler),\n new BrowserStorage('PPSDK'),\n ),\n );\n\n registry.register(\n PaymentStrategyType.QUADPAY,\n () =>\n new QuadpayPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n paymentMethodActionCreator,\n storeCreditActionCreator,\n remoteCheckoutActionCreator,\n storefrontPaymentRequestSender,\n ),\n );\n\n registry.register(\n PaymentStrategyType.SAGE_PAY,\n () =>\n new SagePayPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n formPoster,\n ),\n );\n\n registry.register(\n PaymentStrategyType.SQUARE,\n () =>\n new SquarePaymentStrategy(\n store,\n checkoutActionCreator,\n orderActionCreator,\n paymentActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n requestSender,\n new SquareScriptLoader(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.STRIPE_GOOGLE_PAY,\n () =>\n new GooglePayPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayStripeInitializer()),\n ),\n );\n\n registry.register(\n PaymentStrategyType.STRIPE_UPE_GOOGLE_PAY,\n () =>\n new GooglePayPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayStripeUPEInitializer()),\n ),\n );\n\n registry.register(\n PaymentStrategyType.STRIPEV3,\n () =>\n new StripeV3PaymentStrategy(\n store,\n paymentMethodActionCreator,\n paymentActionCreator,\n orderActionCreator,\n new StripeV3ScriptLoader(scriptLoader),\n storeCreditActionCreator,\n hostedFormFactory,\n locale,\n ),\n );\n\n registry.register(\n PaymentStrategyType.STRIPE_UPE,\n () =>\n new StripeUPEPaymentStrategy(\n store,\n paymentMethodActionCreator,\n paymentActionCreator,\n orderActionCreator,\n new StripeUPEScriptLoader(scriptLoader),\n storeCreditActionCreator,\n billingAddressActionCreator,\n ),\n );\n\n registry.register(\n PaymentStrategyType.WE_PAY,\n () =>\n new WepayPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n new WepayRiskClient(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.WORLDPAYACCESS,\n () =>\n new WorldpayaccessPaymetStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n ),\n );\n\n registry.register(\n PaymentStrategyType.WORLDPAYACCESS_GOOGLE_PAY,\n () =>\n new GooglePayPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayWorldpayAccessInitializer()),\n ),\n );\n\n registry.register(\n PaymentStrategyType.ZIP,\n () =>\n new ZipPaymentStrategy(\n store,\n paymentMethodActionCreator,\n storeCreditActionCreator,\n remoteCheckoutActionCreator,\n orderActionCreator,\n storefrontPaymentRequestSender,\n paymentActionCreator,\n ),\n );\n\n return registry;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { Overlay } from '@bigcommerce/checkout-sdk/ui';\n\nimport BraintreeHostedForm from './braintree-hosted-form';\nimport BraintreePaymentProcessor from './braintree-payment-processor';\nimport BraintreeScriptLoader from './braintree-script-loader';\nimport BraintreeSDKCreator from './braintree-sdk-creator';\n\nexport default function createBraintreePaymentProcessor(scriptLoader: ScriptLoader) {\n const braintreeScriptLoader = new BraintreeScriptLoader(scriptLoader);\n const braintreeSDKCreator = new BraintreeSDKCreator(braintreeScriptLoader);\n const braintreeHostedForm = new BraintreeHostedForm(braintreeSDKCreator);\n const overlay = new Overlay();\n\n return new BraintreePaymentProcessor(braintreeSDKCreator, braintreeHostedForm, overlay);\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { CheckoutRequestSender, CheckoutStore } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { PaymentMethodActionCreator, PaymentMethodRequestSender } from '../payment';\nimport { createAmazonPayV2PaymentProcessor } from '../payment/strategies/amazon-pay-v2';\nimport { StripeScriptLoader } from '../payment/strategies/stripe-upe';\n\nimport ConsignmentActionCreator from './consignment-action-creator';\nimport ConsignmentRequestSender from './consignment-request-sender';\nimport ShippingStrategyActionCreator from './shipping-strategy-action-creator';\nimport { ShippingStrategy } from './strategies';\nimport { AmazonPayV2ShippingStrategy } from './strategies/amazon-pay-v2';\nimport { DefaultShippingStrategy } from './strategies/default';\nimport { StripeUPEShippingStrategy } from './strategies/stripe-upe';\n\nexport default function createShippingStrategyRegistry(\n store: CheckoutStore,\n requestSender: RequestSender,\n): Registry {\n const registry = new Registry();\n const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n const consignmentRequestSender = new ConsignmentRequestSender(requestSender);\n const consignmentActionCreator = new ConsignmentActionCreator(\n consignmentRequestSender,\n checkoutRequestSender,\n );\n const paymentMethodActionCreator = new PaymentMethodActionCreator(\n new PaymentMethodRequestSender(requestSender),\n );\n const scriptLoader = getScriptLoader();\n\n registry.register(\n 'amazonpay',\n () =>\n new AmazonPayV2ShippingStrategy(\n store,\n consignmentActionCreator,\n new PaymentMethodActionCreator(new PaymentMethodRequestSender(requestSender)),\n createAmazonPayV2PaymentProcessor(),\n new ShippingStrategyActionCreator(registry),\n ),\n );\n\n registry.register(\n 'stripeupe',\n () =>\n new StripeUPEShippingStrategy(\n store,\n new StripeScriptLoader(scriptLoader),\n consignmentActionCreator,\n paymentMethodActionCreator,\n ),\n );\n\n registry.register(\n 'default',\n () => new DefaultShippingStrategy(store, consignmentActionCreator),\n );\n\n return registry;\n}\n","export interface RootCacheKeyMap {\n maps: ChildCacheKeyMap[];\n}\n\nexport interface IntermediateCacheKeyMap {\n maps: ChildCacheKeyMap[];\n parentMap: RootCacheKeyMap | IntermediateCacheKeyMap;\n usedCount: number;\n value: any;\n}\n\nexport interface TerminalCacheKeyMap extends IntermediateCacheKeyMap {\n cacheKey: string;\n}\n\nexport type ChildCacheKeyMap = IntermediateCacheKeyMap | TerminalCacheKeyMap;\n\nexport function isTerminalCacheKeyMap(map: ChildCacheKeyMap): map is TerminalCacheKeyMap {\n return Object.prototype.hasOwnProperty.call(map, 'cacheKey');\n}\n\nexport function isRootCacheKeyMap(map: RootCacheKeyMap | ChildCacheKeyMap): map is RootCacheKeyMap {\n return Object.prototype.hasOwnProperty.call(map, 'parentMap');\n}\n","import { noop } from 'lodash';\nimport shallowEqual from 'shallowequal';\n\nimport {\n ChildCacheKeyMap,\n IntermediateCacheKeyMap,\n isRootCacheKeyMap,\n isTerminalCacheKeyMap,\n RootCacheKeyMap,\n TerminalCacheKeyMap,\n} from './cache-key-maps';\n\nexport interface CacheKeyResolverOptions {\n maxSize?: number;\n onExpire?(key: string): void;\n isEqual?(valueA: any, valueB: any): boolean;\n}\n\ninterface ResolveResult {\n index: number;\n parentMap: RootCacheKeyMap | IntermediateCacheKeyMap;\n map?: TerminalCacheKeyMap;\n}\n\nexport default class CacheKeyResolver {\n private _lastId = 0;\n private _map: RootCacheKeyMap = { maps: [] };\n private _usedMaps: TerminalCacheKeyMap[] = [];\n private _options: Required;\n\n constructor(options?: CacheKeyResolverOptions) {\n this._options = {\n maxSize: 0,\n isEqual: shallowEqual,\n onExpire: noop,\n ...options,\n };\n }\n\n getKey(...args: any[]): string {\n const result = this._resolveMap(...args);\n const { index, parentMap } = result;\n let { map } = result;\n\n if (map && map.cacheKey) {\n map.usedCount++;\n } else {\n map = this._generateMap(parentMap, args.slice(index));\n }\n\n // Keep track of the least used map so we can remove it if the size of\n // the stack exceeds the maximum size.\n this._removeLeastUsedMap(map);\n\n return map.cacheKey;\n }\n\n getUsedCount(...args: any[]): number {\n const { map } = this._resolveMap(...args);\n\n return map ? map.usedCount : 0;\n }\n\n private _resolveMap(...args: any[]): ResolveResult {\n let index = 0;\n let parentMap = this._map;\n\n // Traverse the tree to find the linked list of maps that match the\n // arguments of the call. Each intermediate or terminal map contains a\n // value that could be used to match with the arguments. The last map in\n // the list (the terminal) should contain a cache key. If it can does\n // not exist, we will return a falsy value so that the caller could\n // handle and generate a new cache key.\n while (parentMap.maps.length) {\n let isMatched = false;\n\n for (let mapIndex = 0; mapIndex < parentMap.maps.length; mapIndex++) {\n const map = parentMap.maps[mapIndex];\n\n if (!this._options.isEqual(map.value, args[index])) {\n continue;\n }\n\n // Move the most recently used map to the top of the stack for\n // quicker access\n parentMap.maps.unshift(...parentMap.maps.splice(mapIndex, 1));\n\n if (\n (args.length === 0 || index === args.length - 1) &&\n isTerminalCacheKeyMap(map)\n ) {\n return { index, map, parentMap };\n }\n\n isMatched = true;\n parentMap = map;\n index++;\n\n break;\n }\n\n if (!isMatched) {\n break;\n }\n }\n\n return { index, parentMap };\n }\n\n private _generateMap(\n parent: RootCacheKeyMap | IntermediateCacheKeyMap,\n args: any[],\n ): TerminalCacheKeyMap {\n let index = 0;\n let parentMap = parent;\n let map: IntermediateCacheKeyMap;\n\n do {\n map = {\n maps: [],\n parentMap,\n usedCount: 1,\n value: args[index],\n };\n\n // Continue to build the tree of maps so that it could be resolved\n // next time when the function is called with the same set of\n // arguments.\n parentMap.maps.unshift(map);\n\n parentMap = map;\n index++;\n } while (index < args.length);\n\n const terminalMap = map as TerminalCacheKeyMap;\n\n terminalMap.cacheKey = `${++this._lastId}`;\n\n return terminalMap;\n }\n\n private _removeLeastUsedMap(recentlyUsedMap: TerminalCacheKeyMap): void {\n if (!this._options.maxSize) {\n return;\n }\n\n const index = this._usedMaps.indexOf(recentlyUsedMap);\n\n this._usedMaps.splice(index === -1 ? 0 : index, index === -1 ? 0 : 1, recentlyUsedMap);\n\n if (this._usedMaps.length <= this._options.maxSize) {\n return;\n }\n\n const map = this._usedMaps.pop();\n\n if (!map) {\n return;\n }\n\n this._removeMap(map);\n this._options.onExpire(map.cacheKey);\n }\n\n private _removeMap(map: ChildCacheKeyMap): void {\n if (!map.parentMap) {\n return;\n }\n\n map.parentMap.maps.splice(map.parentMap.maps.indexOf(map), 1);\n\n if (isRootCacheKeyMap(map.parentMap)) {\n return;\n }\n\n this._removeMap(map.parentMap);\n }\n}\n","import { memoize } from '@bigcommerce/memoize';\n\nimport { bindDecorator, CacheKeyResolver, isEqual, isPrivate } from '../utility';\n\n/**\n * Decorates a class by patching all of its methods to cache their return values\n * and return them if they are called again with the same set of parameters. The\n * decorator also binds all the methods to the calling instance so it can be\n * destructed.\n */\nexport default function selectorDecorator>(target: T): T {\n const decoratedTarget = class extends target {};\n\n Object.getOwnPropertyNames(target.prototype).forEach((key) => {\n const descriptor = Object.getOwnPropertyDescriptor(target.prototype, key);\n\n if (!descriptor || key === 'constructor') {\n return;\n }\n\n Object.defineProperty(\n decoratedTarget.prototype,\n key,\n selectorMethodDecorator(target.prototype, key, descriptor),\n );\n });\n\n return decoratedTarget;\n}\n\nfunction selectorMethodDecorator(\n target: object,\n key: string,\n descriptor: TypedPropertyDescriptor,\n): TypedPropertyDescriptor {\n if (typeof descriptor.value !== 'function') {\n return descriptor;\n }\n\n let resolver = new CacheKeyResolver();\n let method = descriptor.value;\n let memoizedMethod = memoize(method);\n\n return bindDecorator(target, key, {\n get() {\n const value = ((...args: any[]) => {\n const cachedValue = memoizedMethod.call(this, ...args);\n\n if (resolver.getUsedCount(...args) === 1) {\n return cachedValue;\n }\n\n const newValue = method.call(this, ...args);\n\n if (isEqual(newValue, cachedValue, { keyFilter: (key) => !isPrivate(key) })) {\n return cachedValue;\n }\n\n memoizedMethod.cache.set(resolver.getKey(...args), newValue);\n\n return newValue;\n }) as T;\n\n Object.defineProperty(this, key, { ...descriptor, value });\n\n return value;\n },\n set(value) {\n resolver = new CacheKeyResolver();\n method = value;\n memoizedMethod = memoize(method);\n },\n });\n}\n\nexport type Constructor = new (...args: any[]) => T;\ntype Method = (...args: any[]) => any;\n","export default function isPrivate(key: string): boolean {\n return `${key}`.indexOf('$$') === 0 || `${key}`.indexOf('_') === 0;\n}\n","import { InternalCheckoutSelectors } from '../checkout';\nimport { selector } from '../common/selector';\n\nimport CheckoutButtonSelector from './checkout-button-selector';\nimport { CheckoutButtonMethodType } from './strategies';\n\n@selector\nexport default class CheckoutButtonErrorSelector {\n private _checkoutButton: CheckoutButtonSelector;\n\n /**\n * @internal\n */\n constructor(selectors: InternalCheckoutSelectors) {\n this._checkoutButton = selectors.checkoutButton;\n }\n\n getInitializeButtonError(methodId?: CheckoutButtonMethodType): Error | undefined {\n return this._checkoutButton.getInitializeError(methodId);\n }\n\n getDeinitializeButtonError(methodId?: CheckoutButtonMethodType): Error | undefined {\n return this._checkoutButton.getDeinitializeError(methodId);\n }\n}\n","import { InternalCheckoutSelectors } from '../checkout';\nimport { selector } from '../common/selector';\n\nimport CheckoutButtonSelector from './checkout-button-selector';\nimport { CheckoutButtonMethodType } from './strategies';\n\n@selector\nexport default class CheckoutButtonStatusSelector {\n private _checkoutButton: CheckoutButtonSelector;\n\n /**\n * @internal\n */\n constructor(selectors: InternalCheckoutSelectors) {\n this._checkoutButton = selectors.checkoutButton;\n }\n\n isInitializingButton(methodId?: CheckoutButtonMethodType): boolean {\n return this._checkoutButton.isInitializing(methodId);\n }\n\n isDeinitializingButton(methodId?: CheckoutButtonMethodType): boolean {\n return this._checkoutButton.isDeinitializing(methodId);\n }\n}\n","import { InternalCheckoutSelectors } from '../checkout';\n\nimport CheckoutButtonErrorSelector from './checkout-button-error-selector';\nimport CheckoutButtonSelectors from './checkout-button-selectors';\nimport CheckoutButtonStatusSelector from './checkout-button-status-selector';\n\nexport default function createCheckoutButtonSelectors(\n selectors: InternalCheckoutSelectors,\n): CheckoutButtonSelectors {\n const errors = new CheckoutButtonErrorSelector(selectors);\n const statuses = new CheckoutButtonStatusSelector(selectors);\n\n return {\n errors,\n statuses,\n };\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../checkout';\nimport { isElementId, setUniqueElementId } from '../common/dom';\nimport { bindDecorator as bind } from '../common/utility';\n\nimport { CheckoutButtonInitializeOptions, CheckoutButtonOptions } from './checkout-button-options';\nimport CheckoutButtonSelectors from './checkout-button-selectors';\nimport CheckoutButtonStrategyActionCreator from './checkout-button-strategy-action-creator';\nimport createCheckoutButtonSelectors from './create-checkout-button-selectors';\n\n@bind\nexport default class CheckoutButtonInitializer {\n private _state: CheckoutButtonSelectors;\n\n /**\n * @internal\n */\n constructor(\n private _store: CheckoutStore,\n private _buttonStrategyActionCreator: CheckoutButtonStrategyActionCreator,\n ) {\n this._state = createCheckoutButtonSelectors(this._store.getState());\n\n this._store.subscribe((state) => {\n this._state = createCheckoutButtonSelectors(state);\n });\n }\n\n /**\n * Returns a snapshot of the current state.\n *\n * The method returns a new instance every time there is a change in the\n * state. You can query the state by calling any of its getter methods.\n *\n * ```js\n * const state = service.getState();\n *\n * console.log(state.errors.getInitializeButtonError());\n * console.log(state.statuses.isInitializingButton());\n * ```\n *\n * @returns The current customer's checkout state\n */\n getState(): CheckoutButtonSelectors {\n return this._state;\n }\n\n /**\n * Subscribes to any changes to the current state.\n *\n * The method registers a callback function and executes it every time there\n * is a change in the current state.\n *\n * ```js\n * service.subscribe(state => {\n * console.log(state.statuses.isInitializingButton());\n * });\n * ```\n *\n * The method can be configured to notify subscribers only regarding\n * relevant changes, by providing a filter function.\n *\n * ```js\n * const filter = state => state.errors.getInitializeButtonError();\n *\n * // Only trigger the subscriber when the cart changes.\n * service.subscribe(state => {\n * console.log(state.errors.getInitializeButtonError())\n * }, filter);\n * ```\n *\n * @param subscriber - The function to subscribe to state changes.\n * @param filters - One or more functions to filter out irrelevant state\n * changes. If more than one function is provided, the subscriber will only\n * be triggered if all conditions are met.\n * @returns A function, if called, will unsubscribe the subscriber.\n */\n subscribe(\n subscriber: (state: CheckoutButtonSelectors) => void,\n ...filters: Array<(state: CheckoutButtonSelectors) => any>\n ): () => void {\n return this._store.subscribe(\n () => subscriber(this.getState()),\n (state) => state.checkoutButton.getState(),\n ...filters.map(\n (filter) => (state: InternalCheckoutSelectors) =>\n filter(createCheckoutButtonSelectors(state)),\n ),\n );\n }\n\n /**\n * Initializes the checkout button of a payment method.\n *\n * When the checkout button is initialized, it will be inserted into the DOM,\n * ready to be interacted with by the customer.\n *\n * ```js\n * initializer.initializeButton({\n * methodId: 'braintreepaypal',\n * containerId: 'checkoutButton',\n * braintreepaypal: {\n * },\n * });\n * ```\n *\n * @param options - Options for initializing the checkout button.\n * @returns A promise that resolves to the current state.\n */\n initializeButton(options: CheckoutButtonInitializeOptions): Promise {\n const containerIds = isElementId(options.containerId)\n ? [options.containerId]\n : setUniqueElementId(options.containerId, `${options.methodId}-container`);\n\n return Promise.all(\n containerIds.map((containerId) => {\n const action = this._buttonStrategyActionCreator.initialize({\n ...options,\n containerId,\n });\n const queueId = `checkoutButtonStrategy:${options.methodId}:${containerId}`;\n\n return this._store.dispatch(action, { queueId });\n }),\n ).then(() => this.getState());\n }\n\n /**\n * De-initializes the checkout button by performing any necessary clean-ups.\n *\n * ```js\n * await service.deinitializeButton({\n * methodId: 'braintreepaypal',\n * });\n * ```\n *\n * @param options - Options for deinitializing the checkout button.\n * @returns A promise that resolves to the current state.\n */\n deinitializeButton(options: CheckoutButtonOptions): Promise {\n const action = this._buttonStrategyActionCreator.deinitialize(options);\n const queueId = `checkoutButtonStrategy:${options.methodId}`;\n\n return this._store.dispatch(action, { queueId }).then(() => this.getState());\n }\n}\n","/* eslint-disable no-useless-escape */\nexport default function isElementId(id: string): boolean {\n return /^\\w[\\w\\-\\:\\.]*$/.test(id);\n}\n","import { uniqueId } from 'lodash';\n\nimport { InvalidArgumentError } from '../error/errors';\n\nexport default function setUniqueElementId(selector: string, idPrefix: string): string[] {\n const containers = document.querySelectorAll(selector);\n\n if (!containers.length) {\n throw new InvalidArgumentError(\n `Unable to find any element with the specified selector: ${selector}`,\n );\n }\n\n return Array.prototype.slice.call(containers).map((container: HTMLElement) => {\n if (!container.id) {\n container.id = uniqueId(idPrefix);\n }\n\n return container.id;\n });\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, empty, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { CheckoutButtonStrategy as CheckoutButtonStrategyV2 } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { Registry } from '../common/registry';\nimport { PaymentMethodActionCreator } from '../payment';\n\nimport {\n CheckoutButtonActionType,\n DeinitializeButtonAction,\n InitializeButtonAction,\n} from './checkout-button-actions';\nimport { CheckoutButtonInitializeOptions, CheckoutButtonOptions } from './checkout-button-options';\nimport CheckoutButtonRegistryV2 from './checkout-button-strategy-registry-v2';\nimport { CheckoutButtonMethodType, CheckoutButtonStrategy } from './strategies';\n\nexport default class CheckoutButtonStrategyActionCreator {\n constructor(\n private _registry: Registry,\n private _registryV2: CheckoutButtonRegistryV2,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n ) {}\n\n initialize(\n options: CheckoutButtonInitializeOptions,\n ): ThunkAction {\n return (store) => {\n const meta = {\n methodId: options.methodId,\n containerId: options.containerId,\n };\n\n if (\n store.getState().checkoutButton.isInitialized(options.methodId, options.containerId)\n ) {\n return empty();\n }\n\n const paymentMethodRequestParams = options.currencyCode\n ? { params: { currencyCode: options.currencyCode } }\n : {};\n\n const paymentMethodRequestOptions = {\n ...paymentMethodRequestParams,\n timeout: options.timeout,\n useCache: true,\n };\n\n return concat(\n of(\n createAction(\n CheckoutButtonActionType.InitializeButtonRequested,\n undefined,\n meta,\n ),\n ),\n this._paymentMethodActionCreator.loadPaymentMethod(\n options.methodId,\n paymentMethodRequestOptions,\n )(store),\n defer(() =>\n this._getStrategy(options.methodId)\n .initialize(options)\n .then(() =>\n createAction(\n CheckoutButtonActionType.InitializeButtonSucceeded,\n undefined,\n meta,\n ),\n ),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CheckoutButtonActionType.InitializeButtonFailed, error, meta),\n ),\n );\n };\n }\n\n deinitialize(\n options: CheckoutButtonOptions,\n ): ThunkAction {\n return (store) => {\n const meta = { methodId: options.methodId };\n\n if (!store.getState().checkoutButton.isInitialized(options.methodId)) {\n return empty();\n }\n\n return concat(\n of(\n createAction(\n CheckoutButtonActionType.DeinitializeButtonRequested,\n undefined,\n meta,\n ),\n ),\n defer(() =>\n this._getStrategy(options.methodId)\n .deinitialize()\n .then(() =>\n createAction(\n CheckoutButtonActionType.DeinitializeButtonSucceeded,\n undefined,\n meta,\n ),\n ),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(\n CheckoutButtonActionType.DeinitializeButtonFailed,\n error,\n meta,\n ),\n ),\n );\n };\n }\n\n private _getStrategy(\n methodId: CheckoutButtonMethodType,\n ): CheckoutButtonStrategy | CheckoutButtonStrategyV2 {\n let strategy: CheckoutButtonStrategy | CheckoutButtonStrategyV2;\n\n try {\n strategy = this._registryV2.get({ id: methodId });\n } catch {\n strategy = this._registry.get(methodId);\n }\n\n return strategy;\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when a shopper tries to sign in as a guest but\n * they are already signed in as a registered customer.\n */\nexport default class BuyNowCartCreationError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'An unexpected error has occurred during buy now cart creation process. Please try again later.',\n );\n\n this.name = 'BuyNowCartCreationError';\n this.type = 'buy_now_cart_creation_error';\n }\n}\n","import { BuyNowCartRequestBody } from '../../../cart';\nimport {\n AmazonPayV2ButtonConfig,\n AmazonPayV2ButtonParameters,\n} from '../../../payment/strategies/amazon-pay-v2';\n\nexport function isWithBuyNowFeatures(options: unknown): options is WithBuyNowFeature {\n if (!(options instanceof Object)) {\n return false;\n }\n\n return 'buyNowInitializeOptions' in options;\n}\n\nexport interface WithBuyNowFeature extends AmazonPayV2ButtonConfig {\n /**\n * The options that are required to initialize Buy Now functionality.\n */\n buyNowInitializeOptions?: {\n getBuyNowCartRequestBody?(): BuyNowCartRequestBody | void;\n };\n}\n\n/**\n * The required config to render the AmazonPayV2 button.\n */\nexport type AmazonPayV2ButtonInitializeOptions = AmazonPayV2ButtonParameters | WithBuyNowFeature;\n","import { StandardError } from '../../../../common/error/errors';\n\nexport default class AmazonPayV2ConfigCreationError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'An unexpected error has occurred during config creation process. Please try again later.',\n );\n\n this.name = 'AmazonPayV2ConfigCreationError';\n this.type = 'amazon_pay_v2_config_creation_error';\n }\n}\n","import { CartRequestSender } from '../../../cart';\nimport BuyNowCartRequestBody from '../../../cart/buy-now-cart-request-body';\nimport { BuyNowCartCreationError } from '../../../cart/errors';\nimport { CheckoutActionCreator, CheckoutStore } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../../../common/error/errors';\nimport {\n AmazonPayV2CheckoutSessionConfig,\n AmazonPayV2PaymentProcessor,\n AmazonPayV2PayOptions,\n AmazonPayV2Placement,\n} from '../../../payment/strategies/amazon-pay-v2';\nimport { getShippableItemsCount } from '../../../shipping';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nimport { isWithBuyNowFeatures } from './amazon-pay-v2-button-options';\nimport AmazonPayV2RequestSender from './amazon-pay-v2-request-sender';\nimport AmazonPayV2ConfigCreationError from './errors/amazon-pay-v2-config-creation-error';\n\nexport default class AmazonPayV2ButtonStrategy implements CheckoutButtonStrategy {\n private _buyNowCartRequestBody?: BuyNowCartRequestBody | void;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _amazonPayV2PaymentProcessor: AmazonPayV2PaymentProcessor,\n private _cartRequestSender: CartRequestSender,\n private _amazonPayV2ConfigRequestSender: AmazonPayV2RequestSender,\n ) {}\n\n async initialize(options: CheckoutButtonInitializeOptions): Promise {\n const { methodId, containerId, amazonpay } = options;\n const { buttonColor } = amazonpay || {};\n\n if (!methodId || !containerId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" or \"containerId\" argument is not provided.',\n );\n }\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n\n await this._amazonPayV2PaymentProcessor.initialize(getPaymentMethodOrThrow(methodId));\n\n if (!amazonpay) {\n await this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout());\n }\n\n const initializeAmazonButtonOptions = isWithBuyNowFeatures(amazonpay)\n ? undefined\n : amazonpay;\n\n if (\n isWithBuyNowFeatures(amazonpay) &&\n typeof amazonpay?.buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function'\n ) {\n this._buyNowCartRequestBody =\n amazonpay.buyNowInitializeOptions.getBuyNowCartRequestBody();\n\n if (this._buyNowCartRequestBody) {\n this._amazonPayV2PaymentProcessor.setCartRequestBody(this._buyNowCartRequestBody);\n }\n }\n\n this._amazonPayV2PaymentProcessor.renderAmazonPayButton({\n checkoutState: this._store.getState(),\n containerId,\n methodId,\n options: initializeAmazonButtonOptions,\n placement: AmazonPayV2Placement.Cart,\n buttonColor,\n });\n\n if (this._buyNowCartRequestBody) {\n this._amazonPayV2PaymentProcessor.prepareCheckoutWithCreationRequestConfig(\n this._getCheckoutCreationRequestConfig.bind(this),\n );\n }\n }\n\n deinitialize(): Promise {\n return this._amazonPayV2PaymentProcessor.deinitialize();\n }\n\n private async _createBuyNowCart() {\n if (!this._buyNowCartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n const { body: buyNowCart } = await this._cartRequestSender.createBuyNowCart(\n this._buyNowCartRequestBody,\n );\n\n return buyNowCart;\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n\n private async _createCheckoutConfig(\n id: string,\n ): Promise> {\n try {\n const {\n body: { payload, public_key, ...rest },\n } = await this._amazonPayV2ConfigRequestSender.createCheckoutConfig(id);\n\n return {\n payloadJSON: payload,\n publicKeyId: public_key,\n ...rest,\n };\n } catch (error) {\n throw new AmazonPayV2ConfigCreationError();\n }\n }\n\n private async _getCheckoutCreationRequestConfig() {\n const buyNowCart = await this._createBuyNowCart();\n\n const estimatedOrderAmount = {\n amount: String(buyNowCart.baseAmount),\n currencyCode: buyNowCart.currency.code,\n };\n\n const createCheckoutSessionConfig = await this._createCheckoutConfig(buyNowCart.id);\n\n return {\n createCheckoutSessionConfig,\n estimatedOrderAmount,\n productType:\n getShippableItemsCount(buyNowCart) === 0\n ? AmazonPayV2PayOptions.PayOnly\n : AmazonPayV2PayOptions.PayAndShip,\n };\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { ContentType, INTERNAL_USE_ONLY, SDK_VERSION_HEADERS } from '../../../common/http-request';\n\nexport interface CheckoutConfig {\n payload: string;\n signature: string;\n public_key: string;\n}\n\nexport default class AmazonPayV2RequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n createCheckoutConfig(cartId: string | number): Promise> {\n const body = { cartId };\n const headers = {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n 'Content-Type': ContentType.Json,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post('/api/storefront/payment/amazonpay', { headers, body });\n }\n}\n","import { isNil, omitBy } from 'lodash';\n\nimport { PaypalStyleOptions } from '../../../payment/strategies/paypal';\n\nexport default function getValidButtonStyle(style: PaypalStyleOptions): PaypalStyleOptions {\n const { color, fundingicons, height, layout, shape, size, tagline } = style;\n\n const validStyles = {\n color,\n fundingicons,\n height: getValidHeight(height),\n layout,\n shape: shape || 'rect',\n size,\n tagline,\n };\n\n return omitBy(validStyles, isNil);\n}\n\nfunction getValidHeight(height?: number): number {\n const minHeight = 25;\n const maxHeight = 55;\n\n if (typeof height !== 'number' || height > maxHeight) {\n return maxHeight;\n }\n\n if (height < minHeight) {\n return minHeight;\n }\n\n return height;\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { Cart, CartRequestSender } from '../../../cart';\nimport { BuyNowCartCreationError } from '../../../cart/errors';\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n StandardError,\n} from '../../../common/error/errors';\nimport PaymentMethod from '../../../payment/payment-method';\nimport {\n BraintreeError,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeSDKCreator,\n BraintreeTokenizePayload,\n mapToBraintreeShippingAddressOverride,\n} from '../../../payment/strategies/braintree';\nimport { PaypalAuthorizeData, PaypalHostWindow } from '../../../payment/strategies/paypal';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nimport { BraintreePaypalButtonInitializeOptions } from './braintree-paypal-button-options';\nimport getValidButtonStyle from './get-valid-button-style';\nimport mapToLegacyBillingAddress from './map-to-legacy-billing-address';\nimport mapToLegacyShippingAddress from './map-to-legacy-shipping-address';\n\ntype BuyNowInitializeOptions = Pick<\n BraintreePaypalButtonInitializeOptions,\n 'buyNowInitializeOptions'\n>;\n\nexport default class BraintreePaypalButtonStrategy implements CheckoutButtonStrategy {\n private _buyNowCart?: Cart;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _cartRequestSender: CartRequestSender,\n private _braintreeSDKCreator: BraintreeSDKCreator,\n private _formPoster: FormPoster,\n private _window: PaypalHostWindow,\n ) {}\n\n async initialize(options: CheckoutButtonInitializeOptions): Promise {\n const { braintreepaypal, containerId, methodId } = options;\n const { messagingContainerId, onError } = braintreepaypal || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!braintreepaypal) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypal\" argument is not provided.`,\n );\n }\n\n let state: InternalCheckoutSelectors;\n let paymentMethod: PaymentMethod;\n let currencyCode: string;\n\n if (braintreepaypal.buyNowInitializeOptions) {\n state = this._store.getState();\n paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n if (!braintreepaypal.currencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypal.currencyCode\" argument is not provided.`,\n );\n }\n\n currencyCode = braintreepaypal.currencyCode;\n } else {\n state = await this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout());\n paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n currencyCode = state.cart.getCartOrThrow().currency.code;\n }\n\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const paypalCheckoutOptions: Partial = {\n currency: currencyCode,\n intent: paymentMethod.initializationData?.intent,\n isCreditEnabled: paymentMethod.initializationData?.isCreditEnabled,\n };\n\n const paypalCheckoutSuccessCallback = (\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n this._renderPayPalComponents(\n braintreePaypalCheckout,\n braintreepaypal,\n containerId,\n methodId,\n Boolean(paymentMethod.config.testMode),\n );\n };\n const paypalCheckoutErrorCallback = (error: BraintreeError) =>\n this._handleError(error, containerId, messagingContainerId, onError);\n\n this._braintreeSDKCreator.initialize(paymentMethod.clientToken);\n await this._braintreeSDKCreator.getPaypalCheckout(\n paypalCheckoutOptions,\n paypalCheckoutSuccessCallback,\n paypalCheckoutErrorCallback,\n );\n }\n\n deinitialize(): Promise {\n this._braintreeSDKCreator.teardown();\n\n return Promise.resolve();\n }\n\n private _renderPayPalComponents(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypal: BraintreePaypalButtonInitializeOptions,\n containerId: string,\n methodId: string,\n testMode: boolean,\n ): void {\n const { messagingContainerId } = braintreepaypal;\n\n this._renderPayPalMessages(messagingContainerId);\n this._renderPayPalButton(\n braintreePaypalCheckout,\n braintreepaypal,\n containerId,\n methodId,\n testMode,\n );\n }\n\n private _renderPayPalButton(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypal: BraintreePaypalButtonInitializeOptions,\n containerId: string,\n methodId: string,\n testMode: boolean,\n ): void {\n const { style, shouldProcessPayment, onAuthorizeError } = braintreepaypal;\n\n const { paypal } = this._window;\n const fundingSource = paypal?.FUNDING.PAYPAL;\n\n if (paypal && fundingSource) {\n const validButtonStyle = style ? getValidButtonStyle(style) : {};\n\n const paypalButtonRender = paypal.Buttons({\n env: testMode ? 'sandbox' : 'production',\n commit: false,\n fundingSource,\n style: validButtonStyle,\n createOrder: () =>\n this._setupPayment(braintreePaypalCheckout, braintreepaypal, methodId),\n onApprove: (authorizeData: PaypalAuthorizeData) =>\n this._tokenizePayment(\n authorizeData,\n braintreePaypalCheckout,\n methodId,\n shouldProcessPayment,\n onAuthorizeError,\n ),\n });\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${containerId}`);\n }\n } else {\n this._removeElement(containerId);\n }\n }\n\n private _renderPayPalMessages(messagingContainerId?: string): void {\n const isMessageContainerAvailable =\n messagingContainerId && Boolean(document.getElementById(messagingContainerId));\n const { paypal } = this._window;\n\n if (paypal && isMessageContainerAvailable) {\n const state = this._store.getState();\n const cart = state.cart.getCartOrThrow();\n\n const paypalMessagesRender = paypal.Messages({\n amount: cart.cartAmount,\n placement: 'cart',\n });\n\n paypalMessagesRender.render(`#${messagingContainerId}`);\n } else {\n this._removeElement(messagingContainerId);\n }\n }\n\n private async _setupPayment(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypal: BraintreePaypalButtonInitializeOptions,\n methodId: string,\n ): Promise {\n const { buyNowInitializeOptions, shippingAddress, onPaymentError } = braintreepaypal;\n let state: InternalCheckoutSelectors;\n\n try {\n this._buyNowCart = await this._createBuyNowCart({ buyNowInitializeOptions });\n\n if (this._buyNowCart) {\n state = this._store.getState();\n } else {\n state = await this._store.dispatch(\n this._checkoutActionCreator.loadDefaultCheckout(),\n );\n }\n\n const customer = state.customer.getCustomer();\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n const amount = this._buyNowCart\n ? this._buyNowCart.cartAmount\n : state.checkout.getCheckoutOrThrow().outstandingBalance;\n const currencyCode =\n braintreepaypal.currencyCode ?? state.config.getStoreConfigOrThrow().currency.code;\n\n const address = shippingAddress || customer?.addresses[0];\n const shippingAddressOverride = address\n ? mapToBraintreeShippingAddressOverride(address)\n : undefined;\n\n return await braintreePaypalCheckout.createPayment({\n flow: 'checkout',\n enableShippingAddress: true,\n shippingAddressEditable: false,\n shippingAddressOverride,\n amount,\n currency: currencyCode,\n offerCredit: false,\n intent: paymentMethod.initializationData?.intent,\n });\n } catch (error) {\n if (onPaymentError) {\n onPaymentError(error);\n }\n\n throw error;\n }\n }\n\n private async _createBuyNowCart({ buyNowInitializeOptions }: BuyNowInitializeOptions) {\n if (typeof buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function') {\n const cartRequestBody = buyNowInitializeOptions.getBuyNowCartRequestBody();\n\n if (!cartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n const { body: cart } = await this._cartRequestSender.createBuyNowCart(\n cartRequestBody,\n );\n\n return cart;\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n }\n\n private async _tokenizePayment(\n authorizeData: PaypalAuthorizeData,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n methodId: string,\n shouldProcessPayment?: boolean,\n onError?: (error: BraintreeError | StandardError) => void,\n ): Promise {\n try {\n const { deviceData } = await this._braintreeSDKCreator.getDataCollector({\n paypal: true,\n });\n const tokenizePayload = await braintreePaypalCheckout.tokenizePayment(authorizeData);\n const { details, nonce } = tokenizePayload;\n const buyNowCartId = this._buyNowCart?.id;\n\n this._formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n provider: methodId,\n action: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n nonce,\n device_data: deviceData,\n billing_address: JSON.stringify(mapToLegacyBillingAddress(details)),\n shipping_address: JSON.stringify(mapToLegacyShippingAddress(details)),\n ...(buyNowCartId && { cart_id: buyNowCartId }),\n });\n\n return tokenizePayload;\n } catch (error) {\n if (onError) {\n onError(error);\n }\n\n throw error;\n }\n }\n\n private _handleError(\n error: BraintreeError,\n buttonContainerId: string,\n messagingContainerId?: string,\n onErrorCallback?: (error: BraintreeError) => void,\n ): void {\n this._removeElement(buttonContainerId);\n this._removeElement(messagingContainerId);\n\n if (onErrorCallback) {\n onErrorCallback(error);\n }\n }\n\n private _removeElement(elementId?: string): void {\n const element = elementId && document.getElementById(elementId);\n\n if (element) {\n element.remove();\n }\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { Cart, CartRequestSender } from '../../../cart';\nimport { BuyNowCartCreationError } from '../../../cart/errors';\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n StandardError,\n} from '../../../common/error/errors';\nimport PaymentMethod from '../../../payment/payment-method';\nimport {\n BraintreeError,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeSDKCreator,\n BraintreeTokenizePayload,\n mapToBraintreeShippingAddressOverride,\n} from '../../../payment/strategies/braintree';\nimport {\n PaypalAuthorizeData,\n PaypalButtonStyleLabelOption,\n PaypalHostWindow,\n} from '../../../payment/strategies/paypal';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nimport { BraintreePaypalCreditButtonInitializeOptions } from './braintree-paypal-credit-button-options';\nimport getValidButtonStyle from './get-valid-button-style';\nimport mapToLegacyBillingAddress from './map-to-legacy-billing-address';\nimport mapToLegacyShippingAddress from './map-to-legacy-shipping-address';\n\ntype BuyNowInitializeOptions = Pick<\n BraintreePaypalCreditButtonInitializeOptions,\n 'buyNowInitializeOptions'\n>;\n\nexport default class BraintreePaypalCreditButtonStrategy implements CheckoutButtonStrategy {\n private _buyNowCart?: Cart;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _cartRequestSender: CartRequestSender,\n private _braintreeSDKCreator: BraintreeSDKCreator,\n private _formPoster: FormPoster,\n private _window: PaypalHostWindow,\n ) {}\n\n async initialize(options: CheckoutButtonInitializeOptions): Promise {\n const { braintreepaypalcredit, containerId, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!braintreepaypalcredit) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypalcredit\" argument is not provided.`,\n );\n }\n\n let state: InternalCheckoutSelectors;\n let paymentMethod: PaymentMethod;\n let currencyCode: string;\n\n if (braintreepaypalcredit.buyNowInitializeOptions) {\n state = this._store.getState();\n paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n if (!braintreepaypalcredit.currencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypalcredit.currencyCode\" argument is not provided.`,\n );\n }\n\n currencyCode = braintreepaypalcredit.currencyCode;\n } else {\n state = await this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout());\n paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n currencyCode = state.cart.getCartOrThrow().currency.code;\n }\n\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const paypalCheckoutOptions: Partial = {\n currency: currencyCode,\n intent: paymentMethod.initializationData?.intent,\n isCreditEnabled: paymentMethod.initializationData?.isCreditEnabled,\n };\n\n const paypalCheckoutCallback = (braintreePaypalCheckout: BraintreePaypalCheckout) =>\n this._renderPayPalButton(\n braintreePaypalCheckout,\n braintreepaypalcredit,\n containerId,\n methodId,\n Boolean(paymentMethod.config.testMode),\n );\n const paypalCheckoutErrorCallback = (error: BraintreeError) =>\n this._handleError(error, containerId, braintreepaypalcredit.onError);\n\n this._braintreeSDKCreator.initialize(paymentMethod.clientToken);\n await this._braintreeSDKCreator.getPaypalCheckout(\n paypalCheckoutOptions,\n paypalCheckoutCallback,\n paypalCheckoutErrorCallback,\n );\n }\n\n deinitialize(): Promise {\n this._braintreeSDKCreator.teardown();\n\n return Promise.resolve();\n }\n\n private _renderPayPalButton(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypalcredit: BraintreePaypalCreditButtonInitializeOptions,\n containerId: string,\n methodId: string,\n testMode: boolean,\n ): void {\n const { style, shouldProcessPayment, onAuthorizeError } = braintreepaypalcredit;\n const { paypal } = this._window;\n\n let hasRenderedSmartButton = false;\n\n if (paypal) {\n const fundingSources = [paypal.FUNDING.PAYLATER, paypal.FUNDING.CREDIT];\n const commonButtonStyle = style ? getValidButtonStyle(style) : {};\n\n fundingSources.forEach((fundingSource) => {\n const buttonStyle =\n fundingSource === paypal.FUNDING.CREDIT\n ? { label: PaypalButtonStyleLabelOption.CREDIT, ...commonButtonStyle }\n : commonButtonStyle;\n\n if (!hasRenderedSmartButton) {\n const paypalButtonRender = paypal.Buttons({\n env: testMode ? 'sandbox' : 'production',\n commit: false,\n fundingSource,\n style: buttonStyle,\n createOrder: () =>\n this._setupPayment(\n braintreePaypalCheckout,\n braintreepaypalcredit,\n methodId,\n ),\n onApprove: (authorizeData: PaypalAuthorizeData) =>\n this._tokenizePayment(\n authorizeData,\n braintreePaypalCheckout,\n methodId,\n shouldProcessPayment,\n onAuthorizeError,\n ),\n });\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${containerId}`);\n hasRenderedSmartButton = true;\n }\n }\n });\n }\n\n if (!paypal || !hasRenderedSmartButton) {\n this._removeElement(containerId);\n }\n }\n\n private async _setupPayment(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypalcredit: BraintreePaypalCreditButtonInitializeOptions,\n methodId: string,\n ): Promise {\n const { onPaymentError, shippingAddress, buyNowInitializeOptions } = braintreepaypalcredit;\n let state: InternalCheckoutSelectors;\n\n try {\n this._buyNowCart = await this._createBuyNowCart({ buyNowInitializeOptions });\n\n if (this._buyNowCart) {\n state = this._store.getState();\n } else {\n state = await this._store.dispatch(\n this._checkoutActionCreator.loadDefaultCheckout(),\n );\n }\n\n const customer = state.customer.getCustomer();\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n const amount = this._buyNowCart\n ? this._buyNowCart.cartAmount\n : state.checkout.getCheckoutOrThrow().outstandingBalance;\n const currencyCode =\n braintreepaypalcredit.currencyCode ??\n state.config.getStoreConfigOrThrow().currency.code;\n\n const address = shippingAddress || customer?.addresses[0];\n const shippingAddressOverride = address\n ? mapToBraintreeShippingAddressOverride(address)\n : undefined;\n\n return await braintreePaypalCheckout.createPayment({\n flow: 'checkout',\n enableShippingAddress: true,\n shippingAddressEditable: false,\n shippingAddressOverride,\n amount,\n currency: currencyCode,\n offerCredit: true,\n intent: paymentMethod.initializationData?.intent,\n });\n } catch (error) {\n if (onPaymentError) {\n onPaymentError(error);\n }\n\n throw error;\n }\n }\n\n private async _createBuyNowCart({ buyNowInitializeOptions }: BuyNowInitializeOptions) {\n if (typeof buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function') {\n const cartRequestBody = buyNowInitializeOptions.getBuyNowCartRequestBody();\n\n if (!cartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n const { body: buyNowCart } = await this._cartRequestSender.createBuyNowCart(\n cartRequestBody,\n );\n\n return buyNowCart;\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n }\n\n private async _tokenizePayment(\n authorizeData: PaypalAuthorizeData,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n methodId: string,\n shouldProcessPayment?: boolean,\n onError?: (error: BraintreeError | StandardError) => void,\n ): Promise {\n try {\n const { deviceData } = await this._braintreeSDKCreator.getDataCollector({\n paypal: true,\n });\n const tokenizePayload = await braintreePaypalCheckout.tokenizePayment(authorizeData);\n const { details, nonce } = tokenizePayload;\n const buyNowCartId = this._buyNowCart?.id;\n\n this._formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n provider: methodId,\n action: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n nonce,\n device_data: deviceData,\n billing_address: JSON.stringify(mapToLegacyBillingAddress(details)),\n shipping_address: JSON.stringify(mapToLegacyShippingAddress(details)),\n ...(buyNowCartId && { cart_id: buyNowCartId }),\n });\n\n return tokenizePayload;\n } catch (error) {\n if (onError) {\n onError(error);\n }\n\n throw error;\n }\n }\n\n private _handleError(\n error: BraintreeError,\n containerId: string,\n onErrorCallback?: (error: BraintreeError) => void,\n ): void {\n this._removeElement(containerId);\n\n if (onErrorCallback) {\n onErrorCallback(error);\n }\n }\n\n private _removeElement(elementId?: string): void {\n const element = elementId && document.getElementById(elementId);\n\n if (element) {\n element.remove();\n }\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { noop } from 'lodash';\n\nimport { BuyNowCartRequestBody, CartRequestSender } from '../../../cart';\nimport { BuyNowCartCreationError } from '../../../cart/errors';\nimport { CheckoutStore } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n UnsupportedBrowserError,\n} from '../../../common/error/errors';\nimport { PaymentMethodActionCreator } from '../../../payment';\nimport {\n BraintreeError,\n BraintreeSDKCreator,\n BraintreeTokenizePayload,\n BraintreeVenmoCheckout,\n} from '../../../payment/strategies/braintree';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\nimport { CheckoutButtonMethodType } from '../index';\n\nimport mapToLegacyBillingAddress from './map-to-legacy-billing-address';\nimport mapToLegacyShippingAddress from './map-to-legacy-shipping-address';\n\nconst venmoButtonStyle = {\n backgroundColor: '#3D95CE',\n backgroundPosition: '50% 50%',\n backgroundSize: '80px auto',\n backgroundImage: 'url(\"/app/assets/img/payment-providers/venmo-logo-white.svg\")',\n backgroundRepeat: 'no-repeat',\n borderRadius: '4px',\n cursor: 'pointer',\n transition: '0.2s ease',\n minHeight: '40px',\n minWidth: '150px',\n height: '100%',\n width: '100%',\n};\n\nconst venmoButtonStyleHover = {\n backgroundColor: '#0a7fc2',\n};\n\ninterface BuyNowInitializeOptions {\n getBuyNowCartRequestBody?(): BuyNowCartRequestBody | void;\n}\n\nexport default class BraintreeVenmoButtonStrategy implements CheckoutButtonStrategy {\n private _onError = noop;\n\n constructor(\n private _store: CheckoutStore,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _cartRequestSender: CartRequestSender,\n private _braintreeSDKCreator: BraintreeSDKCreator,\n private _formPoster: FormPoster,\n ) {}\n\n async initialize(options: CheckoutButtonInitializeOptions): Promise {\n const { braintreevenmo, containerId, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n this._onError = braintreevenmo?.onError || this._handleError;\n\n this._braintreeSDKCreator.initialize(paymentMethod.clientToken);\n await this._braintreeSDKCreator.getVenmoCheckout(\n (braintreeVenmoCheckout) =>\n this._handleInitializationVenmoSuccess(\n braintreeVenmoCheckout,\n containerId,\n braintreevenmo?.buyNowInitializeOptions,\n ),\n (error) => this._handleInitializationVenmoError(error, containerId),\n );\n }\n\n deinitialize(): Promise {\n this._braintreeSDKCreator.teardown();\n\n return Promise.resolve();\n }\n\n private _handleError(error: BraintreeError) {\n throw new Error(error.message);\n }\n\n private _handleInitializationVenmoSuccess(\n braintreeVenmoCheckout: BraintreeVenmoCheckout,\n parentContainerId: string,\n buyNowInitializeOptions?: BuyNowInitializeOptions,\n ): void {\n return this._renderVenmoButton(\n braintreeVenmoCheckout,\n parentContainerId,\n buyNowInitializeOptions,\n );\n }\n\n private _handleInitializationVenmoError(\n error: BraintreeError | UnsupportedBrowserError,\n containerId: string,\n ): void {\n this._removeVenmoContainer(containerId);\n\n return this._onError(error);\n }\n\n private _removeVenmoContainer(containerId: string): void {\n const buttonContainer = document.getElementById(containerId);\n\n if (buttonContainer) {\n buttonContainer.remove();\n }\n }\n\n private _renderVenmoButton(\n braintreeVenmoCheckout: BraintreeVenmoCheckout,\n containerId: string,\n buyNowInitializeOptions?: BuyNowInitializeOptions,\n ): void {\n const venmoButton = document.getElementById(containerId);\n\n if (!venmoButton) {\n throw new InvalidArgumentError(\n 'Unable to create wallet button without valid container ID.',\n );\n }\n\n venmoButton.setAttribute('aria-label', 'Venmo');\n Object.assign(venmoButton.style, venmoButtonStyle);\n\n venmoButton.addEventListener('click', async () => {\n venmoButton.setAttribute('disabled', 'true');\n\n const buyBowCart = await this._createBuyNowCart(buyNowInitializeOptions);\n\n if (braintreeVenmoCheckout.tokenize) {\n braintreeVenmoCheckout.tokenize(\n async (error: BraintreeError, payload: BraintreeTokenizePayload) => {\n venmoButton.removeAttribute('disabled');\n\n if (error) {\n return this._onError(error);\n }\n\n await this._handlePostForm(payload, buyBowCart?.id);\n },\n );\n }\n });\n\n venmoButton.addEventListener('mouseenter', () => {\n venmoButton.style.backgroundColor = venmoButtonStyleHover.backgroundColor;\n });\n\n venmoButton.addEventListener('mouseleave', () => {\n venmoButton.style.backgroundColor = venmoButtonStyle.backgroundColor;\n });\n }\n\n private async _createBuyNowCart(buyNowInitializeOptions?: BuyNowInitializeOptions) {\n if (typeof buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function') {\n const cartRequestBody = buyNowInitializeOptions.getBuyNowCartRequestBody();\n\n if (!cartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n const { body: buyNowCart } = await this._cartRequestSender.createBuyNowCart(\n cartRequestBody,\n );\n\n return buyNowCart;\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n }\n\n private async _handlePostForm(\n payload: BraintreeTokenizePayload,\n buyNowCartId?: string,\n ): Promise {\n const { deviceData } = await this._braintreeSDKCreator.getDataCollector();\n const { nonce, details } = payload;\n\n this._formPoster.postForm('/checkout.php', {\n nonce,\n provider: CheckoutButtonMethodType.BRAINTREE_VENMO,\n payment_type: 'paypal',\n device_data: deviceData,\n action: 'set_external_checkout',\n billing_address: JSON.stringify(mapToLegacyBillingAddress(details)),\n shipping_address: JSON.stringify(mapToLegacyShippingAddress(details)),\n ...(buyNowCartId && { cart_id: buyNowCartId }),\n });\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CheckoutButtonMethodType } from '../';\nimport { Cart, CartRequestSender } from '../../../cart';\nimport { BuyNowCartCreationError } from '../../../cart/errors';\nimport { CheckoutActionCreator, CheckoutStore } from '../../../checkout';\nimport { SDK_VERSION_HEADERS } from '../../../common/http-request';\nimport { bindDecorator as bind } from '../../../common/utility';\nimport {\n CallbackIntentsType,\n CallbackTriggerType,\n EnvironmentType,\n GooglePayPaymentOptions,\n GooglePayPaymentProcessor,\n IntermediatePaymentData,\n NewTransactionInfo,\n TotalPriceStatusType,\n} from '../../../payment/strategies/googlepay';\nimport { GooglePayBuyNowInitializeOptions } from './googlepay-button-types';\nimport { getShippableItemsCount } from '../../../shipping';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nimport { GooglePayButtonInitializeOptions } from './googlepay-button-options';\n\nexport default class GooglePayButtonStrategy implements CheckoutButtonStrategy {\n private _methodId?: string;\n private _walletButton?: HTMLElement;\n private _buyNowCart?: Cart;\n private _isBuyNowFlow?: boolean;\n\n constructor(\n private _store: CheckoutStore,\n private _formPoster: FormPoster,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n private _cartRequestSender: CartRequestSender,\n ) {}\n\n async initialize(options: CheckoutButtonInitializeOptions): Promise {\n const { containerId, methodId, currencyCode } = options;\n\n const googlePayOptions = this._getGooglePayOptions(options);\n const { buyNowInitializeOptions } = googlePayOptions;\n\n if (!containerId || !methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"containerId\" argument is not provided.',\n );\n }\n\n const state = this._store.getState();\n const paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n const { testMode } = paymentMethod?.config || {};\n\n this._methodId = methodId;\n\n this._isBuyNowFlow = !!buyNowInitializeOptions;\n\n if (this._isBuyNowFlow) {\n if (!currencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.currencyCode\" argument is not provided.`,\n );\n }\n\n const { buyNowInitializeOptions } = googlePayOptions;\n this._googlePayPaymentProcessor.updateBuyNowFlowFlag(this._isBuyNowFlow);\n\n await this._googlePayPaymentProcessor.initialize(\n this._getMethodId(),\n this._getGooglePayClientOptions(currencyCode, testMode, buyNowInitializeOptions),\n );\n } else {\n await this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout());\n await this._googlePayPaymentProcessor.initialize(this._getMethodId());\n }\n\n this._walletButton = this._createSignInButton(containerId, googlePayOptions, currencyCode);\n }\n\n deinitialize(): Promise {\n if (this._walletButton && this._walletButton.parentNode) {\n this._walletButton.parentNode.removeChild(this._walletButton);\n this._walletButton = undefined;\n }\n\n return this._googlePayPaymentProcessor.deinitialize();\n }\n\n private _getGooglePayClientOptions(\n currencyCode: string,\n testMode?: boolean,\n buyNowInitializeOptions?: GooglePayBuyNowInitializeOptions,\n ): GooglePayPaymentOptions {\n const environment: EnvironmentType = testMode ? 'TEST' : 'PRODUCTION';\n\n return {\n environment,\n paymentDataCallbacks: {\n onPaymentDataChanged: async ({\n callbackTrigger,\n }: IntermediatePaymentData): Promise => {\n if (callbackTrigger !== CallbackTriggerType.INITIALIZE) {\n return;\n }\n\n try {\n this._buyNowCart = await this._createBuyNowCart(buyNowInitializeOptions);\n\n if (this._buyNowCart) {\n const { id, cartAmount } = this._buyNowCart;\n\n await this._store.dispatch(\n this._checkoutActionCreator.loadCheckout(id),\n );\n\n return {\n newTransactionInfo: {\n currencyCode,\n totalPrice: String(cartAmount),\n totalPriceStatus: TotalPriceStatusType.FINAL,\n },\n };\n }\n } catch (error) {\n throw new BuyNowCartCreationError(error);\n }\n },\n },\n };\n }\n\n private _createSignInButton(\n containerId: string,\n buttonOptions: GooglePayButtonInitializeOptions,\n currencyCode?: string,\n ): HTMLElement {\n const container = document.getElementById(containerId);\n const { buttonType, buttonColor } = buttonOptions;\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to create sign-in button without valid container ID.',\n );\n }\n\n const onClick = (event: Event) => this._handleWalletButtonClick(event, currencyCode);\n\n const googlePayButton = this._googlePayPaymentProcessor.createButton(\n onClick,\n buttonType,\n buttonColor,\n );\n\n container.appendChild(googlePayButton);\n\n return googlePayButton;\n }\n\n private _getMethodId(): string {\n if (!this._methodId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._methodId;\n }\n\n private _getGooglePayOptions(\n options: CheckoutButtonInitializeOptions,\n ): GooglePayButtonInitializeOptions {\n if (\n options.methodId === CheckoutButtonMethodType.GOOGLEPAY_ADYENV2 &&\n options.googlepayadyenv2\n ) {\n return options.googlepayadyenv2;\n }\n\n if (\n options.methodId === CheckoutButtonMethodType.GOOGLEPAY_ADYENV3 &&\n options.googlepayadyenv3\n ) {\n return options.googlepayadyenv3;\n }\n\n if (\n options.methodId === CheckoutButtonMethodType.GOOGLEPAY_AUTHORIZENET &&\n options.googlepayauthorizenet\n ) {\n return options.googlepayauthorizenet;\n }\n\n if (options.methodId === CheckoutButtonMethodType.GOOGLEPAY_BNZ && options.googlepaybnz) {\n return options.googlepaybnz;\n }\n\n if (\n options.methodId === CheckoutButtonMethodType.GOOGLEPAY_BRAINTREE &&\n options.googlepaybraintree\n ) {\n return options.googlepaybraintree;\n }\n\n if (\n options.methodId === CheckoutButtonMethodType.GOOGLEPAY_CHECKOUTCOM &&\n options.googlepaycheckoutcom\n ) {\n return options.googlepaycheckoutcom;\n }\n\n if (\n options.methodId === CheckoutButtonMethodType.GOOGLEPAY_CYBERSOURCEV2 &&\n options.googlepaycybersourcev2\n ) {\n return options.googlepaycybersourcev2;\n }\n\n if (\n options.methodId === CheckoutButtonMethodType.GOOGLEPAY_ORBITAL &&\n options.googlepayorbital\n ) {\n return options.googlepayorbital;\n }\n\n if (\n options.methodId === CheckoutButtonMethodType.GOOGLEPAY_STRIPE &&\n options.googlepaystripe\n ) {\n return options.googlepaystripe;\n }\n\n if (\n options.methodId === CheckoutButtonMethodType.GOOGLEPAY_STRIPEUPE &&\n options.googlepaystripeupe\n ) {\n return options.googlepaystripeupe;\n }\n\n if (\n options.methodId === CheckoutButtonMethodType.GOOGLEPAY_WORLDPAYACCESS &&\n options.googlepayworldpayaccess\n ) {\n return options.googlepayworldpayaccess;\n }\n\n throw new InvalidArgumentError();\n }\n\n private async _createBuyNowCart(\n buyNowInitializeOptions?: GooglePayBuyNowInitializeOptions,\n ): Promise {\n if (typeof buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function') {\n const cartRequestBody = buyNowInitializeOptions.getBuyNowCartRequestBody();\n\n if (!cartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n const { body: cart } = await this._cartRequestSender.createBuyNowCart(\n cartRequestBody,\n );\n\n return cart;\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n }\n\n @bind\n private async _handleWalletButtonClick(event: Event, currencyCode?: string): Promise {\n event.preventDefault();\n\n try {\n if (this._isBuyNowFlow && currencyCode) {\n this._googlePayPaymentProcessor.updatePaymentDataRequest({\n transactionInfo: {\n currencyCode,\n totalPrice: '0',\n totalPriceStatus: TotalPriceStatusType.ESTIMATED,\n },\n callbackIntents: [CallbackIntentsType.OFFER],\n });\n }\n const paymentData = await this._googlePayPaymentProcessor.displayWallet();\n\n await this._googlePayPaymentProcessor.handleSuccess(paymentData);\n\n const cart = this._store.getState().cart.getCartOrThrow();\n const hasPhysicalItems = getShippableItemsCount(cart) > 0;\n\n if (hasPhysicalItems && paymentData.shippingAddress) {\n await this._googlePayPaymentProcessor.updateShippingAddress(\n paymentData.shippingAddress,\n );\n }\n\n await this._onPaymentSelectComplete();\n } catch (error) {\n if (error && error.message !== 'CANCELED') {\n throw error;\n }\n }\n }\n\n private _onPaymentSelectComplete(): void {\n const buyNowCartId = this._buyNowCart?.id;\n\n this._formPoster.postForm('/checkout.php', {\n headers: {\n Accept: 'text/html',\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...SDK_VERSION_HEADERS,\n },\n ...(buyNowCartId && {\n action: 'set_external_checkout',\n provider: this._methodId,\n cart_id: buyNowCartId,\n }),\n });\n }\n}\n","import { CheckoutActionCreator, CheckoutStore } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { bindDecorator as bind } from '../../../common/utility';\nimport {\n formatLocale,\n getCallbackUrl,\n Masterpass,\n MasterpassCheckoutOptions,\n MasterpassScriptLoader,\n} from '../../../payment/strategies/masterpass';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nexport default class MasterpassButtonStrategy implements CheckoutButtonStrategy {\n private _masterpassClient?: Masterpass;\n private _methodId?: string;\n private _signInButton?: HTMLElement;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _masterpassScriptLoader: MasterpassScriptLoader,\n private _locale: string,\n ) {}\n\n initialize(options: CheckoutButtonInitializeOptions): Promise {\n const { containerId, methodId } = options;\n\n if (!containerId || !methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"containerId\" argument is not provided.',\n );\n }\n\n this._methodId = methodId;\n\n return this._store\n .dispatch(this._checkoutActionCreator.loadDefaultCheckout())\n .then((state) => {\n const paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n if (!paymentMethod || !paymentMethod.initializationData.checkoutId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const masterpassScriptLoaderParams = {\n useMasterpassSrc: paymentMethod.initializationData.isMasterpassSrcEnabled,\n language: formatLocale(this._locale),\n testMode: paymentMethod.config.testMode,\n checkoutId: paymentMethod.initializationData.checkoutId,\n };\n\n return this._masterpassScriptLoader.load(masterpassScriptLoaderParams);\n })\n .then((masterpass) => {\n this._masterpassClient = masterpass;\n this._signInButton = this._createSignInButton(containerId);\n });\n }\n\n deinitialize(): Promise {\n if (this._signInButton && this._signInButton.parentNode) {\n this._signInButton.removeEventListener('click', this._handleWalletButtonClick);\n this._signInButton.parentNode.removeChild(this._signInButton);\n this._signInButton = undefined;\n }\n\n return Promise.resolve();\n }\n\n private _createSignInButton(containerId: string): HTMLElement {\n const buttonContainer = document.getElementById(containerId);\n const state = this._store.getState();\n const paymentMethod = this._methodId\n ? state.paymentMethods.getPaymentMethod(this._methodId)\n : null;\n const storeConfig = state.config.getStoreConfig();\n\n if (!buttonContainer) {\n throw new Error('Need a container to place the button');\n }\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (!storeConfig) {\n throw new InvalidArgumentError('Unable to retrieve store configuration');\n }\n\n const button = document.createElement('input');\n\n button.type = 'image';\n\n if (paymentMethod.initializationData.isMasterpassSrcEnabled) {\n const subdomain = paymentMethod.config.testMode ? 'sandbox.' : '';\n const { checkoutId } = paymentMethod.initializationData;\n\n const params = [\n `locale=${formatLocale(this._locale)}`,\n `paymentmethod=master,visa,amex,discover`,\n `checkoutid=${checkoutId}`,\n ];\n\n button.src = [\n `https://${subdomain}src.mastercard.com/assets/img/btn/src_chk_btn_126x030px.svg`,\n params.join('&'),\n ].join('?');\n } else {\n button.src =\n 'https://static.masterpass.com/dyn/img/btn/global/mp_chk_btn_160x037px.svg';\n }\n\n buttonContainer.appendChild(button);\n\n button.addEventListener('click', this._handleWalletButtonClick);\n\n return button;\n }\n\n private _createMasterpassPayload(): MasterpassCheckoutOptions {\n const state = this._store.getState();\n const checkout = state.checkout.getCheckout();\n const paymentMethod = this._methodId\n ? state.paymentMethods.getPaymentMethod(this._methodId)\n : null;\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n return {\n checkoutId: paymentMethod.initializationData.checkoutId,\n allowedCardTypes: paymentMethod.initializationData.allowedCardTypes,\n amount: checkout.cart.cartAmount.toString(),\n currency: checkout.cart.currency.code,\n cartId: checkout.cart.id,\n callbackUrl: getCallbackUrl('cart'),\n };\n }\n\n @bind\n private _handleWalletButtonClick(): void {\n if (!this._masterpassClient) {\n throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n }\n\n this._masterpassClient.checkout(this._createMasterpassPayload());\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { pick } from 'lodash';\n\nimport { CheckoutActionCreator, CheckoutStore } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n StandardError,\n} from '../../../common/error/errors';\nimport { INTERNAL_USE_ONLY, SDK_VERSION_HEADERS } from '../../../common/http-request';\nimport { PaymentMethod } from '../../../payment';\nimport {\n PaypalActions,\n PaypalAuthorizeData,\n PaypalButtonStyleShapeOption,\n PaypalButtonStyleSizeOption,\n PaypalClientToken,\n PaypalScriptLoader,\n} from '../../../payment/strategies/paypal';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nexport default class PaypalButtonStrategy implements CheckoutButtonStrategy {\n private _paymentMethod?: PaymentMethod;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _paypalScriptLoader: PaypalScriptLoader,\n private _formPoster: FormPoster,\n private _host: string = '',\n ) {}\n\n initialize(options: CheckoutButtonInitializeOptions): Promise {\n const paypalOptions = options.paypal;\n const state = this._store.getState();\n const paymentMethod = (this._paymentMethod = state.paymentMethods.getPaymentMethod(\n options.methodId,\n ));\n\n if (!paypalOptions) {\n throw new InvalidArgumentError();\n }\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n return this._paypalScriptLoader\n .loadPaypal(paymentMethod.config.merchantId)\n .then((paypal) => {\n if (!paymentMethod || !paymentMethod.config.merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const merchantId = paymentMethod.config.merchantId;\n const env = paymentMethod.config.testMode ? 'sandbox' : 'production';\n const clientToken: PaypalClientToken = { [env]: paypalOptions.clientId };\n\n const fundingCreditOption = paypal.FUNDING.CREDIT || 'credit';\n const allowedSources = paypalOptions.allowCredit ? [fundingCreditOption] : [];\n const disallowedSources = !paypalOptions.allowCredit ? [fundingCreditOption] : [];\n\n return paypal.Button.render(\n {\n env,\n client: clientToken,\n commit: paypalOptions.shouldProcessPayment,\n funding: {\n allowed: allowedSources,\n disallowed: disallowedSources,\n },\n style: {\n shape: PaypalButtonStyleShapeOption.RECT,\n ...pick(\n paypalOptions.style,\n 'layout',\n 'color',\n 'label',\n 'shape',\n 'tagline',\n 'fundingicons',\n ),\n size:\n paymentMethod.id === 'paypalexpress' &&\n paypalOptions.style?.size === 'small'\n ? PaypalButtonStyleSizeOption.RESPONSIVE\n : paypalOptions.style?.size,\n },\n payment: (_, actions) =>\n this._setupPayment(merchantId, actions, paypalOptions.onPaymentError),\n onAuthorize: (data, actions) =>\n this._tokenizePayment(\n data,\n actions,\n paypalOptions.shouldProcessPayment,\n paypalOptions.onAuthorizeError,\n ),\n },\n options.containerId,\n );\n });\n }\n\n deinitialize(): Promise {\n this._paymentMethod = undefined;\n\n return Promise.resolve();\n }\n\n private _setupPayment(\n merchantId: string,\n actions?: PaypalActions,\n onError?: (error: StandardError) => void,\n ): Promise {\n if (!actions) {\n throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n }\n\n return this._store\n .dispatch(this._checkoutActionCreator.loadDefaultCheckout())\n .then((state) => {\n const cart = state.cart.getCart();\n const cartId = cart ? cart.id : '';\n\n return actions.request.post(\n `${this._host}/api/storefront/payment/paypalexpress`,\n { merchantId, cartId },\n {\n headers: {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n },\n );\n })\n .then((res) => res.id)\n .catch((error) => {\n if (onError) {\n onError(error);\n }\n\n throw error;\n });\n }\n\n private _tokenizePayment(\n data: PaypalAuthorizeData,\n actions?: PaypalActions,\n shouldProcessPayment?: boolean,\n _onError?: (error: StandardError) => void, // FIXME: This parameter seems to be unused\n ): Promise {\n if (!this._paymentMethod) {\n throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n }\n\n if (!actions) {\n throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n }\n\n if (!data.paymentID || !data.payerID) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n const methodId = this._paymentMethod.id;\n\n return actions.payment.get(data.paymentID).then((payload) => {\n this._formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n provider: methodId,\n action: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n paymentId: data.paymentID,\n payerId: data.payerID,\n payerInfo: JSON.stringify(payload.payer.payer_info),\n });\n });\n }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\nimport { noop } from 'lodash';\n\nimport {\n AddressRequestBody,\n BuyNowCartCreationError,\n Cart,\n Checkout,\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n Payment,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n ShippingOption,\n StoreConfig,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ApplePayButtonInitializeOptions, {\n WithApplePayButtonInitializeOptions,\n} from './apple-pay-button-initialize-options';\nimport ApplePaySessionFactory, { assertApplePayWindow } from './apple-pay-session-factory';\n\nconst validationEndpoint = (bigPayEndpoint: string) =>\n `${bigPayEndpoint}/api/public/v1/payments/applepay/validate_merchant`;\n\nenum DefaultLabels {\n Subtotal = 'Subtotal',\n Shipping = 'Shipping',\n}\n\nfunction isShippingOptions(options: ShippingOption[] | undefined): options is ShippingOption[] {\n return options instanceof Array;\n}\n\nexport default class ApplePayButtonStrategy implements CheckoutButtonStrategy {\n private _paymentMethod?: PaymentMethod;\n private _applePayButton?: HTMLElement;\n private _requiresShipping?: boolean;\n private _buyNowInitializeOptions?: ApplePayButtonInitializeOptions['buyNowInitializeOptions'];\n private _onAuthorizeCallback = noop;\n private _subTotalLabel: string = DefaultLabels.Subtotal;\n private _shippingLabel: string = DefaultLabels.Shipping;\n\n constructor(\n private _requestSender: RequestSender,\n private _paymentIntegrationService: PaymentIntegrationService,\n private _sessionFactory: ApplePaySessionFactory,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithApplePayButtonInitializeOptions,\n ): Promise {\n const { methodId, containerId, applepay } = options;\n\n assertApplePayWindow(window);\n\n if (!methodId || !applepay) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { buttonClassName, onPaymentAuthorize, buyNowInitializeOptions, requiresShipping } =\n applepay;\n\n this._requiresShipping = requiresShipping;\n\n this._buyNowInitializeOptions = buyNowInitializeOptions;\n\n this._onAuthorizeCallback = onPaymentAuthorize;\n\n if (!buyNowInitializeOptions) {\n await this._paymentIntegrationService.loadDefaultCheckout();\n }\n\n await this._paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this._paymentIntegrationService.getState();\n\n this._paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n await this._paymentIntegrationService.verifyCheckoutSpamProtection();\n\n this._applePayButton = this._createButton(containerId, buttonClassName);\n this._applePayButton.addEventListener('click', this._handleWalletButtonClick.bind(this));\n\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private _createButton(\n containerId: string,\n buttonClassName = 'apple-pay-checkout-button',\n ): HTMLElement {\n const container = document.getElementById(containerId);\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to create wallet button without valid container ID.',\n );\n }\n\n document.body.classList.add('apple-pay-supported');\n\n const button = document.createElement('div');\n\n button.setAttribute('class', buttonClassName);\n button.setAttribute('role', 'button');\n button.setAttribute('aria-label', 'Apple Pay button');\n container.appendChild(button);\n\n return button;\n }\n\n private async _handleWalletButtonClick(event: Event) {\n event.preventDefault();\n\n if (!this._paymentMethod || !this._paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (\n this._buyNowInitializeOptions &&\n typeof this._buyNowInitializeOptions.getBuyNowCartRequestBody === 'function'\n ) {\n const {\n countryCode,\n currencyCode,\n merchantCapabilities,\n supportedNetworks,\n storeName,\n } = this._paymentMethod.initializationData;\n\n const request = this._getRequestWithEmptyTotal(\n countryCode,\n currencyCode,\n supportedNetworks,\n merchantCapabilities,\n );\n\n if (this._requiresShipping) {\n request.requiredShippingContactFields?.push('postalAddress');\n }\n\n const applePaySession = this._sessionFactory.create(request);\n\n this._handleApplePayEvents(applePaySession, this._paymentMethod, storeName);\n\n applePaySession.begin();\n } else {\n const state = this._paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const config = state.getStoreConfigOrThrow();\n const checkout = state.getCheckoutOrThrow();\n const request = this._getBaseRequest(cart, checkout, config, this._paymentMethod);\n const applePaySession = this._sessionFactory.create(request);\n\n this._handleApplePayEvents(\n applePaySession,\n this._paymentMethod,\n config.storeProfile.storeName,\n );\n\n applePaySession.begin();\n }\n }\n\n private _getRequestWithEmptyTotal(\n countryCode: string,\n currencyCode: string,\n supportedNetworks: string[],\n merchantCapabilities: ApplePayJS.ApplePayMerchantCapability[],\n ): ApplePayJS.ApplePayPaymentRequest {\n return {\n countryCode,\n currencyCode,\n supportedNetworks,\n merchantCapabilities,\n total: { label: '', amount: '0', type: 'pending' },\n requiredBillingContactFields: ['postalAddress'],\n requiredShippingContactFields: ['email', 'phone'],\n };\n }\n\n private _getBaseRequest(\n cart: Cart,\n checkout: Checkout,\n config: StoreConfig,\n paymentMethod: PaymentMethod,\n ): ApplePayJS.ApplePayPaymentRequest {\n const {\n storeProfile: { storeCountryCode, storeName },\n } = config;\n const {\n currency: { code, decimalPlaces },\n } = cart;\n\n const {\n initializationData: { merchantCapabilities, supportedNetworks },\n } = paymentMethod;\n\n const requiresShipping = cart.lineItems.physicalItems.length > 0;\n const total: ApplePayJS.ApplePayLineItem = requiresShipping\n ? {\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n type: 'pending',\n }\n : {\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n type: 'final',\n };\n\n const request: ApplePayJS.ApplePayPaymentRequest = {\n requiredBillingContactFields: ['postalAddress'],\n requiredShippingContactFields: ['email', 'phone'],\n countryCode: storeCountryCode,\n currencyCode: code,\n merchantCapabilities,\n supportedNetworks,\n lineItems: [],\n total,\n };\n\n if (requiresShipping) {\n request.requiredShippingContactFields?.push('postalAddress');\n } else {\n const lineItems: ApplePayJS.ApplePayLineItem[] = [\n {\n label: this._subTotalLabel,\n amount: `${checkout.subtotal.toFixed(decimalPlaces)}`,\n },\n ];\n\n checkout.taxes.forEach((tax) =>\n lineItems.push({\n label: tax.name,\n amount: `${tax.amount.toFixed(decimalPlaces)}`,\n }),\n );\n\n request.lineItems = lineItems;\n }\n\n return request;\n }\n\n private _handleApplePayEvents(\n applePaySession: ApplePaySession,\n paymentMethod: PaymentMethod,\n storeName: string,\n ) {\n applePaySession.onvalidatemerchant = async (event) => {\n try {\n const { body: merchantSession } = await this._onValidateMerchant(\n paymentMethod,\n event,\n );\n\n applePaySession.completeMerchantValidation(merchantSession);\n } catch (error) {\n throw new Error('Merchant validation failed');\n }\n };\n\n if (this._buyNowInitializeOptions && !this._requiresShipping) {\n applePaySession.onpaymentmethodselected = async () => {\n await this._createBuyNowCart();\n this._handlePaymentMethodSelected(applePaySession);\n };\n }\n\n applePaySession.onshippingcontactselected = async (event) => {\n if (this._buyNowInitializeOptions && this._requiresShipping) {\n await this._createBuyNowCart();\n }\n\n await this._handleShippingContactSelected(applePaySession, storeName, event);\n };\n\n applePaySession.onshippingmethodselected = async (event) => {\n await this._handleShippingMethodSelected(applePaySession, storeName, event);\n };\n\n applePaySession.oncancel = async () => {\n try {\n const url = `/remote-checkout/${paymentMethod.id}/signout`;\n\n await this._requestSender.get(url);\n\n return await this._paymentIntegrationService.loadCheckout();\n } catch (error) {\n throw new PaymentMethodCancelledError();\n }\n };\n\n applePaySession.onpaymentauthorized = async (event) =>\n this._onPaymentAuthorized(event, applePaySession, paymentMethod);\n }\n\n private async _createBuyNowCart() {\n try {\n const cartRequestBody = this._buyNowInitializeOptions?.getBuyNowCartRequestBody?.();\n\n if (!cartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n const buyNowCart = await this._paymentIntegrationService.createBuyNowCart(\n cartRequestBody,\n );\n\n await this._paymentIntegrationService.loadCheckout(buyNowCart.id);\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n\n private _handlePaymentMethodSelected(applePaySession: ApplePaySession) {\n const state = this._paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const config = state.getStoreConfigOrThrow();\n const checkout = state.getCheckoutOrThrow();\n\n if (!this._paymentMethod || !this._paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const request = this._getBaseRequest(cart, checkout, config, this._paymentMethod);\n\n delete request.total.type;\n\n applePaySession.completePaymentMethodSelection({\n newTotal: request.total,\n newLineItems: request.lineItems,\n });\n }\n\n private async _handleShippingContactSelected(\n applePaySession: ApplePaySession,\n storeName: string,\n event: ApplePayJS.ApplePayShippingContactSelectedEvent,\n ) {\n const shippingAddress = this._transformContactToAddress(event.shippingContact);\n\n try {\n await this._paymentIntegrationService.updateShippingAddress(shippingAddress);\n } catch (error) {\n applePaySession.abort();\n\n throw new Error('Shipping address update failed');\n }\n\n let state = this._paymentIntegrationService.getState();\n const {\n currency: { decimalPlaces },\n } = state.getCartOrThrow();\n let checkout = state.getCheckoutOrThrow();\n const selectionShippingOptionId = checkout.consignments[0].selectedShippingOption?.id;\n const availableOptions = checkout.consignments[0].availableShippingOptions;\n const selectedOption = availableOptions?.find(({ id }) => id === selectionShippingOptionId);\n const unselectedOptions = availableOptions?.filter(\n (option) => option.id !== selectionShippingOptionId,\n );\n const shippingOptions: ApplePayJS.ApplePayShippingMethod[] = selectedOption\n ? [\n {\n label: selectedOption.description,\n amount: `${selectedOption.cost.toFixed(decimalPlaces)}`,\n detail: selectedOption.additionalDescription,\n identifier: selectedOption.id,\n },\n ]\n : [];\n\n if (unselectedOptions) {\n [\n ...unselectedOptions.filter((option) => option.isRecommended),\n ...unselectedOptions.filter((option) => !option.isRecommended),\n ].forEach((option) =>\n shippingOptions.push({\n label: option.description,\n amount: `${option.cost.toFixed(decimalPlaces)}`,\n detail: option.additionalDescription,\n identifier: option.id,\n }),\n );\n }\n\n if (!isShippingOptions(availableOptions)) {\n throw new Error('Shipping options not available.');\n }\n\n if (availableOptions.length === 0) {\n applePaySession.completeShippingContactSelection(\n ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,\n [],\n {\n type: 'pending',\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n },\n [],\n );\n\n return;\n }\n\n const recommendedOption = availableOptions.find((option) => option.isRecommended);\n\n const optionId = recommendedOption ? recommendedOption.id : availableOptions[0].id;\n const selectedOptionId = selectedOption ? selectedOption.id : optionId;\n\n try {\n await this._updateShippingOption(selectedOptionId);\n } catch (error) {\n throw new Error('Shipping options update failed');\n }\n\n state = this._paymentIntegrationService.getState();\n checkout = state.getCheckoutOrThrow();\n\n applePaySession.completeShippingContactSelection({\n newShippingMethods: shippingOptions,\n newTotal: {\n type: 'final',\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n },\n newLineItems: this._getUpdatedLineItems(checkout, decimalPlaces),\n });\n }\n\n private async _handleShippingMethodSelected(\n applePaySession: ApplePaySession,\n storeName: string,\n event: ApplePayJS.ApplePayShippingMethodSelectedEvent,\n ) {\n const {\n shippingMethod: { identifier: optionId },\n } = event;\n\n try {\n await this._updateShippingOption(optionId);\n } catch (error) {\n applePaySession.abort();\n\n throw new Error('Shipping option selection update failed.');\n }\n\n const state = this._paymentIntegrationService.getState();\n const {\n currency: { decimalPlaces },\n } = state.getCartOrThrow();\n const checkout = state.getCheckoutOrThrow();\n\n applePaySession.completeShippingMethodSelection({\n newTotal: {\n type: 'final',\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n },\n newLineItems: this._getUpdatedLineItems(checkout, decimalPlaces),\n });\n }\n\n private _getUpdatedLineItems(\n checkout: Checkout,\n decimalPlaces: number,\n ): ApplePayJS.ApplePayLineItem[] {\n const lineItems: ApplePayJS.ApplePayLineItem[] = [\n {\n label: this._subTotalLabel,\n amount: `${checkout.subtotal.toFixed(decimalPlaces)}`,\n },\n ];\n\n checkout.taxes.forEach((tax) =>\n lineItems.push({\n label: tax.name,\n amount: `${tax.amount.toFixed(decimalPlaces)}`,\n }),\n );\n lineItems.push({\n label: this._shippingLabel,\n amount: `${checkout.shippingCostTotal.toFixed(decimalPlaces)}`,\n });\n\n return lineItems;\n }\n\n private async _updateShippingOption(optionId: string) {\n return this._paymentIntegrationService.selectShippingOption(optionId);\n }\n\n private async _onValidateMerchant(\n paymentData: PaymentMethod,\n event: ApplePayJS.ApplePayValidateMerchantEvent,\n ) {\n const body = [\n `validationUrl=${event.validationURL}`,\n `merchantIdentifier=${paymentData.initializationData.merchantId}`,\n `displayName=${paymentData.initializationData.storeName}`,\n `domainName=${window.location.hostname}`,\n ].join('&');\n\n return this._requestSender.post(\n validationEndpoint(paymentData.initializationData.paymentsUrl),\n {\n credentials: false,\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'X-XSRF-TOKEN': null,\n },\n body,\n },\n );\n }\n\n private async _onPaymentAuthorized(\n event: ApplePayJS.ApplePayPaymentAuthorizedEvent,\n applePaySession: ApplePaySession,\n paymentMethod: PaymentMethod,\n ) {\n const { token, billingContact, shippingContact } = event.payment;\n const state = this._paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const requiresShipping = cart.lineItems.physicalItems.length > 0;\n\n const payment: Payment = {\n methodId: paymentMethod.id,\n paymentData: {\n formattedPayload: {\n apple_pay_token: {\n payment_data: token.paymentData,\n payment_method: token.paymentMethod,\n transaction_id: token.transactionIdentifier,\n },\n },\n },\n };\n\n const transformedBillingAddress = this._transformContactToAddress(billingContact);\n const transformedShippingAddress = this._transformContactToAddress(shippingContact);\n const emailAddress = shippingContact?.emailAddress;\n const phone = shippingContact?.phoneNumber || '';\n\n try {\n await this._paymentIntegrationService.updateBillingAddress({\n ...transformedBillingAddress,\n email: emailAddress,\n phone,\n });\n\n if (requiresShipping) {\n await this._paymentIntegrationService.updateShippingAddress(\n transformedShippingAddress,\n );\n }\n\n await this._paymentIntegrationService.submitOrder({\n useStoreCredit: false,\n });\n\n await this._paymentIntegrationService.submitPayment(payment);\n applePaySession.completePayment(ApplePaySession.STATUS_SUCCESS);\n\n return this._onAuthorizeCallback();\n } catch (error) {\n applePaySession.completePayment(ApplePaySession.STATUS_FAILURE);\n\n throw new Error('Payment cannot complete');\n }\n }\n\n private _transformContactToAddress(\n contact?: ApplePayJS.ApplePayPaymentContact,\n ): AddressRequestBody {\n return {\n firstName: contact?.givenName || '',\n lastName: contact?.familyName || '',\n city: contact?.locality || '',\n company: '',\n address1: (contact?.addressLines && contact.addressLines[0]) || '',\n address2: (contact?.addressLines && contact.addressLines[1]) || '',\n postalCode: contact?.postalCode || '',\n countryCode: contact?.countryCode || '',\n phone: contact?.phoneNumber || '',\n stateOrProvince: contact?.administrativeArea || '',\n stateOrProvinceCode: contact?.administrativeArea || '',\n customFields: [],\n };\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ApplePayButtonStrategy from './apple-pay-button-strategy';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst createApplePayButtonStrategy: CheckoutButtonStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new ApplePayButtonStrategy(\n createRequestSender({ host: getHost() }),\n paymentIntegrationService,\n new ApplePaySessionFactory(),\n );\n};\n\nexport default toResolvableModule(createApplePayButtonStrategy, [{ id: 'applepay' }]);\n","import { stringifyUrl } from 'query-string';\n\nimport {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n NotImplementedError,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n BoltButtonStyleOptions,\n BoltHostWindow,\n BoltPaymentMethod,\n StyleButtonShape,\n StyleButtonSize,\n} from './bolt';\nimport { WithBoltButtonInitializeOptions } from './bolt-button-initialize-options';\nimport BoltScriptLoader from './bolt-script-loader';\n\nexport default class BoltButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private boltScriptLoader: BoltScriptLoader,\n public boltHostWindow: BoltHostWindow = window,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithBoltButtonInitializeOptions,\n ): Promise {\n const { bolt, containerId, methodId } = options;\n const { buyNowInitializeOptions, style } = bolt || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!bolt) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bolt\" argument is not provided.`,\n );\n }\n\n const isBuyNowFlow = Boolean(buyNowInitializeOptions);\n\n if (!isBuyNowFlow) {\n throw new NotImplementedError('Only buy now flow is implemented for Bolt button');\n }\n\n if (\n !buyNowInitializeOptions?.storefrontApiToken ||\n typeof buyNowInitializeOptions.storefrontApiToken !== 'string'\n ) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.storefrontApiToken\" argument is not provided.`,\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod: BoltPaymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { initializationData, config } = paymentMethod;\n const { publishableKey, developerConfig } = initializationData || {};\n\n await this.boltScriptLoader.loadBoltClient(\n publishableKey,\n config.testMode,\n developerConfig,\n 'BigCommerce',\n buyNowInitializeOptions.storefrontApiToken,\n );\n\n this.renderButton(containerId, paymentMethod, style);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n paymentMethod: BoltPaymentMethod,\n style?: BoltButtonStyleOptions,\n ): void {\n if (typeof this.boltHostWindow.BoltConnect?.setupProductPageCheckout !== 'function') {\n return;\n }\n\n this.addButtonContainer(containerId, paymentMethod, style);\n this.boltHostWindow.BoltConnect.setupProductPageCheckout();\n }\n\n private addButtonContainer(\n containerId: string,\n paymentMethod: BoltPaymentMethod,\n style?: BoltButtonStyleOptions,\n ): void {\n const container = document.getElementById(containerId);\n\n if (!container) {\n return;\n }\n\n const boltButtonContainer = document.createElement('div');\n const boltButtonObject = document.createElement('object');\n\n boltButtonContainer.setAttribute('id', 'product-page-checkout-wrapper');\n boltButtonContainer.setAttribute('class', 'bolt-button-wrapper');\n boltButtonContainer.setAttribute('style', 'display:none');\n boltButtonContainer.setAttribute('data-tid', 'product-page-checkout-wrapper');\n\n boltButtonObject.setAttribute('data', this.getBoltObjectData(paymentMethod, style));\n boltButtonObject.setAttribute('class', 'bolt-product-checkout-button');\n\n boltButtonContainer.append(boltButtonObject);\n container.innerHTML = '';\n container.append(boltButtonContainer);\n }\n\n private getBoltObjectData(\n paymentMethod: BoltPaymentMethod,\n style?: BoltButtonStyleOptions,\n ): string {\n const { initializationData, config } = paymentMethod;\n const { publishableKey, developerConfig } = initializationData || {};\n\n const domainUrl = this.boltScriptLoader.getDomainURL(!!config.testMode, developerConfig);\n const buttonHeight = this.getButtonHeight(style?.size);\n const buttonBorderRadius = this.getButtonBorderRadius(style?.shape, buttonHeight);\n\n return stringifyUrl({\n url: `https://${domainUrl}/v1/checkout_button`,\n query: {\n publishable_key: publishableKey,\n variant: 'ppc',\n height: buttonHeight,\n border_radius: buttonBorderRadius,\n },\n });\n }\n\n private getButtonHeight(buttonSize?: StyleButtonSize): number | undefined {\n if (!buttonSize) {\n return;\n }\n\n switch (buttonSize) {\n case StyleButtonSize.Small:\n return 25;\n\n case StyleButtonSize.Large:\n return 45;\n\n case StyleButtonSize.Medium:\n default:\n return 40;\n }\n }\n\n private getButtonBorderRadius(\n buttonShape?: StyleButtonShape,\n buttonHeight?: number,\n ): number | undefined {\n if (!buttonShape) {\n return;\n }\n\n switch (buttonShape) {\n case StyleButtonShape.Pill:\n return buttonHeight ? Math.round(buttonHeight / 2) : undefined;\n\n case StyleButtonShape.Rect:\n default:\n return 4;\n }\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BoltButtonStrategy from './bolt-button-strategy';\nimport BoltScriptLoader from './bolt-script-loader';\n\nconst createBoltButtonStrategy: CheckoutButtonStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new BoltButtonStrategy(\n paymentIntegrationService,\n new BoltScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createBoltButtonStrategy, [{ id: 'bolt' }]);\n","import {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n PayPalBuyNowInitializeOptions,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceButtonInitializeOptions, {\n WithPayPalCommerceButtonInitializeOptions,\n} from './paypal-commerce-button-initialize-options';\n\nexport default class PayPalCommerceButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithPayPalCommerceButtonInitializeOptions,\n ): Promise {\n const { paypalcommerce, containerId, methodId } = options;\n\n const isBuyNowFlow = Boolean(paypalcommerce?.buyNowInitializeOptions);\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!paypalcommerce) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerce\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !paypalcommerce.currencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerce.currencyCode\" argument is not provided.`,\n );\n }\n\n if (\n isBuyNowFlow &&\n typeof paypalcommerce.buyNowInitializeOptions?.getBuyNowCartRequestBody !== 'function'\n ) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerce.buyNowInitializeOptions.getBuyNowCartRequestBody\" argument is not provided or it is not a function.`,\n );\n }\n\n if (!isBuyNowFlow) {\n // Info: default checkout should not be loaded for BuyNow flow,\n // since there is no checkout session available for that.\n await this.paymentIntegrationService.loadDefaultCheckout();\n }\n\n // Info: we are using provided currency code for buy now cart,\n // because checkout session is not available before buy now cart creation,\n // hence application will throw an error on getCartOrThrow method call\n const currencyCode = isBuyNowFlow\n ? paypalcommerce.currencyCode\n : this.paymentIntegrationService.getState().getCartOrThrow().currency.code;\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId, currencyCode, false);\n\n this.renderButton(containerId, methodId, paypalcommerce);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n paypalcommerce: PayPalCommerceButtonInitializeOptions,\n ): void {\n const { buyNowInitializeOptions, style, onComplete } = paypalcommerce;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled } = paymentMethod.initializationData || {};\n\n const defaultCallbacks = {\n createOrder: () => this.paypalCommerceIntegrationService.createOrder('paypalcommerce'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const hostedCheckoutCallbacks = {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(data, actions, methodId, onComplete),\n };\n\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(style),\n ...defaultCallbacks,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n };\n\n const paypalButton = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButton.isEligible()) {\n paypalButton.render(`#${containerId}`);\n } else {\n this.paypalCommerceIntegrationService.removeElement(containerId);\n }\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart = await this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(\n buyNowInitializeOptions,\n );\n\n await this.paymentIntegrationService.loadCheckout(buyNowCart.id);\n }\n }\n\n private async onHostedCheckoutApprove(\n data: ApproveCallbackPayload,\n actions: ApproveCallbackActions,\n methodId: string,\n onComplete?: () => void,\n ): Promise {\n if (!data.orderID) {\n throw new MissingDataError(MissingDataErrorType.MissingOrderId);\n }\n\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const orderDetails = await actions.order.get();\n\n try {\n const billingAddress =\n this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.paypalCommerceIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.paypalCommerceIntegrationService.submitPayment(methodId, data.orderID);\n\n if (onComplete && typeof onComplete === 'function') {\n onComplete();\n }\n\n return true; // FIXME: Do we really need to return true here?\n } catch (error) {\n throw new Error(error);\n }\n }\n\n private async onShippingAddressChange(\n data: ShippingAddressChangeCallbackPayload,\n ): Promise {\n const address = this.paypalCommerceIntegrationService.getAddress({\n city: data.shippingAddress.city,\n countryCode: data.shippingAddress.country_code,\n postalCode: data.shippingAddress.postal_code,\n stateOrProvinceCode: data.shippingAddress.state,\n });\n\n try {\n // Info: we use the same address to fill billing and shipping addresses to have valid quota on BE for order updating process\n // on this stage we don't have access to valid customer's address accept shipping data\n await this.paymentIntegrationService.updateBillingAddress(address);\n await this.paymentIntegrationService.updateShippingAddress(address);\n\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n throw new Error(error);\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n ): Promise {\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n throw new Error(error);\n }\n }\n}\n","import {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceButtonStrategy from './paypal-commerce-button-strategy';\n\nconst createPayPalCommerceButtonStrategy: CheckoutButtonStrategyFactory<\n PayPalCommerceButtonStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceButtonStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceButtonStrategy, [{ id: 'paypalcommerce' }]);\n","import {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n PayPalBuyNowInitializeOptions,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceCreditButtonInitializeOptions, {\n WithPayPalCommerceCreditButtonInitializeOptions,\n} from './paypal-commerce-credit-button-initialize-options';\n\nexport default class PayPalCommerceCreditButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithPayPalCommerceCreditButtonInitializeOptions,\n ): Promise {\n const { paypalcommercecredit, containerId, methodId } = options;\n const {\n buyNowInitializeOptions,\n currencyCode: providedCurrencyCode,\n messagingContainerId,\n } = paypalcommercecredit || {};\n\n const isBuyNowFlow = !!buyNowInitializeOptions;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!paypalcommercecredit) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercecredit\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !providedCurrencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercecredit.currencyCode\" argument is not provided.`,\n );\n }\n\n if (\n isBuyNowFlow &&\n typeof buyNowInitializeOptions?.getBuyNowCartRequestBody !== 'function'\n ) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercecredit.buyNowInitializeOptions.getBuyNowCartRequestBody\" argument is not provided or it is not a function.`,\n );\n }\n\n if (!isBuyNowFlow) {\n // Info: default checkout should not be loaded for BuyNow flow,\n // since there is no checkout session available for that.\n await this.paymentIntegrationService.loadDefaultCheckout();\n }\n\n // Info: we are using provided currency code for buy now cart,\n // because checkout session is not available before buy now cart creation,\n // hence application will throw an error on getCartOrThrow method call\n const currencyCode = isBuyNowFlow\n ? providedCurrencyCode\n : this.paymentIntegrationService.getState().getCartOrThrow().currency.code;\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId, currencyCode, false);\n\n this.renderButton(containerId, methodId, paypalcommercecredit);\n this.renderMessages(messagingContainerId);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n paypalcommercecredit: PayPalCommerceCreditButtonInitializeOptions,\n ): void {\n const { buyNowInitializeOptions, style, onComplete } = paypalcommercecredit;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled } = paymentMethod.initializationData || {};\n\n const defaultCallbacks = {\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder('paypalcommercecredit'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const hostedCheckoutCallbacks = {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(data, actions, methodId, onComplete),\n };\n\n const fundingSources = [paypalSdk.FUNDING.PAYLATER, paypalSdk.FUNDING.CREDIT];\n let hasRenderedSmartButton = false;\n\n fundingSources.forEach((fundingSource) => {\n if (!hasRenderedSmartButton) {\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(style),\n ...defaultCallbacks,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n };\n\n const paypalButton = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButton.isEligible()) {\n paypalButton.render(`#${containerId}`);\n hasRenderedSmartButton = true;\n }\n }\n });\n\n if (!hasRenderedSmartButton) {\n this.paypalCommerceIntegrationService.removeElement(containerId);\n }\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart = await this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(\n buyNowInitializeOptions,\n );\n\n await this.paymentIntegrationService.loadCheckout(buyNowCart.id);\n }\n }\n\n private async onHostedCheckoutApprove(\n data: ApproveCallbackPayload,\n actions: ApproveCallbackActions,\n methodId: string,\n onComplete?: () => void,\n ): Promise {\n if (!data.orderID) {\n throw new MissingDataError(MissingDataErrorType.MissingOrderId);\n }\n\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const orderDetails = await actions.order.get();\n\n try {\n const billingAddress =\n this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.paypalCommerceIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.paypalCommerceIntegrationService.submitPayment(methodId, data.orderID);\n\n if (onComplete && typeof onComplete === 'function') {\n onComplete();\n }\n\n return true; // FIXME: Do we really need to return true here?\n } catch (error) {\n throw new Error(error);\n }\n }\n\n private async onShippingAddressChange(\n data: ShippingAddressChangeCallbackPayload,\n ): Promise {\n const address = this.paypalCommerceIntegrationService.getAddress({\n city: data.shippingAddress.city,\n countryCode: data.shippingAddress.country_code,\n postalCode: data.shippingAddress.postal_code,\n stateOrProvinceCode: data.shippingAddress.state,\n });\n\n try {\n // Info: we use the same address to fill billing and shipping addresses to have valid quota on BE for order updating process\n // on this stage we don't have access to valid customer's address accept shipping data\n await this.paymentIntegrationService.updateBillingAddress(address);\n await this.paymentIntegrationService.updateShippingAddress(address);\n\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n throw new Error(error);\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n ): Promise {\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n throw new Error(error);\n }\n }\n\n private renderMessages(messagingContainerId?: string): void {\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n\n if (messagingContainerId && document.getElementById(messagingContainerId)) {\n const cart = this.paymentIntegrationService.getState().getCartOrThrow();\n\n const paypalMessagesOptions = {\n amount: cart.cartAmount,\n placement: 'cart',\n style: {\n layout: 'text',\n },\n };\n\n const paypalMessages = paypalSdk.Messages(paypalMessagesOptions);\n\n paypalMessages.render(`#${messagingContainerId}`);\n }\n }\n}\n","import {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceCreditButtonStrategy from './paypal-commerce-credit-button-strategy';\n\nconst createPayPalCommerceCreditButtonStrategy: CheckoutButtonStrategyFactory<\n PayPalCommerceCreditButtonStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditButtonStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceCreditButtonStrategy, [\n { id: 'paypalcommercecredit' },\n]);\n","import {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n PayPalButtonStyleOptions,\n PayPalBuyNowInitializeOptions,\n PayPalCommerceButtonsOptions,\n StyleButtonColor,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceVenmoButtonInitializeOptions, {\n WithPayPalCommerceVenmoButtonInitializeOptions,\n} from './paypal-commerce-venmo-button-initialize-options';\n\nexport default class PayPalCommerceVenmoButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithPayPalCommerceVenmoButtonInitializeOptions,\n ): Promise {\n const { paypalcommercevenmo, containerId, methodId } = options;\n const { buyNowInitializeOptions, currencyCode: providedCurrencyCode } =\n paypalcommercevenmo || {};\n\n const isBuyNowFlow = !!buyNowInitializeOptions;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!paypalcommercevenmo) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercevenmo\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !providedCurrencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercevenmo.currencyCode\" argument is not provided.`,\n );\n }\n\n if (\n isBuyNowFlow &&\n typeof buyNowInitializeOptions?.getBuyNowCartRequestBody !== 'function'\n ) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercevenmo.buyNowInitializeOptions.getBuyNowCartRequestBody\" argument is not provided or it is not a function.`,\n );\n }\n\n if (!isBuyNowFlow) {\n // Info: default checkout should not be loaded for BuyNow flow,\n // since there is no checkout session available for that.\n await this.paymentIntegrationService.loadDefaultCheckout();\n }\n\n // Info: we are using provided currency code for buy now cart,\n // because checkout session is not available before buy now cart creation,\n // hence application will throw an error on getCartOrThrow method call\n const currencyCode = isBuyNowFlow\n ? providedCurrencyCode\n : this.paymentIntegrationService.getState().getCartOrThrow().currency.code;\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId, currencyCode, false);\n\n this.renderButton(containerId, methodId, paypalcommercevenmo);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n paypalcommercevenmo: PayPalCommerceVenmoButtonInitializeOptions,\n ): void {\n const { buyNowInitializeOptions, style } = paypalcommercevenmo;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const fundingSource = paypalSdk.FUNDING.VENMO;\n\n const defaultCallbacks = {\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder('paypalcommercevenmo'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource,\n style: this.getValidVenmoButtonStyles(style),\n ...defaultCallbacks,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n };\n\n const paypalButtonRender = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${containerId}`);\n } else {\n this.paypalCommerceIntegrationService.removeElement(containerId);\n }\n }\n\n private getValidVenmoButtonStyles(style: PayPalButtonStyleOptions | undefined) {\n const validButtonStyle = this.paypalCommerceIntegrationService.getValidButtonStyle(style);\n\n if (validButtonStyle.color === StyleButtonColor.gold) {\n return {\n ...validButtonStyle,\n color: undefined,\n };\n }\n\n return validButtonStyle;\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart = await this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(\n buyNowInitializeOptions,\n );\n\n await this.paymentIntegrationService.loadCheckout(buyNowCart.id);\n }\n }\n}\n","import {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceVenmoButtonStrategy from './paypal-commerce-venmo-button-strategy';\n\nconst createPayPalCommerceVenmoButtonStrategy: CheckoutButtonStrategyFactory<\n PayPalCommerceVenmoButtonStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceVenmoButtonStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceVenmoButtonStrategy, [\n { id: 'paypalcommercevenmo' },\n]);\n","import {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n PayPalBuyNowInitializeOptions,\n PayPalCommerceButtonsOptions,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceAlternativeMethodsButtonOptions, {\n WithPayPalCommerceAlternativeMethodsButtonInitializeOptions,\n} from './paypal-commerce-alternative-methods-button-initialize-options';\n\nexport default class PayPalCommerceAlternativeMethodsButtonStrategy\n implements CheckoutButtonStrategy\n{\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions &\n WithPayPalCommerceAlternativeMethodsButtonInitializeOptions,\n ): Promise {\n const { paypalcommercealternativemethods, containerId, methodId } = options;\n const {\n apm,\n buyNowInitializeOptions,\n currencyCode: providedCurrencyCode,\n } = paypalcommercealternativemethods || {};\n\n const isBuyNowFlow = !!buyNowInitializeOptions;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!paypalcommercealternativemethods) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercealternativemethods\" argument is not provided.`,\n );\n }\n\n if (!apm) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercealternativemethods.apm\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !providedCurrencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercealternativemethods.currencyCode\" argument is not provided.`,\n );\n }\n\n if (\n isBuyNowFlow &&\n typeof buyNowInitializeOptions?.getBuyNowCartRequestBody !== 'function'\n ) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercealternativemethods.buyNowInitializeOptions.getBuyNowCartRequestBody\" argument is not provided or it is not a function.`,\n );\n }\n\n if (!isBuyNowFlow) {\n // Info: default checkout should not be loaded for BuyNow flow,\n // since there is no checkout session available for that.\n await this.paymentIntegrationService.loadDefaultCheckout();\n }\n\n // Info: we are using provided currency code for buy now cart,\n // because checkout session is not available before buy now cart creation,\n // hence application will throw an error on getCartOrThrow method call\n const currencyCode = isBuyNowFlow\n ? providedCurrencyCode\n : this.paymentIntegrationService.getState().getCartOrThrow().currency.code;\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId, currencyCode, false);\n\n this.renderButton(containerId, methodId, paypalcommercealternativemethods);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n paypalcommercealternativemethods: PayPalCommerceAlternativeMethodsButtonOptions,\n ): void {\n const { apm, buyNowInitializeOptions, style } = paypalcommercealternativemethods;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const isAvailableFundingSource = Object.values(paypalSdk.FUNDING).includes(apm);\n\n if (!isAvailableFundingSource) {\n throw new InvalidArgumentError(\n `Unable to initialize PayPal button because \"options.paypalcommercealternativemethods.apm\" argument is not valid funding source.`,\n );\n }\n\n const defaultCallbacks = {\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder(\n 'paypalcommercealternativemethod',\n ),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource: apm,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(style),\n ...defaultCallbacks,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n };\n\n const paypalButtonRender = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${containerId}`);\n } else {\n this.paypalCommerceIntegrationService.removeElement(containerId);\n }\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart = await this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(\n buyNowInitializeOptions,\n );\n\n await this.paymentIntegrationService.loadCheckout(buyNowCart.id);\n }\n }\n}\n","import {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceAlternativeMethodsButtonStrategy from './paypal-commerce-alternative-methods-button-strategy';\n\nconst createPayPalCommerceAlternativeMethodsButtonStrategy: CheckoutButtonStrategyFactory<\n PayPalCommerceAlternativeMethodsButtonStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceAlternativeMethodsButtonStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceAlternativeMethodsButtonStrategy, [\n { id: 'paypalcommercealternativemethods' },\n]);\n","export interface PaypalFundingTypeList {\n CARD?: string;\n CREDIT?: string;\n PAYPAL?: string;\n PAYLATER?: string;\n}\n\nexport interface PaypalButton {\n render(options: PaypalButtonOptions, container: string): void;\n}\n\nexport interface PaypalButtonRender {\n render(container: string): void;\n isEligible(): boolean;\n}\n\nexport interface MessagingRender {\n render(container: string): void;\n}\n\nexport interface MessagingOptions {\n amount: number;\n placement: string;\n}\n\nexport interface PaypalButtonOptions {\n env?: string;\n commit?: boolean;\n style?: PaypalStyleOptions;\n funding?: PaypalFundingType;\n fundingSource?: string;\n client?: PaypalClientToken;\n payment?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onAuthorize?(data: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n createOrder?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onApprove?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n}\n\nexport interface PaypalClientToken {\n production?: string;\n sandbox?: string;\n}\n\nexport interface PaypalFundingType {\n allowed?: string[];\n disallowed?: string[];\n}\n\nexport enum PaypalButtonStyleLayoutOption {\n HORIZONTAL = 'horizontal',\n VERTICAL = 'vertical',\n}\n\nexport enum PaypalButtonStyleSizeOption {\n SMALL = 'small',\n MEDIUM = 'medium',\n LARGE = 'large',\n RESPONSIVE = 'responsive',\n}\n\nexport enum PaypalButtonStyleColorOption {\n GOLD = 'gold',\n BLUE = 'blue',\n SIlVER = 'silver',\n BLACK = 'black',\n}\n\nexport enum PaypalButtonStyleLabelOption {\n CHECKOUT = 'checkout',\n PAY = 'pay',\n BUYNOW = 'buynow',\n PAYPAL = 'paypal',\n CREDIT = 'credit',\n}\n\nexport enum PaypalButtonStyleShapeOption {\n PILL = 'pill',\n RECT = 'rect',\n}\n\nexport interface PaypalStyleOptions {\n layout?: PaypalButtonStyleLayoutOption;\n size?: PaypalButtonStyleSizeOption;\n color?: PaypalButtonStyleColorOption;\n label?: PaypalButtonStyleLabelOption;\n shape?: PaypalButtonStyleShapeOption;\n tagline?: boolean;\n fundingicons?: boolean;\n height?: number;\n}\n\nexport interface PaypalActions {\n payment: PaypalPaymentActions;\n request: PaypalRequestActions;\n}\n\nexport interface PaypalPaymentActions {\n get(id: string): Promise;\n}\n\nexport interface PaypalRequestActions {\n post(url: string, payload?: object, options?: object): Promise<{ id: string }>;\n}\n\nexport interface PaypalTransaction {\n amount?: PaypalAmount;\n payee?: PaypalPayee;\n description?: string;\n note_to_payee?: string;\n item_list?: PaypalItemList;\n}\n\nexport interface PaypalItemList {\n items?: PaypalItem[];\n shipping_address?: PaypalAddress;\n}\n\nexport interface PaypalItem {\n sku?: string;\n name?: string;\n description?: string;\n quantity: string;\n price: string;\n currency: string;\n tax?: string;\n}\n\nexport interface PaypalAmount {\n currency: string;\n total: string;\n}\n\nexport interface PaypalPayer {\n payer_info: object;\n}\n\nexport interface PaypalPayee {\n email?: string;\n merchant_id?: string;\n}\n\nexport interface PaypalAddress {\n line1: string;\n line2?: string;\n city?: string;\n country_code: string;\n postal_code?: string;\n state?: string;\n phone?: string;\n type?: string;\n}\n\nexport interface PaypalPaymentPayload {\n payment: PaypalPaymentPayload;\n payer: PaypalPayer;\n transactions?: PaypalTransaction[];\n}\n\nexport interface PaypalAuthorizeData {\n payerId: string;\n paymentId?: string;\n billingToken?: string;\n // the PayPal side of things uses uppercase ID instead of camel case Id\n payerID?: string;\n paymentID?: string;\n}\n\nexport interface PaypalExpressCheckout {\n initXO(): void;\n startFlow(url: string): void;\n closeFlow(): void;\n setup(merchantId: string, options: PaypalExpressCheckoutOptions): void;\n}\n\nexport interface PaypalExpressCheckoutOptions {\n button: string;\n environment: string;\n}\n\nexport interface PaypalHostWindow extends Window {\n paypal?: PaypalSDK;\n}\n\nexport interface PaypalSDK {\n Button: PaypalButton;\n checkout: PaypalExpressCheckout;\n FUNDING: PaypalFundingTypeList;\n Messages(options: MessagingOptions): MessagingRender;\n Buttons(options: PaypalButtonOptions): PaypalButtonRender;\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n INTERNAL_USE_ONLY,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentIntegrationService,\n SDK_VERSION_HEADERS,\n StandardError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithPaypalExpressButtonInitializeOptions } from './paypal-express-button-initialize-options';\nimport PaypalScriptLoader from './paypal-express-script-loader';\nimport {\n PaypalActions,\n PaypalAuthorizeData,\n PaypalButtonStyleShapeOption,\n PaypalButtonStyleSizeOption,\n PaypalClientToken,\n PaypalSDK,\n PaypalStyleOptions,\n} from './paypal-express-types';\n\nexport default class PaypalButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalExpressScriptLoader: PaypalScriptLoader,\n private formPoster: FormPoster,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithPaypalExpressButtonInitializeOptions,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(options.methodId);\n\n if (!options.paypal) {\n throw new InvalidArgumentError();\n }\n\n if (!paymentMethod.config.merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const paypalSDK = await this.paypalExpressScriptLoader.loadPaypalSDK(\n paymentMethod.config.merchantId,\n );\n\n this.renderButton(options, paypalSDK);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n options: CheckoutButtonInitializeOptions & WithPaypalExpressButtonInitializeOptions,\n paypalSDK: PaypalSDK,\n ) {\n const { containerId, methodId, paypal } = options;\n const { allowCredit, clientId, onPaymentError, shouldProcessPayment, style } = paypal;\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(options.methodId);\n\n if (!paymentMethod.config.merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const merchantId = paymentMethod.config.merchantId;\n const env = paymentMethod.config.testMode ? 'sandbox' : 'production';\n const clientToken: PaypalClientToken = { [env]: clientId };\n const fundingCreditOption = paypalSDK.FUNDING.CREDIT || 'credit';\n const allowedSources = allowCredit ? [fundingCreditOption] : [];\n const disallowedSources = !allowCredit ? [fundingCreditOption] : [];\n\n return paypalSDK.Button.render(\n {\n env,\n client: clientToken,\n commit: shouldProcessPayment,\n funding: {\n allowed: allowedSources,\n disallowed: disallowedSources,\n },\n style: this.getStyle(style),\n payment: (_, actions) => this.setupPayment(merchantId, actions, onPaymentError),\n onAuthorize: (data, actions) =>\n this.tokenizePayment(data, methodId, actions, shouldProcessPayment),\n },\n containerId,\n );\n }\n\n private getStyle(style?: Omit): PaypalStyleOptions {\n const { color, fundingicons, label, layout, shape, size, tagline } = style || {};\n\n return {\n color,\n fundingicons,\n label,\n layout,\n shape: shape || PaypalButtonStyleShapeOption.RECT,\n size: size === 'small' ? PaypalButtonStyleSizeOption.RESPONSIVE : size,\n tagline,\n };\n }\n\n private async setupPayment(\n merchantId: string,\n actions?: PaypalActions,\n onError?: (error: StandardError) => void,\n ): Promise {\n if (!actions) {\n throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n }\n\n try {\n const state = await this.paymentIntegrationService.loadDefaultCheckout();\n const { id: cartId } = state.getCartOrThrow();\n const host = state.getHost() || '';\n\n const paymentRequest = await actions.request.post(\n `${host}/api/storefront/payment/paypalexpress`,\n { merchantId, cartId },\n {\n headers: {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n },\n );\n\n return paymentRequest.id;\n } catch (error) {\n if (onError) {\n onError(error);\n }\n\n throw error;\n }\n }\n\n private async tokenizePayment(\n data: PaypalAuthorizeData,\n methodId: string,\n actions?: PaypalActions,\n shouldProcessPayment?: boolean,\n ): Promise {\n if (!actions) {\n throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n }\n\n if (!data.paymentID || !data.payerID) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n const getPaymentData = await actions.payment.get(data.paymentID);\n\n return this.formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n provider: paymentMethod.id,\n action: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n paymentId: data.paymentID,\n payerId: data.payerID,\n payerInfo: JSON.stringify(getPaymentData.payer.payer_info),\n });\n }\n}\n","import { LoadScriptOptions, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { PaypalHostWindow, PaypalSDK } from './paypal-express-types';\n\nexport default class PaypalScriptLoader {\n private window: PaypalHostWindow;\n\n constructor(private scriptLoader: ScriptLoader) {\n this.window = window;\n }\n\n async loadPaypalSDK(merchantId = ''): Promise {\n const scriptSrc = '//www.paypalobjects.com/api/checkout.min.js';\n const options: LoadScriptOptions = {\n async: true,\n attributes: { 'data-merchant-id': merchantId },\n ...(merchantId && {\n attributes: { 'data-merchant-id': merchantId },\n }),\n };\n\n await this.scriptLoader.loadScript(scriptSrc, options);\n\n if (!this.window.paypal) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.paypal;\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { PaypalExpressButtonStrategy, PaypalExpressScriptLoader } from './index';\n\nconst createPaypalExpressButtonStrategy: CheckoutButtonStrategyFactory<\n PaypalExpressButtonStrategy\n> = (paymentIntegrationService) => {\n return new PaypalExpressButtonStrategy(\n paymentIntegrationService,\n new PaypalExpressScriptLoader(getScriptLoader()),\n createFormPoster(),\n );\n};\n\nexport default toResolvableModule(createPaypalExpressButtonStrategy, [{ id: 'paypalexpress' }]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport { createCheckoutStore } from '../checkout';\nimport { PaymentMethodActionCreator, PaymentMethodRequestSender } from '../payment';\nimport { createPaymentIntegrationService } from '../payment-integration';\n\nimport CheckoutButtonInitializer from './checkout-button-initializer';\nimport CheckoutButtonInitializerOptions from './checkout-button-initializer-options';\nimport CheckoutButtonStrategyActionCreator from './checkout-button-strategy-action-creator';\nimport createCheckoutButtonRegistry from './create-checkout-button-registry';\nimport createCheckoutButtonRegistryV2 from './create-checkout-button-registry-v2';\n\n/**\n * Creates an instance of `CheckoutButtonInitializer`.\n *\n * @remarks\n * ```js\n * const initializer = createCheckoutButtonInitializer();\n *\n * initializer.initializeButton({\n * methodId: 'braintreepaypal',\n * braintreepaypal: {\n * container: '#checkoutButton',\n * },\n * });\n * ```\n *\n * @alpha\n * Please note that `CheckoutButtonInitializer` is currently in an early stage\n * of development. Therefore the API is unstable and not ready for public\n * consumption.\n *\n * @param options - A set of construction options.\n * @returns an instance of `CheckoutButtonInitializer`.\n */\nexport default function createCheckoutButtonInitializer(\n options?: CheckoutButtonInitializerOptions,\n): CheckoutButtonInitializer {\n const { host, locale = 'en' } = options ?? {};\n const store = createCheckoutStore();\n const requestSender = createRequestSender({ host });\n const formPoster = createFormPoster({ host });\n const paymentIntegrationService = createPaymentIntegrationService(store);\n const registryV2 = createCheckoutButtonRegistryV2(paymentIntegrationService);\n\n return new CheckoutButtonInitializer(\n store,\n new CheckoutButtonStrategyActionCreator(\n createCheckoutButtonRegistry(store, requestSender, formPoster, locale, host),\n registryV2,\n new PaymentMethodActionCreator(new PaymentMethodRequestSender(requestSender)),\n ),\n );\n}\n","import {\n CheckoutButtonStrategy,\n CheckoutButtonStrategyFactory,\n CheckoutButtonStrategyResolveId,\n isResolvableModule,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ResolveIdRegistry } from '../common/registry';\nimport * as defaultCheckoutButtonStrategyFactories from '../generated/checkout-button-strategies';\n\nexport interface CheckoutButtonStrategyFactories {\n [key: string]: CheckoutButtonStrategyFactory;\n}\n\nexport default function createCheckoutButtonStrategyRegistry(\n paymentIntegrationService: PaymentIntegrationService,\n checkoutButtonStrategyFactories: CheckoutButtonStrategyFactories = defaultCheckoutButtonStrategyFactories,\n): ResolveIdRegistry {\n const registry = new ResolveIdRegistry<\n CheckoutButtonStrategy,\n CheckoutButtonStrategyResolveId\n >();\n\n for (const [, createCheckoutButtonStrategy] of Object.entries(\n checkoutButtonStrategyFactories,\n )) {\n if (\n !isResolvableModule<\n CheckoutButtonStrategyFactory,\n CheckoutButtonStrategyResolveId\n >(createCheckoutButtonStrategy)\n ) {\n continue;\n }\n\n for (const resolverId of createCheckoutButtonStrategy.resolveIds) {\n registry.register(resolverId, () =>\n createCheckoutButtonStrategy(paymentIntegrationService),\n );\n }\n }\n\n return registry;\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { RequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { CartRequestSender } from '../cart';\nimport { CheckoutActionCreator, CheckoutRequestSender, CheckoutStore } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { ConfigActionCreator, ConfigRequestSender } from '../config';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport { PaymentMethodActionCreator, PaymentMethodRequestSender } from '../payment';\nimport { createAmazonPayV2PaymentProcessor } from '../payment/strategies/amazon-pay-v2';\nimport { BraintreeScriptLoader, BraintreeSDKCreator } from '../payment/strategies/braintree';\nimport {\n createGooglePayPaymentProcessor,\n GooglePayAdyenV2Initializer,\n GooglePayAdyenV3Initializer,\n GooglePayAuthorizeNetInitializer,\n GooglePayBNZInitializer,\n GooglePayBraintreeInitializer,\n GooglePayCheckoutcomInitializer,\n GooglePayCybersourceV2Initializer,\n GooglePayOrbitalInitializer,\n GooglePayStripeInitializer,\n GooglePayStripeUPEInitializer,\n GooglePayWorldpayAccessInitializer,\n} from '../payment/strategies/googlepay';\nimport { MasterpassScriptLoader } from '../payment/strategies/masterpass';\nimport { PaypalScriptLoader } from '../payment/strategies/paypal';\n\nimport { CheckoutButtonMethodType, CheckoutButtonStrategy } from './strategies';\nimport { AmazonPayV2ButtonStrategy } from './strategies/amazon-pay-v2';\nimport AmazonPayV2RequestSender from './strategies/amazon-pay-v2/amazon-pay-v2-request-sender';\nimport {\n BraintreePaypalButtonStrategy,\n BraintreePaypalCreditButtonStrategy,\n BraintreeVenmoButtonStrategy,\n} from './strategies/braintree';\nimport { GooglePayButtonStrategy } from './strategies/googlepay';\nimport { MasterpassButtonStrategy } from './strategies/masterpass';\nimport { PaypalButtonStrategy } from './strategies/paypal';\n\nexport default function createCheckoutButtonRegistry(\n store: CheckoutStore,\n requestSender: RequestSender,\n formPoster: FormPoster,\n locale: string,\n host?: string,\n): Registry {\n const registry = new Registry();\n const scriptLoader = getScriptLoader();\n const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n const checkoutActionCreator = new CheckoutActionCreator(\n checkoutRequestSender,\n new ConfigActionCreator(new ConfigRequestSender(requestSender)),\n new FormFieldsActionCreator(new FormFieldsRequestSender(requestSender)),\n );\n const paymentMethodActionCreator = new PaymentMethodActionCreator(\n new PaymentMethodRequestSender(requestSender),\n );\n\n const braintreeSdkCreator = new BraintreeSDKCreator(new BraintreeScriptLoader(scriptLoader));\n const cartRequestSender = new CartRequestSender(requestSender);\n const amazonPayV2RequestSender = new AmazonPayV2RequestSender(requestSender);\n\n registry.register(\n CheckoutButtonMethodType.AMAZON_PAY_V2,\n () =>\n new AmazonPayV2ButtonStrategy(\n store,\n checkoutActionCreator,\n createAmazonPayV2PaymentProcessor(),\n cartRequestSender,\n amazonPayV2RequestSender,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.BRAINTREE_PAYPAL,\n () =>\n new BraintreePaypalButtonStrategy(\n store,\n checkoutActionCreator,\n cartRequestSender,\n braintreeSdkCreator,\n formPoster,\n window,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.BRAINTREE_PAYPAL_CREDIT,\n () =>\n new BraintreePaypalCreditButtonStrategy(\n store,\n checkoutActionCreator,\n cartRequestSender,\n braintreeSdkCreator,\n formPoster,\n window,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.BRAINTREE_VENMO,\n () =>\n new BraintreeVenmoButtonStrategy(\n store,\n paymentMethodActionCreator,\n cartRequestSender,\n braintreeSdkCreator,\n formPoster,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.GOOGLEPAY_ADYENV2,\n () =>\n new GooglePayButtonStrategy(\n store,\n formPoster,\n checkoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayAdyenV2Initializer()),\n cartRequestSender,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.GOOGLEPAY_ADYENV3,\n () =>\n new GooglePayButtonStrategy(\n store,\n formPoster,\n checkoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayAdyenV3Initializer()),\n cartRequestSender,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.GOOGLEPAY_AUTHORIZENET,\n () =>\n new GooglePayButtonStrategy(\n store,\n formPoster,\n checkoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayAuthorizeNetInitializer()),\n cartRequestSender,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.GOOGLEPAY_BNZ,\n () =>\n new GooglePayButtonStrategy(\n store,\n formPoster,\n checkoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayBNZInitializer()),\n cartRequestSender,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.GOOGLEPAY_BRAINTREE,\n () =>\n new GooglePayButtonStrategy(\n store,\n formPoster,\n checkoutActionCreator,\n createGooglePayPaymentProcessor(\n store,\n new GooglePayBraintreeInitializer(braintreeSdkCreator),\n ),\n cartRequestSender,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.GOOGLEPAY_CHECKOUTCOM,\n () =>\n new GooglePayButtonStrategy(\n store,\n formPoster,\n checkoutActionCreator,\n createGooglePayPaymentProcessor(\n store,\n new GooglePayCheckoutcomInitializer(requestSender),\n ),\n cartRequestSender,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.GOOGLEPAY_CYBERSOURCEV2,\n () =>\n new GooglePayButtonStrategy(\n store,\n formPoster,\n checkoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayCybersourceV2Initializer()),\n cartRequestSender,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.GOOGLEPAY_ORBITAL,\n () =>\n new GooglePayButtonStrategy(\n store,\n formPoster,\n checkoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayOrbitalInitializer()),\n cartRequestSender,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.GOOGLEPAY_STRIPE,\n () =>\n new GooglePayButtonStrategy(\n store,\n formPoster,\n checkoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayStripeInitializer()),\n cartRequestSender,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.GOOGLEPAY_STRIPEUPE,\n () =>\n new GooglePayButtonStrategy(\n store,\n formPoster,\n checkoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayStripeUPEInitializer()),\n cartRequestSender,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.MASTERPASS,\n () =>\n new MasterpassButtonStrategy(\n store,\n checkoutActionCreator,\n new MasterpassScriptLoader(scriptLoader),\n locale,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.PAYPALEXPRESS,\n () =>\n new PaypalButtonStrategy(\n store,\n checkoutActionCreator,\n new PaypalScriptLoader(scriptLoader),\n formPoster,\n host,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.GOOGLEPAY_WORLDPAYACCESS,\n () =>\n new GooglePayButtonStrategy(\n store,\n formPoster,\n checkoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayWorldpayAccessInitializer()),\n cartRequestSender,\n ),\n );\n\n return registry;\n}\n","import EmbeddedCheckoutError from './embedded-checkout-error';\nimport { EmbeddedContentOptions } from './iframe-content';\n\nexport enum EmbeddedCheckoutEventType {\n CheckoutComplete = 'CHECKOUT_COMPLETE',\n CheckoutError = 'CHECKOUT_ERROR',\n CheckoutLoaded = 'CHECKOUT_LOADED',\n FrameError = 'FRAME_ERROR',\n FrameLoaded = 'FRAME_LOADED',\n SignedOut = 'SIGNED_OUT',\n}\n\nexport interface EmbeddedCheckoutEventMap {\n [EmbeddedCheckoutEventType.CheckoutComplete]: EmbeddedCheckoutCompleteEvent;\n [EmbeddedCheckoutEventType.CheckoutError]: EmbeddedCheckoutErrorEvent;\n [EmbeddedCheckoutEventType.CheckoutLoaded]: EmbeddedCheckoutLoadedEvent;\n [EmbeddedCheckoutEventType.FrameError]: EmbeddedCheckoutFrameErrorEvent;\n [EmbeddedCheckoutEventType.FrameLoaded]: EmbeddedCheckoutFrameLoadedEvent;\n [EmbeddedCheckoutEventType.SignedOut]: EmbeddedCheckoutSignedOutEvent;\n}\n\nexport type EmbeddedCheckoutEvent =\n | EmbeddedCheckoutCompleteEvent\n | EmbeddedCheckoutErrorEvent\n | EmbeddedCheckoutFrameErrorEvent\n | EmbeddedCheckoutFrameLoadedEvent\n | EmbeddedCheckoutLoadedEvent\n | EmbeddedCheckoutSignedOutEvent;\n\nexport interface EmbeddedCheckoutCompleteEvent {\n type: EmbeddedCheckoutEventType.CheckoutComplete;\n}\n\nexport interface EmbeddedCheckoutErrorEvent {\n type: EmbeddedCheckoutEventType.CheckoutError;\n payload: EmbeddedCheckoutError;\n}\n\nexport interface EmbeddedCheckoutLoadedEvent {\n type: EmbeddedCheckoutEventType.CheckoutLoaded;\n}\n\nexport interface EmbeddedCheckoutFrameErrorEvent {\n type: EmbeddedCheckoutEventType.FrameError;\n payload: EmbeddedCheckoutError;\n}\n\nexport interface EmbeddedCheckoutFrameLoadedEvent {\n type: EmbeddedCheckoutEventType.FrameLoaded;\n payload?: EmbeddedContentOptions;\n}\n\nexport interface EmbeddedCheckoutSignedOutEvent {\n type: EmbeddedCheckoutEventType.SignedOut;\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { InternalErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RequestError } from '../../common/error/errors';\n\n/**\n * Throw this error we are not able to sign in a shopper because the provided\n * login token is invalid.\n */\nexport default class InvalidLoginTokenError extends RequestError {\n constructor(response: Response) {\n super(response, { message: response.body.title });\n\n this.name = 'InvalidLoginTokenError';\n this.type = 'invalid_login_token';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport enum NotEmbeddableErrorType {\n MissingContainer = 'missing_container',\n MissingContent = 'missing_content',\n UnknownError = 'unknown_error',\n}\n\n/**\n * Throw this error if we are not able to embed the checkout form as an iframe.\n * This can be due to the fact that the provided container ID is invalid, or the\n * checkout form fails to load inside the iframe. It can also be due to an\n * unknown reason.\n */\nexport default class NotEmbeddableError extends StandardError {\n constructor(\n message?: string,\n public subtype: NotEmbeddableErrorType = NotEmbeddableErrorType.UnknownError,\n ) {\n super(message || 'Unable to embed the checkout form.');\n\n this.name = 'NotEmbeddableError';\n this.type = 'not_embeddable';\n }\n}\n","import EmbeddedCheckoutStyles from '../embedded-checkout-styles';\n\nexport enum EmbeddedContentEventType {\n StyleConfigured = 'STYLE_CONFIGURED',\n}\n\nexport interface EmbeddedContentEventMap {\n [EmbeddedContentEventType.StyleConfigured]: EmbeddedContentStyleConfiguredEvent;\n}\n\nexport type EmbeddedContentEvent = EmbeddedContentStyleConfiguredEvent;\n\nexport interface EmbeddedContentStyleConfiguredEvent {\n type: EmbeddedContentEventType.StyleConfigured;\n payload: EmbeddedCheckoutStyles;\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport { IFrameComponent, IframeEventListener, IframeEventPoster } from '../common/iframe';\nimport { BrowserStorage } from '../common/storage';\nimport { parseUrl } from '../common/url';\nimport { bindDecorator as bind } from '../common/utility';\n\nimport EmbeddedCheckoutError from './embedded-checkout-error';\nimport { EmbeddedCheckoutEventMap, EmbeddedCheckoutEventType } from './embedded-checkout-events';\nimport EmbeddedCheckoutOptions from './embedded-checkout-options';\nimport { InvalidLoginTokenError, NotEmbeddableError, NotEmbeddableErrorType } from './errors';\nimport { EmbeddedContentEvent, EmbeddedContentEventType } from './iframe-content';\nimport ResizableIframeCreator from './resizable-iframe-creator';\n\nexport const ALLOW_COOKIE_ATTEMPT_INTERVAL = 10 * 60 * 1000;\nexport const IS_COOKIE_ALLOWED_KEY = 'isCookieAllowed';\nexport const LAST_ALLOW_COOKIE_ATTEMPT_KEY = 'lastAllowCookieAttempt';\n\n@bind\nexport default class EmbeddedCheckout {\n private _iframe?: IFrameComponent;\n private _isAttached: boolean;\n\n /**\n * @internal\n */\n constructor(\n private _iframeCreator: ResizableIframeCreator,\n private _messageListener: IframeEventListener,\n private _messagePoster: IframeEventPoster,\n private _loadingIndicator: LoadingIndicator,\n private _requestSender: RequestSender,\n private _storage: BrowserStorage,\n private _location: Location,\n private _options: EmbeddedCheckoutOptions,\n ) {\n this._isAttached = false;\n\n if (this._options.onComplete) {\n this._messageListener.addListener(\n EmbeddedCheckoutEventType.CheckoutComplete,\n this._options.onComplete,\n );\n }\n\n if (this._options.onError) {\n this._messageListener.addListener(\n EmbeddedCheckoutEventType.CheckoutError,\n this._options.onError,\n );\n }\n\n if (this._options.onLoad) {\n this._messageListener.addListener(\n EmbeddedCheckoutEventType.CheckoutLoaded,\n this._options.onLoad,\n );\n }\n\n if (this._options.onFrameLoad) {\n this._messageListener.addListener(\n EmbeddedCheckoutEventType.FrameLoaded,\n this._options.onFrameLoad,\n );\n }\n\n if (this._options.onSignOut) {\n this._messageListener.addListener(\n EmbeddedCheckoutEventType.SignedOut,\n this._options.onSignOut,\n );\n }\n\n this._messageListener.addListener(EmbeddedCheckoutEventType.FrameLoaded, () =>\n this._configureStyles(),\n );\n }\n\n attach(): Promise {\n if (this._isAttached) {\n return Promise.resolve(this);\n }\n\n this._isAttached = true;\n this._messageListener.listen();\n this._loadingIndicator.show(this._options.containerId);\n\n return this._allowCookie()\n .then(() => this._attemptLogin())\n .then((url) => this._iframeCreator.createFrame(url, this._options.containerId))\n .then((iframe) => {\n this._iframe = iframe;\n\n this._configureStyles();\n this._loadingIndicator.hide();\n })\n .catch((error) => {\n this._isAttached = false;\n\n return this._retryAllowCookie(error).catch(() => {\n this._messageListener.trigger({\n type: EmbeddedCheckoutEventType.FrameError,\n payload: error,\n });\n\n this._loadingIndicator.hide();\n\n throw error;\n });\n })\n .then(() => this);\n }\n\n detach(): void {\n if (!this._isAttached) {\n return;\n }\n\n this._isAttached = false;\n this._messageListener.stopListen();\n\n if (this._iframe && this._iframe.parentNode) {\n this._iframe.parentNode.removeChild(this._iframe);\n this._iframe.iFrameResizer.close();\n }\n }\n\n private _configureStyles(): void {\n if (!this._iframe || !this._iframe.contentWindow || !this._options.styles) {\n return;\n }\n\n this._messagePoster.setTarget(this._iframe.contentWindow);\n\n this._messagePoster.post({\n type: EmbeddedContentEventType.StyleConfigured,\n payload: this._options.styles,\n });\n }\n\n private _attemptLogin(): Promise {\n if (!/^\\/login\\/token/.test(parseUrl(this._options.url).pathname)) {\n return Promise.resolve(this._options.url);\n }\n\n return this._requestSender\n .post<{ redirectUrl: string }>(this._options.url)\n .then(({ body: { redirectUrl } }) => redirectUrl)\n .catch((response) => Promise.reject(new InvalidLoginTokenError(response)));\n }\n\n /**\n * This workaround is required for certain browsers (namely Safari) that\n * prevent session cookies to be set for a third party website unless the\n * user has recently visited such website. Therefore, before we attempt to\n * login or set an active cart in the session, we need to first redirect the\n * user to the domain of Embedded Checkout.\n */\n private _allowCookie(): Promise {\n if (this._storage.getItem(IS_COOKIE_ALLOWED_KEY)) {\n return Promise.resolve();\n }\n\n this._storage.setItem(IS_COOKIE_ALLOWED_KEY, true);\n\n // It could be possible that the flag is set to true but the browser has\n // already removed the permission to store third-party cookies. In that\n // case, we should try to redirect the user again. But we only want to\n // do it once within a fixed interval. This is to avoid getting into a\n // redirect loop if the shopper actually doesn't have a valid card\n // session.\n this._storage.setItem(LAST_ALLOW_COOKIE_ATTEMPT_KEY, Date.now());\n\n const { origin } = parseUrl(this._options.url);\n const redirectUrl = `${origin}/embedded-checkout/allow-cookie?returnUrl=${encodeURIComponent(\n this._location.href,\n )}`;\n\n document.body.style.visibility = 'hidden';\n this._location.replace(redirectUrl);\n\n return new Promise(() => {});\n }\n\n private _retryAllowCookie(error: EmbeddedCheckoutError): Promise {\n const lastAttempt = Number(this._storage.getItem(LAST_ALLOW_COOKIE_ATTEMPT_KEY));\n const canRetry =\n (!lastAttempt || Date.now() - lastAttempt > ALLOW_COOKIE_ATTEMPT_INTERVAL) &&\n error instanceof NotEmbeddableError &&\n error.subtype === NotEmbeddableErrorType.MissingContent;\n\n if (!canRetry) {\n return Promise.reject();\n }\n\n this._storage.removeItem(LAST_ALLOW_COOKIE_ATTEMPT_KEY);\n this._storage.removeItem(IS_COOKIE_ALLOWED_KEY);\n\n return this._allowCookie();\n }\n}\n","import { IFrameComponent, iframeResizer, isIframeEvent } from '../common/iframe';\nimport { parseUrl } from '../common/url';\n\nimport { EmbeddedCheckoutEventType } from './embedded-checkout-events';\nimport { NotEmbeddableError, NotEmbeddableErrorType } from './errors';\n\nexport default class ResizableIframeCreator {\n constructor(private _options?: { timeout: number }) {}\n\n createFrame(src: string, containerId: string): Promise {\n const container = document.getElementById(containerId);\n const { timeout = 60000 } = this._options || {};\n\n if (!container) {\n throw new NotEmbeddableError(\n 'Unable to embed the iframe because the container element could not be found.',\n NotEmbeddableErrorType.MissingContainer,\n );\n }\n\n const iframe = document.createElement('iframe');\n\n iframe.src = src;\n iframe.style.border = 'none';\n iframe.style.display = 'none';\n iframe.style.width = '100%';\n iframe.allowPaymentRequest = true;\n\n container.appendChild(iframe);\n\n return this._toResizableFrame(iframe, timeout).catch((error) => {\n container.removeChild(iframe);\n\n throw error;\n });\n }\n\n private _toResizableFrame(\n iframe: HTMLIFrameElement,\n timeoutInterval: number,\n ): Promise {\n // Can't simply listen to `load` event because it always gets triggered even if there's an error.\n // Instead, listen to the `load` inside the iframe and let the parent frame know when it happens.\n return new Promise((resolve, reject) => {\n const timeout = window.setTimeout(() => {\n reject(\n new NotEmbeddableError(\n 'Unable to embed the iframe because the content could not be loaded.',\n ),\n );\n }, timeoutInterval);\n\n const handleMessage = (event: MessageEvent) => {\n if (event.origin !== parseUrl(iframe.src).origin) {\n return;\n }\n\n if (isIframeEvent(event.data, EmbeddedCheckoutEventType.FrameError)) {\n teardown();\n reject(\n new NotEmbeddableError(\n event.data.payload.message,\n NotEmbeddableErrorType.MissingContent,\n ),\n );\n }\n\n if (isIframeEvent(event.data, EmbeddedCheckoutEventType.FrameLoaded)) {\n iframe.style.display = '';\n\n const contentId = event.data.payload && event.data.payload.contentId;\n const iframes = iframeResizer(\n {\n scrolling: false,\n sizeWidth: false,\n heightCalculationMethod: contentId ? 'taggedElement' : 'lowestElement',\n },\n iframe,\n );\n\n teardown();\n resolve(iframes[iframes.length - 1]);\n }\n };\n\n const teardown = () => {\n window.removeEventListener('message', handleMessage);\n window.clearTimeout(timeout);\n };\n\n window.addEventListener('message', handleMessage);\n });\n }\n}\n","import { IFrameComponent, IFrameOptions } from 'iframe-resizer';\n\nexport {\n HeightCalculationMethod,\n IFrameComponent,\n IFrameMessageData,\n IFrameObject,\n IFrameOptions,\n IFramePage,\n IFramePageOptions,\n IFrameResizedData,\n IFrameScrollData,\n PageInfo,\n WidthCalculationMethod,\n} from 'iframe-resizer';\n\n// The reason why we are wrapping the original `iframeResizer` function imported\n// from the package is because the package sets up event listeners (window\n// resize etc...) as soon as the package is imported. Therefore, to defer the\n// side effect from happening until the function is actually being used, we are\n// importing the package inside this function. To minimise the chance of\n// importing the original package inadvertently, we are also re-exporting all of\n// its public interfaces. The re-exports do not cause any side effect because\n// they are plain TypeScript interfaces; meaning they are only used for type\n// checks rather than for code output.\nexport function iframeResizer(\n options: IFrameOptions,\n target: string | HTMLElement,\n): IFrameComponent[] {\n /* eslint-disable @typescript-eslint/no-var-requires */\n const { iframeResizer: originalIframeResizer } = require('iframe-resizer');\n\n return originalIframeResizer(options, target);\n}\n\n// We also need to wrap the original `iframeResizer.contentWindow` because\n// similarly the package sets up event listeners as soon as the package gets\n// imported. Another reason is that if it is imported at the top level using a\n// regular import statement, it will be stripped out by Webpack as it is\n// considered as \"unused\", unless we explicitly mark it as a package that\n// produces side effects.\nexport function setupContentWindowForIframeResizer(): void {\n require('iframe-resizer/js/iframeResizer.contentWindow');\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\n\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport { IframeEventListener, IframeEventPoster } from '../common/iframe';\nimport { BrowserStorage } from '../common/storage';\nimport { parseUrl } from '../common/url';\n\nimport EmbeddedCheckout from './embedded-checkout';\nimport { EmbeddedCheckoutEventMap } from './embedded-checkout-events';\nimport EmbeddedCheckoutOptions from './embedded-checkout-options';\nimport { EmbeddedContentEvent } from './iframe-content';\nimport ResizableIframeCreator from './resizable-iframe-creator';\n\nconst STORAGE_PREFIX = 'BigCommerce.EmbeddedCheckout';\n\n/**\n * Embed the checkout form in an iframe.\n *\n * @remarks\n * Once the iframe is embedded, it will automatically resize according to the\n * size of the checkout form. It will also notify the parent window when certain\n * events have occurred. i.e.: when the form is loaded and ready to be used.\n *\n * ```js\n * embedCheckout({\n * url: 'https://checkout/url',\n * containerId: 'container-id',\n * });\n * ```\n *\n * @param options - Options for embedding the checkout form.\n * @returns A promise that resolves to an instance of `EmbeddedCheckout`.\n */\nexport default function embedCheckout(options: EmbeddedCheckoutOptions): Promise {\n const origin = parseUrl(options.url).origin;\n const embeddedCheckout = new EmbeddedCheckout(\n new ResizableIframeCreator(),\n new IframeEventListener(origin),\n new IframeEventPoster(origin),\n new LoadingIndicator({ styles: options.styles && options.styles.loadingIndicator }),\n createRequestSender(),\n new BrowserStorage(STORAGE_PREFIX),\n window.location,\n options,\n );\n\n return embeddedCheckout.attach();\n}\n","import { EmbeddedCheckoutFrameLoadedEvent } from '../embedded-checkout-events';\n\nexport default function handleFrameLoadedEvent(message: EmbeddedCheckoutFrameLoadedEvent): void {\n if (!message.payload || !message.payload.contentId) {\n return;\n }\n\n const body = document.getElementById(message.payload.contentId);\n\n if (!body || body.hasAttribute('data-iframe-height')) {\n return;\n }\n\n body.setAttribute('data-iframe-height', '');\n}\n","export default interface CustomError extends Error {\n message: string;\n type: string;\n subtype?: string;\n}\n\nexport function isCustomError(error: unknown): error is CustomError {\n return typeof error === 'object' && error !== null && 'message' in error && 'type' in error;\n}\n","import { CustomError, isCustomError } from '../../common/error/errors';\nimport { IframeEventListener, IframeEventPoster } from '../../common/iframe';\nimport { bindDecorator as bind } from '../../common/utility';\nimport EmbeddedCheckoutError from '../embedded-checkout-error';\nimport {\n EmbeddedCheckoutCompleteEvent,\n EmbeddedCheckoutErrorEvent,\n EmbeddedCheckoutEvent,\n EmbeddedCheckoutEventMap,\n EmbeddedCheckoutEventType,\n EmbeddedCheckoutFrameErrorEvent,\n EmbeddedCheckoutFrameLoadedEvent,\n EmbeddedCheckoutLoadedEvent,\n EmbeddedCheckoutSignedOutEvent,\n} from '../embedded-checkout-events';\nimport EmbeddedCheckoutStyles from '../embedded-checkout-styles';\n\nimport EmbeddedCheckoutMessenger from './embedded-checkout-messenger';\nimport { EmbeddedContentEventMap, EmbeddedContentEventType } from './embedded-content-events';\nimport EmbeddedContentOptions from './embedded-content-options';\n\n@bind\nexport default class IframeEmbeddedCheckoutMessenger implements EmbeddedCheckoutMessenger {\n /**\n * @internal\n */\n constructor(\n private _messageListener: IframeEventListener,\n private _messagePoster: IframeEventPoster,\n private _untargetedMessagePoster: IframeEventPoster,\n private _messageHandlers: EventCallbacks = {},\n ) {\n this._messageListener.listen();\n }\n\n postComplete(): void {\n const message: EmbeddedCheckoutCompleteEvent = {\n type: EmbeddedCheckoutEventType.CheckoutComplete,\n };\n\n this._postMessage(message);\n }\n\n postError(payload: Error | CustomError): void {\n const message: EmbeddedCheckoutErrorEvent = {\n type: EmbeddedCheckoutEventType.CheckoutError,\n payload: this._transformError(payload),\n };\n\n this._postMessage(message);\n }\n\n postFrameError(payload: Error | CustomError): void {\n const message: EmbeddedCheckoutFrameErrorEvent = {\n type: EmbeddedCheckoutEventType.FrameError,\n payload: this._transformError(payload),\n };\n\n // Ideally, all messages should be targeted at a specific origin.\n // However, for `FrameError` message, we have to post it in an\n // untargeted fashion. This is because the error could be caused by a\n // missing cart. That makes it not possible to determine of site origin\n // of the parent window. Nevertheless, we still want to notify the\n // parent window about the error.\n this._postMessage(message, { untargeted: true });\n }\n\n postFrameLoaded(payload?: EmbeddedContentOptions): void {\n const message: EmbeddedCheckoutFrameLoadedEvent = {\n type: EmbeddedCheckoutEventType.FrameLoaded,\n payload,\n };\n\n this._postMessage(message);\n }\n\n postLoaded(): void {\n const message: EmbeddedCheckoutLoadedEvent = {\n type: EmbeddedCheckoutEventType.CheckoutLoaded,\n };\n\n this._postMessage(message);\n }\n\n postSignedOut(): void {\n const message: EmbeddedCheckoutSignedOutEvent = {\n type: EmbeddedCheckoutEventType.SignedOut,\n };\n\n this._postMessage(message);\n }\n\n receiveStyles(handler: (styles: EmbeddedCheckoutStyles) => void): void {\n this._messageListener.addListener(\n EmbeddedContentEventType.StyleConfigured,\n ({ payload }) => {\n handler(payload);\n },\n );\n }\n\n private _postMessage(message: EmbeddedCheckoutEvent, options?: { untargeted?: boolean }): void {\n this._notifyMessageHandlers(message);\n\n if (options && options.untargeted) {\n return this._untargetedMessagePoster.post(message);\n }\n\n this._messagePoster.post(message);\n }\n\n private _notifyMessageHandlers(message: EmbeddedCheckoutEvent): void {\n Object.keys(this._messageHandlers).forEach((key) => {\n if (message.type !== key) {\n return;\n }\n\n const handler = this._messageHandlers[key];\n\n if (handler) {\n (handler as (event: EmbeddedCheckoutEvent) => void).call(null, message);\n }\n });\n }\n\n private _transformError(error: Error | CustomError): EmbeddedCheckoutError {\n return {\n message: error.message,\n type: isCustomError(error) ? error.type : undefined,\n subtype: isCustomError(error) ? error.subtype : undefined,\n };\n }\n}\n\nexport type EventCallbacks = {\n [key in keyof TEventMap]?: (event: TEventMap[key]) => void;\n};\n","import { bindDecorator as bind } from '../../common/utility';\n\nimport EmbeddedCheckoutMessenger from './embedded-checkout-messenger';\n\n@bind\nexport default class NoopEmbeddedCheckoutMessenger implements EmbeddedCheckoutMessenger {\n postComplete(): void {}\n\n postError(): void {}\n\n postFrameError(): void {}\n\n postFrameLoaded(): void {}\n\n postLoaded(): void {}\n\n postSignedOut(): void {}\n\n receiveStyles(): void {}\n}\n","import {\n IframeEventListener,\n IframeEventPoster,\n setupContentWindowForIframeResizer,\n} from '../../common/iframe';\nimport { EmbeddedCheckoutEvent, EmbeddedCheckoutEventType } from '../embedded-checkout-events';\n\nimport EmbeddedCheckoutMessenger from './embedded-checkout-messenger';\nimport EmbeddedCheckoutMessengerOptions from './embedded-checkout-messenger-options';\nimport { EmbeddedContentEventMap } from './embedded-content-events';\nimport handleFrameLoadedEvent from './handle-frame-loaded-event';\nimport IframeEmbeddedCheckoutMessenger from './iframe-embedded-checkout-messenger';\nimport NoopEmbeddedCheckoutMessenger from './noop-embedded-checkout-messenger';\n\n/**\n * Create an instance of `EmbeddedCheckoutMessenger`.\n *\n * @remarks\n * The object is responsible for posting messages to the parent window from the\n * iframe when certain events have occurred. For example, when the checkout\n * form is first loaded, you should notify the parent window about it.\n *\n * The iframe can only be embedded in domains that are allowed by the store.\n *\n * ```ts\n * const messenger = createEmbeddedCheckoutMessenger({\n * parentOrigin: 'https://some/website',\n * });\n *\n * messenger.postFrameLoaded();\n * ```\n *\n * @alpha\n * Please note that this feature is currently in an early stage of development.\n * Therefore the API is unstable and not ready for public consumption.\n *\n * @param options - Options for creating `EmbeddedCheckoutMessenger`\n * @returns - An instance of `EmbeddedCheckoutMessenger`\n */\nexport default function createEmbeddedCheckoutMessenger(\n options: EmbeddedCheckoutMessengerOptions,\n): EmbeddedCheckoutMessenger {\n setupContentWindowForIframeResizer();\n\n const parentWindow = options.parentWindow || window.parent;\n\n // Return a No-op messenger if it is not called inside an iframe\n if (window === parentWindow) {\n return new NoopEmbeddedCheckoutMessenger();\n }\n\n return new IframeEmbeddedCheckoutMessenger(\n new IframeEventListener(options.parentOrigin),\n new IframeEventPoster(options.parentOrigin, parentWindow),\n new IframeEventPoster('*', parentWindow),\n { [EmbeddedCheckoutEventType.FrameLoaded]: handleFrameLoadedEvent },\n );\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"messageformat\");","import { isObject, union } from 'lodash';\nimport MessageFormat from 'messageformat';\n\nimport { Logger } from '../common/log';\nimport { bindDecorator as bind } from '../common/utility';\n\nimport LanguageConfig, { Locales, Translations } from './language-config';\n\nconst DEFAULT_LOCALE = 'en';\nconst KEY_PREFIX = 'optimized_checkout';\n\n/**\n * Responsible for getting language strings.\n *\n * This object can be used to retrieve language strings that are most\n * appropriate for a given locale.\n *\n * The language strings provided to the object should follow [ICU\n * MessageFormat](http://userguide.icu-project.org/formatparse/messages) syntax.\n */\n@bind\nexport default class LanguageService {\n private _locale: string;\n private _locales: Locales;\n private _translations: Translations;\n private _formatters: { [key: string]: any };\n\n /**\n * @internal\n */\n constructor(config: Partial, private _logger: Logger) {\n const { locale, locales, translations } = this._transformConfig(config);\n\n this._locale = locale;\n this._locales = locales;\n this._translations = translations;\n this._formatters = {};\n }\n\n /**\n * Remaps a set of language strings with a different set of keys.\n *\n * ```js\n * service.mapKeys({\n * 'new_key': 'existing_key',\n * });\n *\n * console.log(service.translate('new_key'));\n * ```\n *\n * @param maps - The set of language strings.\n */\n mapKeys(maps: { [key: string]: string }): void {\n Object.keys(maps).forEach((key) => {\n const translationKey = `${KEY_PREFIX}.${maps[key]}`;\n\n this._translations[`${KEY_PREFIX}.${key}`] = this._translations[translationKey];\n });\n }\n\n /**\n * Gets the preferred locale of the current customer.\n *\n * @returns The preferred locale code.\n */\n getLocale(): string {\n return this._hasTranslations() ? this._locale : DEFAULT_LOCALE;\n }\n\n /**\n * Gets a language string by a key.\n *\n * ```js\n * service.translate('language_key');\n * ```\n *\n * If the language string contains a placeholder, you can replace it by\n * providing a second argument.\n *\n * ```js\n * service.translate('language_key', { placeholder: 'Hello' });\n * ```\n *\n * @param key - The language key.\n * @param data - Data for replacing placeholders in the language string.\n * @returns The translated language string.\n */\n translate(key: string, data: TranslationData = {}): string {\n const prefixedKey = `${KEY_PREFIX}.${key}`;\n\n if (typeof this._translations[prefixedKey] !== 'string') {\n this._logger.warn(`Translation key \"${prefixedKey}\" is missing`);\n\n return prefixedKey;\n }\n\n if (!this._formatters[prefixedKey]) {\n const messageFormat = new MessageFormat(this._locales[prefixedKey]);\n\n this._formatters[prefixedKey] = messageFormat.compile(\n this._translations[prefixedKey] || '',\n );\n }\n\n return this._formatters[prefixedKey](this._transformData(data));\n }\n\n private _transformConfig(config: Partial = {}): LanguageConfig {\n const output: LanguageConfig = {\n defaultLocale: '',\n defaultTranslations: {},\n translations: {},\n locales: {},\n locale: config.locale || DEFAULT_LOCALE,\n };\n\n const locales = config.locales || {};\n const translations = this._flattenObject(config.translations || {});\n const defaultTranslations = this._flattenObject(config.defaultTranslations || {});\n const fallbackTranslations = this._flattenObject(config.fallbackTranslations || {});\n const translationKeys = union(\n Object.keys(fallbackTranslations),\n Object.keys(defaultTranslations),\n Object.keys(translations),\n );\n\n translationKeys.forEach((key) => {\n if (translations && translations[key]) {\n output.translations[key] = translations[key];\n output.locales[key] = locales[key] || output.locale;\n } else if (defaultTranslations[key]) {\n output.translations[key] = defaultTranslations[key];\n output.locales[key] = config.defaultLocale ?? DEFAULT_LOCALE;\n } else {\n output.translations[key] = fallbackTranslations[key];\n output.locales[key] = config.fallbackLocale ?? DEFAULT_LOCALE;\n }\n });\n\n return output;\n }\n\n private _flattenObject(\n object: Translations,\n result: Translations = {},\n parentKey = '',\n ): Translations {\n try {\n Object.keys(object).forEach((key) => {\n const value = object[key];\n const resultKey = parentKey ? `${parentKey}.${key}` : key;\n\n if (isObject(value)) {\n return this._flattenObject(value, result, resultKey);\n }\n\n result[resultKey] = value;\n });\n } catch (err) {\n this._logger.warn(`Unable to parse object: ${err}`);\n }\n\n return result;\n }\n\n private _transformData(data: TranslationData): TranslationData {\n return Object.keys(data).reduce((result, key) => {\n const value = data[key];\n\n result[key] = value === null || value === undefined ? '' : value;\n\n return result;\n }, {} as TranslationData);\n }\n\n private _hasTranslations(): boolean {\n return (\n Object.keys(this._locales)\n .map((key) => this._locales[key])\n .filter((code) => code.split('-')[0] === this._locale.split('-')[0]).length > 0\n );\n }\n}\n\nexport interface TranslationData {\n [key: string]: string | number;\n}\n","import { getDefaultLogger } from '../common/log';\n\nimport LanguageConfig from './language-config';\nimport LanguageService from './language-service';\n\n/**\n * Creates an instance of `LanguageService`.\n *\n * @remarks\n * ```js\n * const language = {{{langJson 'optimized_checkout'}}}; // `langJson` is a Handlebars helper provided by BigCommerce's Stencil template engine.\n * const service = createLanguageService(language);\n *\n * console.log(service.translate('address.city_label'));\n * ```\n *\n * @param config - A configuration object.\n * @returns An instance of `LanguageService`.\n */\nexport default function createLanguageService(\n config: Partial = {},\n): LanguageService {\n return new LanguageService(config, getDefaultLogger());\n}\n","import { InvalidArgumentError } from '../common/error/errors';\n\nimport { CurrencyConfig } from './currency';\n\nexport default class CurrencyFormatter {\n private _decimalPlaces: number;\n private _symbolLocation: string;\n private _symbol: string;\n private _thousandsSeparator: string;\n private _decimalSeparator: string;\n\n constructor(currencySettings: CurrencyConfig) {\n if (!currencySettings) {\n throw new Error('Currency settings missing');\n }\n\n const { decimalPlaces, symbolLocation, symbol, thousandsSeparator, decimalSeparator } =\n currencySettings;\n\n if (\n typeof symbolLocation !== 'string' ||\n typeof symbol !== 'string' ||\n typeof thousandsSeparator !== 'string' ||\n typeof decimalSeparator !== 'string' ||\n typeof decimalPlaces !== 'string'\n ) {\n throw new InvalidArgumentError('Invalid currency settings provided');\n }\n\n this._decimalPlaces = parseInt(decimalPlaces, 10);\n this._symbolLocation = symbolLocation;\n this._symbol = symbol;\n this._thousandsSeparator = thousandsSeparator;\n this._decimalSeparator = decimalSeparator;\n }\n\n format(amount?: number): string {\n if (typeof amount !== 'number') {\n throw new InvalidArgumentError('Invalid amount provided');\n }\n\n const formattedNumber = this._formatNumber(amount);\n\n const formattedCurrency = this._formatCurrency(formattedNumber);\n\n return amount < 0 ? `-${formattedCurrency}` : formattedCurrency;\n }\n\n private _formatNumber(amount: number): string {\n const positiveAmount = Math.abs(amount);\n const [integerAmount, decimalAmount = ''] = this._toFixed(\n positiveAmount,\n this._decimalPlaces,\n ).split('.');\n const parsedIntegerAmount = integerAmount.replace(\n /\\B(?=(\\d{3})+(?!\\d))/g,\n this._thousandsSeparator,\n );\n\n if (this._decimalPlaces < 1) {\n return parsedIntegerAmount;\n }\n\n return [parsedIntegerAmount, decimalAmount].join(this._decimalSeparator);\n }\n\n private _formatCurrency(formattedNumber: string): string {\n return this._symbolLocation.toLowerCase() === 'left'\n ? `${this._symbol}${formattedNumber}`\n : `${formattedNumber}${this._symbol}`;\n }\n\n private _toFixed(value: number, precision: number): string {\n return (+`${Math.round(+`${value}e${precision}`)}e${-precision}`).toFixed(precision);\n }\n}\n","import { bindDecorator as bind } from '../common/utility';\nimport { StoreConfig } from '../config';\n\nimport CurrencyFormatter from './currency-formatter';\n\n/**\n * Responsible for formatting and converting currencies.\n */\n@bind\nexport default class CurrencyService {\n private _customerFormatter: CurrencyFormatter;\n private _storeFormatter: CurrencyFormatter;\n\n /**\n * @internal\n */\n constructor(private _storeConfig: StoreConfig) {\n this._customerFormatter = new CurrencyFormatter(this._storeConfig.shopperCurrency);\n this._storeFormatter = new CurrencyFormatter(this._storeConfig.currency);\n }\n\n toCustomerCurrency(amount: number): string {\n const exchangeRate = this._storeConfig.shopperCurrency.exchangeRate;\n\n return this._customerFormatter.format(amount * exchangeRate);\n }\n\n toStoreCurrency(amount: number): string {\n return this._storeFormatter.format(amount);\n }\n}\n","import { StoreConfig } from '../config';\n\nimport CurrencyService from './currency-service';\n\n/**\n * Creates an instance of `CurrencyService`.\n *\n * @remarks\n * ```js\n * const { data } = checkoutService.getState();\n * const config = data.getConfig();\n * const checkout = data.getCheckout();\n * const currencyService = createCurrencyService(config);\n *\n * currencyService.toStoreCurrency(checkout.grandTotal);\n * currencyService.toCustomerCurrency(checkout.grandTotal);\n * ```\n *\n * @param config - The config object containing the currency configuration\n * @returns an instance of `CurrencyService`.\n */\nexport default function createCurrencyService(config: StoreConfig): CurrencyService {\n return new CurrencyService(config);\n}\n","import {\n AnalyticsTrackerWindow,\n isAnalyticsTrackerWindow,\n} from '@bigcommerce/checkout-sdk/analytics';\n\ninterface AnalyticsTrackerWindowGA extends AnalyticsTrackerWindow {\n ga(command: string, eventName: string, payload: AnalyticPayload): void;\n}\n\nfunction isAnalyticsTrackerWindowGA(\n window: Window | AnalyticsTrackerWindowGA,\n): window is AnalyticsTrackerWindowGA {\n return window && 'ga' in window && typeof window.ga === 'function';\n}\n\nexport function isGoogleAnalyticsAvailable(): boolean {\n return isAnalyticsTrackerWindow(window) && isAnalyticsTrackerWindowGA(window);\n}\n\nexport function sendGoogleAnalytics(type: string, payload: AnalyticPayload): void {\n if (isAnalyticsTrackerWindowGA(window)) {\n window.ga('send', type, {\n ...payload,\n nonInteraction: false,\n });\n }\n}\n\n/**\n * Max size of the payload for the Google Analytics module\n * if the limit will be succeeded, the GA throwing a silent error,\n * and only in debug mode you can see it\n */\nexport function isPayloadSizeLimitReached(obj: AnalyticPayload): boolean {\n const ANALYTICS_MAX_URI_LENGTH = 8096;\n\n return serializeAnalyticsEventPayload(obj).length >= ANALYTICS_MAX_URI_LENGTH;\n}\n\nfunction serializeAnalyticsEventPayload(obj: AnalyticPayload): string {\n return Object.keys(obj)\n .reduce((acc: string[], key) => {\n const type = typeof obj[key];\n\n if (type === 'string' || type === 'number') {\n return [...acc, `${key}=${obj[key]}`];\n }\n\n if (type === 'object' && obj[key] !== null) {\n return [...acc, serializeAnalyticsEventPayload(obj[key] as AnalyticPayload)];\n }\n\n return acc;\n }, [])\n .join('&');\n}\n\ninterface AnalyticPayload {\n [key: string]: unknown;\n}\n","import { keys } from 'lodash';\n\nimport {\n AnalyticsExtraItemsManager,\n AnalyticsTracker,\n ExtraItemsData,\n} from '@bigcommerce/checkout-sdk/analytics';\n\nimport { LineItemMap } from '../cart';\nimport { Checkout, CheckoutService } from '../checkout';\nimport { InvalidArgumentError } from '../common/error/errors';\nimport { ShopperCurrency, StoreProfile } from '../config';\nimport { Coupon } from '../coupon';\nimport { Order } from '../order';\nimport { ShippingOption } from '../shipping';\n\nimport {\n isGoogleAnalyticsAvailable,\n isPayloadSizeLimitReached,\n sendGoogleAnalytics,\n} from './analytics-tracker-ga';\nimport StepTracker from './step-tracker';\n\nexport interface StepTrackerConfig {\n checkoutSteps?: AnalyticStepType[];\n}\n\nexport type AnalyticStepType = 'customer' | 'shipping' | 'billing' | 'payment';\n\nexport enum AnalyticStepId {\n CUSTOMER = 1,\n SHIPPING,\n BILLING,\n PAYMENT,\n}\n\nconst ANALYTIC_STEPS: { [key: string]: AnalyticStepId } = {\n customer: AnalyticStepId.CUSTOMER,\n shipping: AnalyticStepId.SHIPPING,\n billing: AnalyticStepId.BILLING,\n payment: AnalyticStepId.PAYMENT,\n};\n\nexport default class AnalyticsStepTracker implements StepTracker {\n private _checkoutStarted = false;\n private _completedSteps: { [key: string]: boolean } = {};\n private _viewedSteps: { [key in AnalyticStepId]?: boolean } = {};\n private _analyticStepOrder: AnalyticStepType[] = ['customer', 'shipping', 'billing', 'payment'];\n\n constructor(\n private checkoutService: CheckoutService,\n private analyticsExtraItemsManager: AnalyticsExtraItemsManager,\n private analytics: AnalyticsTracker,\n { checkoutSteps }: StepTrackerConfig = {},\n ) {\n if (checkoutSteps !== undefined) {\n if (checkoutSteps.some((value) => !(value in ANALYTIC_STEPS))) {\n throw new InvalidArgumentError(\n `Invalid checkout steps provided. Valid values are: ${keys(ANALYTIC_STEPS).join(\n ', ',\n )}.`,\n );\n }\n\n this._analyticStepOrder = checkoutSteps;\n }\n }\n\n trackCheckoutStarted(): void {\n if (this._checkoutStarted) {\n return;\n }\n\n const checkout = this.getCheckout();\n\n if (!checkout) {\n return;\n }\n\n const {\n coupons,\n grandTotal,\n shippingCostTotal,\n taxTotal,\n cart: { lineItems, discountAmount, id },\n } = checkout;\n\n const extraItemsData = this.analyticsExtraItemsManager.saveExtraItemsData(id, lineItems);\n\n this.analytics.track(\n 'Checkout Started',\n this.getTrackingPayload({\n revenue: grandTotal,\n shipping: shippingCostTotal,\n tax: taxTotal,\n discount: discountAmount,\n coupons,\n lineItems,\n extraItemsData,\n }),\n );\n\n this._checkoutStarted = true;\n }\n\n trackOrderComplete(): void {\n const order = this.getOrder();\n\n if (!order) {\n return;\n }\n\n const {\n isComplete,\n orderId,\n orderAmount,\n shippingCostTotal,\n taxTotal,\n discountAmount,\n coupons,\n lineItems,\n cartId,\n } = order;\n\n if (!isComplete) {\n return;\n }\n\n const extraItemsData = this.analyticsExtraItemsManager.readExtraItemsData(cartId);\n\n if (extraItemsData === null) {\n return;\n }\n\n const isMissingOrdersExperimentEnabled = this.checkoutService.getState().data.getConfig()\n ?.checkoutSettings.features['DATA-6891.missing_orders_within_GA'];\n\n const payload = this.getTrackingPayload({\n orderId,\n revenue: orderAmount,\n shipping: shippingCostTotal,\n tax: taxTotal,\n discount: discountAmount,\n coupons,\n extraItemsData,\n lineItems,\n });\n\n if (\n isMissingOrdersExperimentEnabled &&\n isGoogleAnalyticsAvailable() &&\n isPayloadSizeLimitReached(payload)\n ) {\n sendGoogleAnalytics('transaction', {\n '&ti': payload.orderId,\n '&ta': payload.affiliation,\n '&tr': payload.revenue,\n '&ts': payload.shipping,\n '&tt': payload.tax,\n '&tcc': payload.coupon,\n '&cu': payload.currency,\n });\n payload.products.forEach((product) => {\n sendGoogleAnalytics('item', {\n '&ti': payload.orderId,\n '&in': product.name,\n '&ic': product.sku,\n '&iv': `${product.category}`,\n '&ip': product.price,\n '&iq': product.quantity,\n });\n });\n\n // TODO: decide how to send large orders to Segment without sending to GA again\n return this.analyticsExtraItemsManager.clearExtraItemData(cartId);\n }\n\n this.analytics.track('Order Completed', payload);\n\n this.analyticsExtraItemsManager.clearExtraItemData(cartId);\n }\n\n trackStepViewed(step: AnalyticStepType): void {\n const stepId = this.getIdFromStep(step);\n\n if (!stepId || this.hasStepViewed(stepId)) {\n return;\n }\n\n this.trackViewed(stepId);\n this.backfill(stepId);\n }\n\n trackStepCompleted(step: AnalyticStepType): void {\n const stepId = this.getIdFromStep(step);\n\n if (!stepId || this.hasStepCompleted(stepId)) {\n return;\n }\n\n this.backfill(stepId);\n this.trackCompleted(stepId);\n }\n\n private backfill(stepId: AnalyticStepId): void {\n for (const i of this._analyticStepOrder) {\n const id = this.getIdFromStep(i);\n\n if (!id) {\n break;\n }\n\n if (!this.hasStepViewed(id)) {\n this.trackViewed(id);\n }\n\n if (id === stepId) {\n break;\n }\n\n if (!this.hasStepCompleted(id)) {\n this.trackCompleted(id);\n }\n }\n }\n\n private trackCompleted(stepId: AnalyticStepId): void {\n const shippingMethod = this.getSelectedShippingOption();\n const { code: currency = '' } = this.getShopperCurrency() || {};\n const paymentMethod = this.getPaymentMethodName();\n\n const payload: {\n step: number;\n currency: string;\n shippingMethod?: string;\n paymentMethod?: string;\n } = {\n step: stepId,\n currency,\n };\n\n if (shippingMethod) {\n payload.shippingMethod = shippingMethod.description;\n }\n\n if (paymentMethod) {\n payload.paymentMethod = paymentMethod;\n }\n\n // due to an issue with the way the segment library works, we must send at least one of the two\n // options--otherwise it rejects the track call with no diagnostic messages. however, if we blindly\n // include both options, it sends a single comma for the value, which is undesireable. by only adding\n // one of the two (shippingMethod here being arbitrarily chosen), we always have at least one value, but\n // never send two empty values.\n if (!payload.shippingMethod && !payload.paymentMethod) {\n payload.shippingMethod = ' ';\n }\n\n this.analytics.track('Checkout Step Completed', payload);\n\n const shippingMethodId = shippingMethod ? shippingMethod.id : '';\n const completedStepId =\n stepId === AnalyticStepId.SHIPPING ? `${stepId}-${shippingMethodId}` : stepId;\n\n this._completedSteps[completedStepId] = true;\n }\n\n private getTrackingPayload({\n orderId,\n revenue,\n shipping,\n tax,\n discount,\n coupons,\n extraItemsData,\n lineItems,\n }: {\n orderId?: number;\n revenue: number;\n shipping: number;\n tax: number;\n discount: number;\n coupons: Coupon[];\n extraItemsData: ExtraItemsData;\n lineItems: LineItemMap;\n }) {\n const { code = '' } = this.getShopperCurrency() || {};\n const { storeName = '' } = this.getStoreProfile() || {};\n\n return {\n orderId,\n affiliation: storeName,\n revenue: this.toShopperCurrency(revenue),\n shipping: this.toShopperCurrency(shipping),\n tax: this.toShopperCurrency(tax),\n discount: this.toShopperCurrency(discount),\n coupon: (coupons || []).map((coupon) => coupon.code.toUpperCase()).join(','),\n currency: code,\n products: this.getProducts(extraItemsData, lineItems),\n };\n }\n\n private hasStepCompleted(stepId: AnalyticStepId): boolean {\n const shippingOption = this.getSelectedShippingOption();\n const shippingMethodId = shippingOption ? shippingOption.id : '';\n\n return (\n Object.prototype.hasOwnProperty.call(this._completedSteps, stepId) ||\n (stepId === AnalyticStepId.SHIPPING &&\n Object.prototype.hasOwnProperty.call(\n this._completedSteps,\n `${stepId}-${shippingMethodId}`,\n ))\n );\n }\n\n private hasStepViewed(stepId: AnalyticStepId): boolean {\n return !!this._viewedSteps[stepId];\n }\n\n private getIdFromStep(step: string): AnalyticStepId | null {\n const name = step.split('.');\n\n return ANALYTIC_STEPS[name[0]] || null;\n }\n\n private trackViewed(stepId: AnalyticStepId): void {\n const currency = this.getShopperCurrency();\n\n this.analytics.track('Checkout Step Viewed', {\n step: stepId,\n currency: currency ? currency.code : '',\n });\n\n this._viewedSteps[stepId] = true;\n }\n\n private getOrder(): Order | undefined {\n const {\n data: { getOrder },\n } = this.checkoutService.getState();\n\n return getOrder();\n }\n\n private getCheckout(): Checkout | undefined {\n const {\n data: { getCheckout },\n } = this.checkoutService.getState();\n\n return getCheckout();\n }\n\n private getShopperCurrency(): ShopperCurrency | undefined {\n const {\n data: { getConfig },\n } = this.checkoutService.getState();\n const config = getConfig();\n\n return config && config.shopperCurrency;\n }\n\n private getStoreProfile(): StoreProfile | undefined {\n const {\n data: { getConfig },\n } = this.checkoutService.getState();\n const config = getConfig();\n\n return config && config.storeProfile;\n }\n\n private toShopperCurrency(amount: number): number {\n const { exchangeRate = 1 } = this.getShopperCurrency() || {};\n\n return Math.round(amount * exchangeRate * 100) / 100;\n }\n\n private getSelectedShippingOption(): ShippingOption | null {\n const { data } = this.checkoutService.getState();\n const shippingOption = data.getSelectedShippingOption();\n\n return shippingOption && shippingOption.id && shippingOption.description\n ? shippingOption\n : null;\n }\n\n private getPaymentMethodName(): string {\n const { data } = this.checkoutService.getState();\n const paymentMethod = data.getSelectedPaymentMethod();\n\n return paymentMethod && paymentMethod.config ? paymentMethod.config.displayName || '' : '';\n }\n\n private getProducts(itemsData: ExtraItemsData, lineItems: LineItemMap): AnalyticsProduct[] {\n const customItems: AnalyticsProduct[] = (lineItems.customItems || []).map((item) => ({\n product_id: item.id,\n sku: item.sku,\n price: item.listPrice,\n quantity: item.quantity,\n name: item.name,\n }));\n\n const giftCertificateItems: AnalyticsProduct[] = lineItems.giftCertificates.map((item) => {\n return {\n product_id: item.id,\n price: this.toShopperCurrency(item.amount),\n name: item.name,\n quantity: 1,\n };\n });\n\n const physicalAndDigitalItems: AnalyticsProduct[] = [\n ...lineItems.physicalItems,\n ...lineItems.digitalItems,\n ].map((item) => {\n let itemAttributes;\n\n if (item.options && item.options.length) {\n itemAttributes = item.options.map((option) => `${option.name}:${option.value}`);\n itemAttributes.sort();\n }\n\n return {\n product_id: item.productId,\n sku: item.sku,\n price: item.salePrice,\n image_url: item.imageUrl,\n name: item.name,\n quantity: item.quantity,\n brand: itemsData[item.productId] ? itemsData[item.productId].brand : '',\n category: itemsData[item.productId] ? itemsData[item.productId].category : '',\n variant: (itemAttributes || []).join(', '),\n };\n });\n\n return [...customItems, ...physicalAndDigitalItems, ...giftCertificateItems];\n }\n}\n\nexport interface AnalyticsProduct {\n product_id: string | number;\n price: number;\n quantity: number;\n name: string;\n sku?: string;\n image_url?: string;\n category?: string;\n variant?: string;\n brand?: string;\n}\n","import StepTracker from './step-tracker';\n\nexport default class NoopStepTracker implements StepTracker {\n trackCheckoutStarted(): void {}\n\n trackOrderComplete(): void {}\n\n trackStepViewed(): void {}\n\n trackStepCompleted(): void {}\n}\n","import localStorageFallback from 'local-storage-fallback';\n\nimport {\n AnalyticsExtraItemsManager,\n isAnalyticsTrackerWindow,\n} from '@bigcommerce/checkout-sdk/analytics';\n\nimport { CheckoutService } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\n\nimport AnalyticsStepTracker, { StepTrackerConfig } from './analytics-step-tracker';\nimport NoopStepTracker from './noop-step-tracker';\nimport StepTracker from './step-tracker';\n\n/**\n * Creates an instance of `StepTracker`.\n *\n * @remarks\n * ```js\n * const checkoutService = createCheckoutService();\n * await checkoutService.loadCheckout();\n * const stepTracker = createStepTracker(checkoutService);\n *\n * stepTracker.trackCheckoutStarted();\n * ```\n *\n * @param CheckoutService - An instance of CheckoutService\n * @param StepTrackerConfig - A step tracker config object\n * @returns an instance of `StepTracker`.\n */\nexport default function createStepTracker(\n checkoutService: CheckoutService,\n stepTrackerConfig?: StepTrackerConfig,\n): StepTracker {\n const { data } = checkoutService.getState();\n const config = data.getConfig();\n\n if (!config) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const { isAnalyticsEnabled } = config.checkoutSettings;\n\n if (isAnalyticsEnabled && isAnalyticsTrackerWindow(window)) {\n return new AnalyticsStepTracker(\n checkoutService,\n new AnalyticsExtraItemsManager(localStorageFallback),\n window.analytics,\n stepTrackerConfig,\n );\n }\n\n return new NoopStepTracker();\n}\n","export enum AnalyticStepType {\n CUSTOMER = 'customer',\n SHIPPING = 'shipping',\n BILLING = 'billing',\n PAYMENT = 'payment',\n}\n\nexport const AnalyticStepOrder: AnalyticStepType[] = [\n AnalyticStepType.CUSTOMER,\n AnalyticStepType.SHIPPING,\n AnalyticStepType.BILLING,\n AnalyticStepType.PAYMENT,\n];\n","import { LineItem, LineItemMap } from '../cart';\nimport { CheckoutSelectors, CheckoutStoreSelector } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { flatten } from 'lodash';\n\nimport { AnalyticStepOrder, AnalyticStepType } from './analytics-steps';\nimport BodlService from './bodl-service';\nimport {\n BodlEventsCheckout,\n BodlEventsPayload,\n BODLProduct,\n CommonCheckoutData,\n} from './bodl-window';\n\nexport default class BodlEmitterService implements BodlService {\n private _checkoutStarted = false;\n private _emailEntryBegan = false;\n private _shippingOptionsShown = false;\n private _completedSteps: { [key: string]: boolean } = {};\n private state?: CheckoutStoreSelector;\n\n constructor(\n private subscribe: (subscriber: (state: CheckoutSelectors) => void) => void,\n private bodlEvents: BodlEventsCheckout,\n ) {\n this.subscribe((state) => {\n this.setState(state.data);\n\n const config = this.state?.getConfig();\n\n if (!config) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n });\n }\n\n setState(state: CheckoutStoreSelector) {\n this.state = state;\n }\n\n checkoutBegin(): void {\n const data = this._getCommonCheckoutData();\n\n if (this._checkoutStarted || !data) {\n return;\n }\n\n this.bodlEvents.emitCheckoutBeginEvent(data);\n\n this._checkoutStarted = true;\n }\n\n orderPurchased(): void {\n const order = this.state?.getOrder();\n\n if (!order) {\n return;\n }\n\n const {\n currency,\n isComplete,\n orderId,\n orderAmount,\n shippingCostTotal,\n lineItems,\n cartId,\n coupons,\n channelId,\n taxTotal,\n } = order;\n\n if (!isComplete) {\n return;\n }\n\n this.bodlEvents.emitOrderPurchasedEvent({\n event_id: cartId,\n currency: currency.code,\n order_id: orderId,\n tax: taxTotal,\n channel_id: channelId,\n cart_value: orderAmount,\n coupon_codes: coupons.map((coupon) => coupon.code.toUpperCase()),\n shipping_cost: shippingCostTotal,\n line_items: this._getProducts(lineItems, currency.code),\n });\n }\n\n stepCompleted(currentStep?: AnalyticStepType): void {\n if (!currentStep) {\n return;\n }\n\n AnalyticStepOrder.some((step: AnalyticStepType) => {\n if (!this._hasStepCompleted(step)) {\n this._trackCompletedStep(step);\n }\n\n return step === currentStep;\n });\n }\n\n customerEmailEntry(email?: string) {\n if (this._emailEntryBegan || !email?.length) {\n return;\n }\n\n this._emailEntryBegan = true;\n this.bodlEvents.emit('bodl_checkout_email_entry_began');\n }\n\n customerSuggestionInit(payload?: BodlEventsPayload) {\n this.bodlEvents.emit('bodl_checkout_customer_suggestion_initialization', payload);\n }\n\n customerSuggestionExecute() {\n this.bodlEvents.emit('bodl_checkout_customer_suggestion_execute');\n }\n\n customerPaymentMethodExecuted(payload?: BodlEventsPayload) {\n this.bodlEvents.emit('bodl_checkout_customer_payment_method_executed', payload);\n }\n\n showShippingMethods() {\n if (this._shippingOptionsShown) {\n return;\n }\n\n this._shippingOptionsShown = true;\n this.bodlEvents.emit('bodl_checkout_show_shipping_options');\n }\n\n selectedPaymentMethod(paymentOption?: string) {\n const commonData = this._getCommonCheckoutData();\n\n if (!commonData || !paymentOption) {\n return;\n }\n\n this.bodlEvents.emitPaymentDetailsProvidedEvent({\n ...commonData,\n payment_type: paymentOption,\n });\n }\n\n clickPayButton(payload?: BodlEventsPayload) {\n this.bodlEvents.emit('bodl_checkout_click_pay_button', payload);\n }\n\n paymentRejected() {\n this.bodlEvents.emit('bodl_checkout_payment_rejected');\n }\n\n paymentComplete() {\n this.bodlEvents.emit('bodl_checkout_payment_complete');\n }\n\n exitCheckout() {\n this.bodlEvents.emit('bodl_checkout_exit');\n }\n\n private _trackCompletedStep(step: AnalyticStepType) {\n this._completedSteps[step] = true;\n\n const bodlEventsMap: { [key in AnalyticStepType]?: () => void } = {\n [AnalyticStepType.SHIPPING]: this._trackShippingStepCompleted.bind(this),\n };\n const emit = bodlEventsMap[step];\n\n if (emit) {\n emit();\n } else {\n this.bodlEvents.emit('bodl_checkout_step_completed', { step });\n }\n }\n\n private _trackShippingStepCompleted(): void {\n const shippingMethod = this.state?.getSelectedShippingOption()?.description;\n const commonData = this._getCommonCheckoutData();\n\n if (!commonData || !shippingMethod) {\n return;\n }\n\n this.bodlEvents.emitShippingDetailsProvidedEvent({\n ...commonData,\n shipping_method: shippingMethod,\n });\n }\n\n private _getCommonCheckoutData(): CommonCheckoutData | null {\n const checkout = this.state?.getCheckout();\n\n if (!checkout) {\n return null;\n }\n\n const {\n cart: { cartAmount, currency, lineItems, id, coupons },\n channelId,\n } = checkout;\n\n return {\n event_id: id,\n currency: currency.code,\n cart_value: cartAmount,\n coupon_codes: coupons.map((coupon) => coupon.code.toUpperCase()),\n line_items: this._getProducts(lineItems, currency.code),\n channel_id: channelId,\n };\n }\n\n private _getProducts(lineItems: LineItemMap, currencyCode: string): BODLProduct[] {\n const customItems: BODLProduct[] = (lineItems.customItems || []).map((item) => ({\n product_id: item.id,\n sku: item.sku,\n base_price: item.listPrice,\n sale_price: item.listPrice,\n purchase_price: item.listPrice,\n quantity: item.quantity,\n product_name: item.name,\n currency: currencyCode,\n }));\n\n const giftCertificateItems: BODLProduct[] = lineItems.giftCertificates.map((item) => {\n return {\n product_id: item.id,\n gift_certificate_id: item.id,\n base_price: item.amount,\n sale_price: item.amount,\n purchase_price: item.amount,\n product_name: item.name,\n gift_certificate_name: item.name,\n gift_certificate_theme: item.theme,\n quantity: 1,\n currency: currencyCode,\n };\n });\n\n const physicalAndDigitalItems: BODLProduct[] = [\n ...lineItems.physicalItems,\n ...lineItems.digitalItems,\n ].map((item) => {\n const getCategoryNames = (lineItem: LineItem): string[] => {\n if (Array.isArray(lineItem.categoryNames)) {\n return lineItem.categoryNames;\n } else if (Array.isArray(lineItem.categories)) {\n return flatten(lineItem.categories).map(({ name }) => name);\n }\n\n return [];\n };\n\n let itemAttributes;\n\n if (item.options && item.options.length) {\n itemAttributes = item.options.map((option) => `${option.name}:${option.value}`);\n itemAttributes.sort();\n }\n\n return {\n product_id: item.productId,\n quantity: item.quantity,\n product_name: item.name,\n base_price: item.listPrice,\n sale_price: item.salePrice,\n purchase_price: item.salePrice > 0 ? item.salePrice : item.listPrice,\n sku: item.sku,\n variant_id: item.variantId,\n discount: item.discountAmount,\n brand_name: item.brand,\n currency: currencyCode,\n category_names: getCategoryNames(item),\n retail_price: item.retailPrice,\n };\n });\n\n return [...customItems, ...physicalAndDigitalItems, ...giftCertificateItems].map(\n (item) => ({\n ...item,\n product_id: String(item.product_id),\n }),\n );\n }\n\n private _hasStepCompleted(step: AnalyticStepType): boolean {\n return this._completedSteps[step];\n }\n}\n","import BodlService from './bodl-service';\n\nexport default class NoopBodlService implements BodlService {\n checkoutBegin(): void {}\n\n orderPurchased(): void {}\n\n stepCompleted(): void {}\n\n customerEmailEntry(): void {}\n\n customerSuggestionInit(): void {}\n\n customerSuggestionExecute(): void {}\n\n customerPaymentMethodExecuted(): void {}\n\n showShippingMethods(): void {}\n\n selectedPaymentMethod(): void {}\n\n clickPayButton(): void {}\n\n paymentRejected(): void {}\n\n paymentComplete(): void {}\n\n exitCheckout(): void {}\n}\n","import { CheckoutSelectors } from '../checkout';\n\nimport BodlEmitterService from './bodl-emitter-service';\nimport BodlService from './bodl-service';\nimport { isBodlEnabled } from './is-bodl-enabled';\nimport NoopBodlService from './noop-bodl-service';\n\n/**\n * Creates an instance of `BodlService`.\n *\n * @remarks\n *\n * ```js\n * const bodlService = BodlService();\n * bodlService.checkoutBegin();\n *\n * ```\n *\n * @param {CheckoutService} checkoutService - An instance of CheckoutService\n * @returns an instance of `BodlService`.\n */\nexport default function createBodlService(\n subscribe: (subscriber: (state: CheckoutSelectors) => void) => void,\n): BodlService {\n if (isBodlEnabled(window)) {\n return new BodlEmitterService(subscribe, window.bodlEvents.checkout);\n }\n\n return new NoopBodlService();\n}\n","import BodlEventsWindow from './bodl-window';\n\nexport function isBodlEnabled(window: Window): window is BodlEventsWindow {\n return 'bodlEvents' in window;\n}\n"],"names":["module","exports","require","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","undefined","__webpack_modules__","n","getter","__esModule","d","a","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","r","Symbol","toStringTag","value","throwErrorAction","type","error","meta","action","concat","of","throwError","createErrorAction","payload","message","object","name","setPrototypeOf","__proto__","Error","captureStackTrace","stack","MissingDataErrorType","subtype","MissingBillingAddress","MissingCart","MissingConsignments","MissingCheckout","MissingCustomer","MissingCheckoutConfig","MissingOrderConfig","MissingOrder","MissingOrderId","MissingPayment","MissingPaymentToken","MissingPaymentMethod","MissingShippingAddress","getErrorMessage","BillingAddressActionType","_requestSender","_subscriptionActionCreator","continueAsGuest","credentials","options","store","state","getState","checkout","getCheckout","customer","getCustomer","isGuest","billingAddressRequestBody","billingAddress","getBillingAddress","existingBillingAddressRequestBody","merge","createAction","ContinueAsGuestRequested","defer","this","_createOrUpdateBillingAddress","id","body","ContinueAsGuestSucceeded","pipe","catchError","ContinueAsGuestFailed","_updateCustomerConsent","updateAddress","address","Observable","observer","next","UpdateBillingAddressRequested","email","then","UpdateBillingAddressSucceeded","complete","catch","response","UpdateBillingAddressFailed","acceptsAbandonedCartEmails","acceptsMarketingNewsletter","empty","updateSubscriptions","checkoutId","createAddress","ContentType","SDK_VERSION_HEADERS","DEFAULT_PARAMS","include","join","timeout","url","headers","Accept","post","params","put","ErrorActionType","clearError","ClearError","getEnvironment","process","env","NODE_ENV","e","_console","log","_logToConsole","messages","info","warn","debug","isEnabled","logger","console","getDefaultLogger","cachableActionDecorator","_","descriptor","memoizedMethods","WeakMap","decorateMethod","method","param","lastArg","args","length","useCache","fn","instanceMethods","set","memoize","from","shareReplay","ConfigActionType","_configRequestSender","loadConfig","LoadConfigRequested","LoadConfigSucceeded","LoadConfigFailed","DEFAULT_RESPONSE","status","errors","title","INTERNAL_USE_ONLY","CouponActionType","_couponRequestSender","applyCoupon","code","ApplyCouponRequested","ApplyCouponSucceeded","ApplyCouponFailed","removeCoupon","RemoveCouponRequested","RemoveCouponSucceeded","RemoveCouponFailed","CheckoutIncludes","joinIncludes","includes","uniq","couponCode","AvailableShippingOptions","delete","GiftCertificateActionType","_giftCertificateRequestSender","applyGiftCertificate","giftCertificate","ApplyGiftCertificateRequested","ApplyGiftCertificateSucceeded","ApplyGiftCertificateFailed","removeGiftCertificate","RemoveGiftCertificateRequested","RemoveGiftCertificateSucceeded","RemoveGiftCertificateFailed","giftCertificateCode","isResolvableModule","_factories","_instances","_defaultToken","defaultToken","_useFallback","useFallback","_tokenResolver","tokenResolver","token","cacheToken","_getInstance","register","factory","_hasFactory","_hasInstance","resolvedToken","keys","_registry","_resolveToken","bind","resolveId","_encodeToken","btoa","JSON","stringify","_decodeToken","parse","atob","registeredTokens","query","results","forEach","registeredToken","resolverId","result","matches","default","entries","push","matchedResults","sort","b","filter","matched","find","toResolvableModule","resolveIds","assign","assertApplePayWindow","window","isApplePayWindow","create","request","ApplePaySession","DefaultLabels","_paymentIntegrationService","_sessionFactory","_onAuthorizeCallback","noop","_onError","_subTotalLabel","Subtotal","_shippingLabel","Shipping","initialize","methodId","applepay","container","shippingLabel","subtotalLabel","onError","onPaymentAuthorize","loadPaymentMethod","_paymentMethod","getPaymentMethodOrThrow","verifyCheckoutSpamProtection","_applePayButton","_createButton","addEventListener","_handleWalletButtonClick","deinitialize","Promise","resolve","signIn","signOut","executePaymentMethodCheckout","continueWithCheckoutCallback","containerId","document","getElementById","button","createElement","setAttribute","appendChild","event","preventDefault","cart","getCartOrThrow","config","getStoreConfigOrThrow","getCheckoutOrThrow","initializationData","_getBaseRequest","applePaySession","_handleApplePayEvents","begin","paymentMethod","storeCountryCode","storeName","decimalPlaces","merchantCapabilities","supportedNetworks","requiresShipping","lineItems","physicalItems","requiredBillingContactFields","requiredShippingContactFields","countryCode","currencyCode","total","label","amount","grandTotal","toFixed","subtotal","taxes","tax","onvalidatemerchant","_onValidateMerchant","merchantSession","completeMerchantValidation","onshippingcontactselected","_handleShippingContactSelected","onshippingmethodselected","_handleShippingMethodSelected","oncancel","loadCheckout","onpaymentauthorized","_onPaymentAuthorized","shippingAddress","_transformContactToAddress","shippingContact","updateShippingAddress","abort","selectionShippingOptionId","consignments","selectedShippingOption","availableOptions","availableShippingOptions","selectedOption","unselectedOptions","option","shippingOptions","description","cost","detail","additionalDescription","identifier","isRecommended","Array","completeShippingContactSelection","STATUS_INVALID_SHIPPING_POSTAL_ADDRESS","recommendedOption","optionId","selectedOptionId","_updateShippingOption","newShippingMethods","newTotal","newLineItems","_getUpdatedLineItems","completeShippingMethodSelection","shippingCostTotal","selectShippingOption","paymentData","validationURL","merchantId","location","hostname","bigPayEndpoint","paymentsUrl","payment","billingContact","formattedPayload","apple_pay_token","payment_data","payment_method","transaction_id","transactionIdentifier","transformedBillingAddress","transformedShippingAddress","emailAddress","phone","phoneNumber","updateBillingAddress","submitOrder","useStoreCredit","submitPayment","completePayment","STATUS_SUCCESS","STATUS_FAILURE","contact","firstName","givenName","lastName","familyName","city","locality","company","address1","addressLines","address2","postalCode","stateOrProvince","administrativeArea","stateOrProvinceCode","customFields","paymentIntegrationService","getHost","createRequestSender","host","NotInitializedErrorType","CustomerNotInitialized","PaymentNotInitialized","ShippingNotInitialized","SpamProtectionNotInitialized","boltScriptLoader","boltHostWindow","bolt","onInit","publishableKey","developerConfig","loadBoltClient","testMode","getCustomerEmail","hasBoltAccount","signInCustomer","signOutCustomer","checkoutPaymentMethodExecuted","openBoltCheckoutModalOrThrow","boltClient","getBoltClientOrThrow","getPaymentMethod","embeddedOneClickEnabled","callbacks","close","openCheckout","BoltCheckout","BoltDeveloperMode","StyleButtonSize","StyleButtonShape","scriptLoader","developerModeParams","cartId","storefrontApiToken","loadScript","getDomainURL","getScriptOptions","loadBoltEmbedded","async","attributes","Bolt","developerMode","StagingMode","DevelopmentMode","developerDomain","getScriptLoader","BraintreeEnv","isBraintreeError","Boolean","PaypalButtonStyleLayoutOption","PaypalButtonStyleSizeOption","PaypalButtonStyleColorOption","PaypalButtonStyleLabelOption","PaypalButtonStyleShapeOption","PAYPAL_COMPONENTS","braintreeScriptLoader","braintreeHostWindow","dataCollectors","clientToken","getClient","client","loadClient","clientCreator","authorization","getPaypalCheckout","onSuccess","loadPaypalCheckout","paypalCheckout","paypalCheckoutConfig","paypalCheckoutCallback","braintreePaypalCheckout","paypalSdkLoadConfig","currency","isCreditEnabled","components","toString","intent","paypal","loadPayPalSDK","loadBraintreeLocalMethods","getLocalPaymentInstance","merchantAccountId","braintreeLocalMethods","localPaymentErr","localPaymentInstance","getUsBankAccount","usBankAccount","loadUsBankAccount","getDataCollector","cacheKey","cached","loadDataCollector","kount","deviceData","teardown","getBraintreeEnv","isTestMode","Sandbox","Production","mapToBraintreeShippingAddressOverride","recipientName","line1","line2","mapToLegacyShippingAddress","details","split","first_name","last_name","phone_number","address_line_1","address_line_2","country_code","postal_code","mapToLegacyBillingAddress","removeElement","elementId","element","remove","getSessionId","teardownModule","VERSION","braintree","localPayment","dataCollector","formPoster","braintreeIntegrationService","braintreepaypal","buttonHeight","paypalCheckoutOptions","paypalCheckoutSuccessCallback","renderPayPalButton","paypalCheckoutErrorCallback","handleError","fundingSource","FUNDING","PAYPAL","paypalButtonRender","Buttons","commit","style","height","createOrder","setupPayment","onApprove","authorizeData","tokenizePayment","isEligible","render","loadDefaultCheckout","outstandingBalance","addresses","shippingAddressOverride","createPayment","flow","enableShippingAddress","shippingAddressEditable","offerCredit","tokenizePayload","nonce","postForm","payment_type","provider","device_data","billing_address","shipping_address","buttonContainerId","onErrorCallback","createFormPoster","CartSource","PayPalCommerceIntent","StyleButtonLabel","StyleButtonColor","NonInstantAlternativePaymentMethods","PayPalOrderStatus","paypalCommerceRequestSender","paypalCommerceScriptLoader","loadPayPalSdk","providedCurrencyCode","initializesOnCheckoutPage","getPayPalSDK","paypalSdk","getPayPalSdkOrThrow","createBuyNowCartOrThrow","buyNowInitializeOptions","cartRequestBody","getBuyNowCartRequestBody","createBuyNowCart","providerId","requestBody","updateOrder","consignment","getConsignmentsOrThrow","getOrderStatus","orderId","order_id","source","BuyNow","cart_id","vault_payment_instrument","set_as_default_stored_instrument","device_info","method_id","paypal_account","getShippingOptionOrThrow","selectedShippingOptionId","recommendedShippingOption","shippingOptionToSelect","getAddress","getBillingAddressFromOrderDetails","payer","given_name","surname","email_address","admin_area_2","admin_area_1","getShippingAddressFromOrderDetails","orderDetails","shipping","getValidButtonStyle","color","shape","validStyles","getValidHeight","omitBy","isNil","requestSender","getPayPalSdkScriptConfigOrThrow","paypalSdkScriptConfig","paypalLoadScript","clientId","buyerCountry","attributionId","isVenmoEnabled","isHostedCheckoutEnabled","isPayPalCreditAvailable","isDeveloperModeApplicable","availableAlternativePaymentMethods","enabledAlternativePaymentMethods","shouldEnableCard","enableCardFunding","disableCardFunding","enableCreditFunding","disableCreditFunding","shouldEnableAPMs","enableVenmoFunding","disableVenmoFunding","enableAPMsFunding","disableAPMsFunding","apm","disableFunding","enableFunding","paypalCommerceIntegrationService","paypalcommerce","renderButton","onComplete","defaultCallbacks","orderID","hostedCheckoutCallbacks","onShippingAddressChange","data","onShippingOptionsChange","actions","onHostedCheckoutApprove","buttonRenderOptions","paypalButton","order","shippingOption","paypalcommercecredit","paypalCommerceCredit","fundingSources","PAYLATER","CREDIT","hasRenderedSmartButton","gold","paypalcommercevenmo","VENMO","createCustomerStrategyRegistry","customerStrategyFactories","registry","createCustomerStrategy","isSpamProtectionExecuteSucceededAction","succeededAction","CustomerActionType","_customerRequestSender","_checkoutActionCreator","_spamProtectionActionCreator","createCustomer","customerAccount","isStorefrontSpamProtectionEnabled","checkoutSettings","createAccount","switchMap","loadCurrentCheckout","CreateCustomerSucceeded","CreateCustomerRequested","execute","CreateCustomerFailed","customerAddress","CreateCustomerAddressRequested","CreateCustomerAddressSucceeded","CreateCustomerAddressFailed","SignInCustomerRequested","SignInCustomerSucceeded","SignInCustomerFailed","SignOutCustomerRequested","SignOutCustomerSucceeded","SignOutCustomerFailed","CustomerStrategyActionType","_strategyRegistry","_strategyRegistryV2","SignInRequested","_getStrategy","SignInSucceeded","SignInFailed","SignOutRequested","SignOutSucceeded","SignOutFailed","ExecutePaymentMethodCheckoutRequested","ExecutePaymentMethodCheckoutSucceeded","ExecutePaymentMethodCheckoutFailed","customerStrategies","isInitialized","InitializeRequested","InitializeSucceeded","InitializeFailed","DeinitializeRequested","DeinitializeSucceeded","DeinitializeFailed","widgetInteraction","WidgetInteractionStarted","WidgetInteractionFinished","WidgetInteractionFailed","strategy","joinOrMergeIncludes","baseIncludes","includeDictionaryOrList","isArray","includesDictionary","deletions","pickBy","on","additions","difference","mergeIncludes","updateCheckout","CheckoutActionType","_checkoutRequestSender","_configActionCreator","_formFieldsActionCreator","LoadCheckoutRequested","loadFormFields","LoadCheckoutSucceeded","LoadCheckoutFailed","context","getContextConfig","UpdateCheckoutRequested","UpdateCheckoutSucceeded","UpdateCheckoutFailed","FormFieldsActionType","_formFieldsRequestSender","LoadFormFieldsRequested","loadFields","LoadFormFieldsSucceeded","LoadFormFieldsFailed","PaymentMethodActionType","loadPaymentMethods","LoadPaymentMethodsRequested","deviceSessionId","sessionHash","methods","filteredMethods","_filterApplePay","LoadPaymentMethodsSucceeded","LoadPaymentMethodsFailed","getCart","LoadPaymentMethodRequested","LoadPaymentMethodSucceeded","LoadPaymentMethodFailed","isEqual","cartA","cartB","_normalize","cartAmount","digitalItems","slice","itemA","itemB","productId","variantId","localeCompare","map","item","extendedSalePrice","quantity","giftCertificates","recipient","giftWrapping","previous","updated","validate","comparator","_compareCoupons","coupons","_compareGiftCertificates","_getComparableCheckout","couponsA","couponsB","giftCertificatesA","giftCertificatesB","promise","cancellable","reject","cancel","race","_mutationObserver","ensurePresence","targets","mutationsList","mutation","removedNodes","node","some","target","contains","observe","childList","subtree","output","disconnect","_window","callback","MutationObserver","parseUrl","test","anchor","href","port","indexOf","hash","origin","protocol","pathname","search","isIframeEvent","targetOrigin","_targetWindow","_targetOrigin","targetWindow","fromEvent","successType","errorType","take","toPromise","postMessage","setTarget","bindMethodDecorator","decoratedTarget","getOwnPropertyNames","getOwnPropertyDescriptor","bindClassDecorator","boundMethod","sourceOrigin","_sourceOrigins","replace","_isListening","_listeners","listen","_handleMessage","stopListen","removeEventListener","addListener","listener","listeners","removeListener","index","splice","trigger","_googleRecaptcha","handle","errorOrId","handleWithRecaptchaSitekey","handleWithPaymentHumanVerificationRequestError","_isPaymentHumanVerificationRequest","_initialize","additional_action_required","_performRecaptcha","human_verification_token","recaptchaSitekey","cardingProtectionElementId","cardingProtectionElement","parentNode","removeChild","load","googleRecaptchaScriptLoader","mutationObserverFactory","_memoized","recaptcha","sitekey","event$","Subject","_widgetId","size","getResponse","reset","_event$","_recaptcha","querySelector","retryWhen","delay","TIMEOUT","_watchRecaptchaChallengeWindow","iframeContainer","parentElement","visibility","attributeFilter","_scriptLoader","_loadPromise","_loadScript","callbackName","grecaptcha","createSpamProtection","MutationObserverFactory","mapFromPaymentErrorResponse","joinErrors","reduce","flatMap","values","fieldErrors","HostedFieldEventType","HostedInputEventType","_type","_containerId","_placeholder","_accessibilityLabel","_styles","_eventPoster","_eventListener","_detachmentObserver","_cardInstrument","_iframe","src","border","overflow","width","getType","attach","contentWindow","AttachRequested","accessibilityLabel","cardInstrument","fontUrls","_getFontUrls","placeholder","styles","AttachSucceeded","AttachFailed","detach","submitForm","fields","SubmitRequested","SubmitSucceeded","SubmitFailed","_isSubmitErrorEvent","validateForm","ValidateRequested","Validated","isValid","links","querySelectorAll","link","fontFamily","family","_fields","_payloadTransformer","_eventCallbacks","_paymentHumanVerificationHandler","_handleEnter","onBlur","onCardTypeChange","onFocus","onValidate","Blurred","CardTypeChanged","Focused","Entered","_cardType","cardType","BinChanged","_bin","bin","getBin","getCardType","field","_getFirstField","otherFields","without","all","otherField","submit","additionalActionData","transform","additionalAction","isVaultedInstrument","instrument","instrumentId","_store","getConfig","instrumentMeta","instruments","getInstrumentsMeta","getOrder","orderMeta","getOrderMeta","omit","paymentMethods","gatewayId","paymentMethodMeta","getPaymentMethodsMeta","authToken","getPaymentToken","vaultAccessToken","fieldOptions","_getCardInstrument","pick","createScriptLoader","getCardInstrument","MissingPaymentInstrument","OrderActionType","_orderRequestSender","_checkoutValidator","loadOrder","LoadOrderRequested","LoadOrderSucceeded","LoadOrderFailed","loadOrderPayments","LoadOrderPaymentsRequested","LoadOrderPaymentsSucceeded","LoadOrderPaymentsFailed","loadCurrentOrder","_getCurrentOrderId","SubmitOrderRequested","externalSource","getExternalSource","variantIdentificationToken","getVariantIdentificationToken","shouldExecuteSpamCheck","_mapToOrderRequestBody","customerMessage","checkoutVariant","SubmitOrderSucceeded","SubmitOrderFailed","finalizeOrder","FinalizeOrderRequested","FinalizeOrderSucceeded","FinalizeOrderFailed","gateway","PaymentActionType","_paymentRequestSender","_orderActionCreator","_paymentRequestTransformer","initializeOffsitePayment","shouldSaveInstrument","shouldSetAsDefaultInstrument","bigpay_token","InitializeOffsitePaymentRequested","InitializeOffsitePaymentSucceeded","InitializeOffsitePaymentFailed","SubmitPaymentRequested","SubmitPaymentSucceeded","SubmitPaymentFailed","_client","_transformResponse","statusText","createPaymentClient","paymentClient","subscribe","getStoreConfig","setHost","paymentSettings","bigpayBaseUrl","isBillingAddressLike","mapToInternalAddress","addressId","addressLine1","addressLine2","province","provinceCode","postCode","country","_decimalPlaces","toInteger","Math","round","pow","CheckoutButtonMethodType","couponTypes","mapToInternalCoupon","coupon","discount","displayName","discountType","couponType","mapToInternalGiftCertificate","discountedAmount","used","remainingBalance","remaining","balance","purchaseDate","mapToInternalLineItems","itemMap","idKey","amountTransformer","imageUrl","amountAfterDiscount","integerAmount","integerAmountAfterDiscount","integerUnitPrice","integerUnitPriceAfterDiscount","integerDiscount","sender","mapGiftCertificateToInternalLineItem","extendedListPrice","discountAmount","listPrice","salePrice","downloadsPageUrl","downloadPageUrl","brand","sku","categoryNames","addedByPromotion","mapToInternalLineItem","mapToInternalLineItemType","mapToInternalCart","promotions","notifications","items","sum","discountNotifications","promotion","banners","banner","placeholders","messageHtml","text","totalDiscountedAmount","certificate","appliedGiftCertificates","keyBy","amountBeforeDiscount","shippingCostBeforeDiscount","integerAmountBeforeDiscount","required","lineItem","isShippingRequired","storeCredit","taxSubtotal","taxTotal","handling","handlingCostTotal","mapToInternalCustomer","customerId","fullName","customerGroupName","customerGroup","format","RegExp","month","year","trimmedMonth","trimmedYear","toObject","card","number","maxLength","max","creditCardType","lengths","unformattedValue","unformat","gaps","gapIndex","mapToInternalOrder","payments","customerCanBeCreated","mapToInternalOrderPayment","baseAmount","orderToken","callbackUrl","socialData","mapToInternalSocialDataList","hasDigitalItems","isDownloadable","isComplete","mapToStoreCredit","orderAmount","orderAmountAsInteger","isDefaultOrderPayment","step","helpText","instructions","returnUrl","socialDataObject","socialMedia","image","shareText","sharingLink","channelName","channel","channelCode","mapToInternalShippingOption","isSelected","price","selected","transitTime","_cardExpiryFormatter","_cardNumberFormatter","checkoutState","formattedInstrument","_mapShippingAddress","getConsignments","getShippingOption","storeConfig","contextConfig","paymentMeta","internalCustomer","_transformPaymentMethod","quoteMeta","geoCountryCode","storeProfile","transformWithHostedFormData","_transformHostedInputValues","ccCvv","cardCodeVerification","ccNumber","cardNumberVerification","hostedFormNonce","cardCode","ccExpiry","cardExpiry","ccName","cardName","cardNumber","isBopisEnabled","bopis","enabled","requiredAddress","isPickup","every","selectedPickupOption","getShippingAddress","ConsignmentActionType","_consignmentRequestSender","unassignItemsByAddress","_consignmentHasAddress","existingConsignment","getConsignmentByAddress","_removeLineItems","updateConsignment","deleteConsignment","assignItemsByAddress","_createOrUpdateConsignment","_addLineItems","consignmentUpdateBody","shippingOptionId","consignmentMeta","UpdateShippingOptionRequested","UpdateShippingOptionSucceeded","UpdateShippingOptionFailed","loadShippingOptions","LoadShippingOptionsRequested","LoadShippingOptionsSucceeded","LoadShippingOptionsFailed","_getUpdateAddressRequestBody","createConsignments","CreateConsignmentsRequested","CreateConsignmentsSucceeded","CreateConsignmentsFailed","UpdateConsignmentRequested","UpdateConsignmentSucceeded","UpdateConsignmentFailed","consignmentId","DeleteConsignmentRequested","DeleteConsignmentSucceeded","DeleteConsignmentFailed","updateShippingOption","_isUpdateConsignmentRequest","customItems","itemId","_hydrateLineItems","lineItemIds","existingItem","sharedItem","DEFAULT_INCLUDES","SpamProtectionActionType","spamProtectionElementId","spamProtectionElement","googleRecaptchaSitekey","VerifyCheckoutRequested","VerifyCheckoutSucceeded","VerifyCheckoutFailed","ExecuteRequested","ExecuteSucceeded","ExecuteFailed","StoreCreditActionType","_storeCreditRequestSender","applyStoreCredit","ApplyStoreCreditRequested","removeStoreCredit","ApplyStoreCreditSucceeded","ApplyStoreCreditFailed","SubscriptionsActionType","_subscriptionsRequestSender","subscriptions","UpdateSubscriptionsRequested","UpdateSubscriptionsSucceeded","UpdateSubscriptionsFailed","isPlainObject","cloneDeep","input","cloneDeepSafe","cache","cloneResult","createPaymentIntegrationSelectors","getBillingAddressOrThrow","getLocale","getCustomerOrThrow","getCardInstrumentOrThrow","getOrderOrThrow","getPaymentTokenOrThrow","getPaymentId","getPaymentIdOrThrow","getPaymentStatus","getPaymentStatusOrThrow","getPaymentRedirectUrl","getPaymentRedirectUrlOrThrow","isPaymentDataRequired","isPaymentMethodInitialized","getShippingAddressOrThrow","getShippingAddresses","getShippingAddressesOrThrow","_storeProjectionFactory","_hostedFormFactory","_billingAddressActionCreator","_consignmentActionCreator","_paymentMethodActionCreator","_paymentActionCreator","_customerActionCreator","_cartRequestSender","_storeCreditActionCreator","_storeProjection","createHostedForm","subscriber","filters","initializeOffsitePaymentConfig","dispatch","buyNowCartRequestBody","ProjectionActionType","createDataStoreProjection","stateTransformer","projection","createDataStore","Synchronize","initial","_transformSelectors","createPaymentIntegrationService","storeProjectionFactory","checkoutActionCreator","hostedFormFactory","orderActionCreator","billingAddressActionCreator","consignmentActionCreator","paymentMethodActionCreator","paymentActionCreator","customerActionCreator","storeCreditActionCreator","spamProtection","spamProtectionRequestSender","spamProtectionActionCreator","cartRequestSender","getShippableItemsCount","guard","errorFactory","AmazonPayV2Regions","AmazonPayV2CheckoutLanguage","AmazonPayV2Placement","AmazonPayV2LedgerCurrency","AmazonPayV2PayOptions","AmazonPayV2ButtonColor","AmazonPayV2ButtonDesign","_amazonPayV2ScriptLoader","_amazonPayV2SDK","_buttonParentContainer","_createAmazonPayButtonParentContainer","_amazonPayV2Button","bindButton","buttonId","sessionId","changeAction","_getAmazonPayV2SDK","Pay","bindChangeAction","amazonCheckoutSessionId","createButton","prepareCheckout","createCheckoutSessionConfig","requestConfig","_prepareRequestConfig","_getAmazonPayV2Button","onClick","initCheckout","prepareCheckoutWithCreationRequestConfig","createCheckoutConfig","estimatedOrderAmount","productType","signout","renderAmazonPayButton","buttonColor","decoupleCheckoutInitiation","placement","parentContainerId","_getButtonParentContainer","design","C0001","amazonPayV2ButtonOptions","_getAmazonPayV2ButtonOptions","setCartRequestBody","_buyNowCartRequestBody","isPh4Enabled","features","isPh4UsOnly","publicKeyId","signedPayload","_isEnvironmentSpecific","uid","random","substr","parentContainer","Gold","checkoutLanguage","checkoutSessionMethod","extractAmazonCheckoutSessionId","ledgerCurrency","buttonBaseConfig","sandbox","PayOnly","PayAndShip","shopPath","buttonOptions","tmpConfig","createCheckoutSession","_getOrThrow","region","amazonPayV2Region","amazon","createAmazonPayV2PaymentProcessor","_braintreeScriptLoader","_dataCollectors","_clientToken","getPaypal","_paypal","loadPaypal","_paypalCheckout","getVenmoCheckout","_venmoCheckout","loadVenmoCheckout","venmoCheckout","venmoCheckoutConfig","allowDesktop","paymentMethodUsage","venmoCheckoutCallback","braintreeVenmoCheckout","isBrowserSupported","get3DS","_3ds","load3DS","version","getVisaCheckout","_visaCheckout","loadVisaCheckout","getGooglePaymentComponent","_googlePay","loadGooglePayment","createHostedFields","loadHostedFields","_teardown","mod","threeDSecure","visaCheckout","venmo","googlePayment","hostedFields","_braintreeSDKCreator","createInitOptions","settings","locale","collectShipping","paymentRequest","String","handleSuccess","billing","braintreeVisaCheckout","tokenize","tokenizedPayload","_toVisaCheckoutAddress","_postForm","userData","cardInformation","userEmail","card_information","_getCardInformation","_getAddress","streetAddress","extendedAddress","lastTwo","createBraintreeVisaCheckoutPaymentProcessor","braintreeSDKCreator","V","JPMC","CallbackTriggerType","TotalPriceStatusType","CallbackIntentsType","ButtonType","ButtonColor","BillingAddressFormat","getFirstAndLastName","nameParts","_googlePayScriptLoader","_googlePayInitializer","_isBuyNowFlow","googlePayClientOptions","_methodId","_configureWallet","buttonType","Short","Default","_googlePayClient","updatePaymentDataRequest","paymentDataRequest","existingPaymentDataRequest","_getPaymentDataRequest","_paymentDataRequest","merchantInfo","transactionInfo","shippingAddressParameters","displayWallet","loadPaymentData","parseResponse","_updateBillingAddress","_mapGooglePayAddressToShippingAddress","updateBuyNowFlowFlag","isBuyNowFlow","_getMethodId","_getCheckout","hasShippingAddress","googlePay","_getGooglePayClient","isReadyToPay","allowedPaymentMethods","parameters","allowedAuthMethods","allowedCardNetworks","apiVersion","apiVersionMinor","lastFour","google","environment","api","PaymentsClient","_mapGooglePayAddressToBillingAddress","customerEmail","paymentMethodData","companyName","address3","postPaymentData","buyNowCartId","tokenFormat","remoteBillingAddress","googlePayAddressMapped","createGooglePayPaymentProcessor","initializer","_getGooglePayPaymentDataRequest","totalPrice","gatewayMerchantId","merchantName","authJwt","billingAddressRequired","billingAddressParameters","Full","phoneNumberRequired","tokenizationSpecification","totalPriceStatus","FINAL","emailRequired","shippingAddressRequired","baseRequest","_getGooglePaymentDataRequest","supportedCards","paymentGatewaySpecification","_getPaymentGatewaySpecification","cardPaymentMethod","_getCardPaymentMethod","googleBraintreePaymentInstance","_googlePaymentInstance","_createGooglePayPayload","tokenizationData","androidPayCards","binData","platformToken","googlePayBraintreePaymentDataRequest","googleMerchantName","googleMerchantId","cardRequirements","billingAddressFormat","_mapGooglePayBraintreeDataRequestToGooglePayDataRequestV2","createPaymentDataRequest","googlePayBraintreeDataRequestV1","paymentMethodTokenizationParameters","_publishableKey","_testMode","_errorMessage","checkoutcomkey","_mapGooglePayCheckoutcomDataRequestToGooglePayDataRequestV2","err","signature","protocolVersion","signedMessage","_convertToken","finalToken","cardNetwork","cardDetails","token_format","_requestCheckoutcomTokenize","token_data","checkoutcomToken","checkoutcomKey","Authorization","last4","stripeVersion","stripePublishableKey","stripeConnectedAccount","useMasterpassSrc","language","sourceUrl","masterpass","getStripeClient","stripeAccount","stripeClient","bcStripeClient","stripe","betas","getElements","stripeElements","bcStripeElements","fetchUpdates","update","elements","Stripe","initializeBilling","methodName","initializeShipping","initializePayment","loadSettings","generateToken","trackAuthorizationEvent","forgetCheckout","RemoteCheckoutActionType","_remoteCheckoutRequestSender","InitializeRemoteBillingRequested","InitializeRemoteBillingSucceeded","InitializeRemoteBillingFailed","InitializeRemoteShippingRequested","InitializeRemoteShippingSucceeded","InitializeRemoteShippingFailed","InitializeRemotePaymentRequested","InitializeRemotePaymentSucceeded","InitializeRemotePaymentFailed","LoadRemoteSettingsRequested","LoadRemoteSettingsSucceeded","LoadRemoteSettingsFailed","SignOutRemoteCustomerRequested","SignOutRemoteCustomerSucceeded","SignOutRemoteCustomerFailed","ForgetCheckoutRemoteCustomerRequested","ForgetCheckoutRemoteCustomerSucceeded","ForgetCheckoutRemoteCustomerFailed","UpdateRemoteCheckout","_remoteCheckoutActionCreator","_amazonPayV2PaymentProcessor","amazonpay","Checkout","_customerStrategyActionCreator","_braintreeVisaCheckoutPaymentProcessor","_visaCheckoutScriptLoader","_formPoster","_buttonClassName","visaCheckoutOptions","initOptions","storeLanguage","signInButton","_createSignInButton","init","paymentSuccessPayload","_paymentInstrumentSelected","_onPaymentSelectComplete","queueId","buttonClass","_insertVisaCheckoutButton","visaCheckoutButton","display","flexDirection","className","innerHTML","braintreepaypalcredit","_renderPayPalButton","_handleError","buttonStyle","_setupPayment","_tokenizePayment","_removeElement","_chasePayScriptLoader","chasePayOptions","digitalSessionId","ChasePay","configure","isChasePayUp","insertButtons","containers","EventType","START_CHECKOUT","startCheckout","COMPLETE_CHECKOUT","requestId","merchantRequestId","_setExternalCheckoutData","_reloadPage","sessionToken","sendRequest","fromChasePay","GooglePayCustomerMethodType","_googlePayPaymentProcessor","googlePayOptions","_getGooglePayOptions","_walletButton","googlepayadyenv2","googlepayadyenv3","googlepayauthorizenet","googlepaybnz","googlepaybraintree","googlepaycheckoutcom","googlepaycybersourcev2","googlepayorbital","googlepaystripe","googlepaystripeupe","googlepayworldpayaccess","hasPhysicalItems","payloadToUpdate","checkoutUrl","siteLink","getCallbackUrl","supportedLocales","es","en","pt","zu","ar","zh","ms","uk","sv","hr","pl","nl","it","de","fr","formatLocale","localeLanguage","toLowerCase","formattedLocale","countryLocales","_masterpassScriptLoader","_locale","masterpassOptions","allowedCardTypes","suppressShippingAddress","masterpassScriptLoaderParams","isMasterpassSrcEnabled","Masterpass","_signInButton","subdomain","StripeFormMode","DisplayName","StripePaymentMethodType","StripeStringConstants","StripeElementType","_stripeUPEScriptLoader","stripeupe","onEmailChange","getStyles","isLoading","isStripeLinkAuthenticated","appearance","variables","colorPrimary","fieldInnerShadow","colorBackground","fieldBackground","colorText","labelText","colorDanger","fieldErrorText","colorTextSecondary","colorTextPlaceholder","fieldPlaceholderText","rules","borderColor","fieldBorder","fieldText","boxShadow","stripeUPEClient","_stripeElements","clientSecret","billingEmail","defaultValues","mode","SHIPPING","linkAuthenticationElement","getElement","AUTHENTICATION","StripeLinkAuthenticated","authenticated","mount","unmount","ExtensionActionType","_extension","_cartId","URL","searchParams","InvalidExtensionConfigError","loadExtensions","LoadExtensionsRequested","extensions","LoadExtensionsSucceeded","LoadExtensionsFailed","renderExtension","extension","getExtensionByRegion","ExtensionNotFoundError","RenderExtensionRequested","ExtensionIframe","RenderExtensionSucceeded","RenderExtensionFailed","invalidFields","getBrowserInfo","navigator","userLanguage","color_depth","screen","colorDepth","java_enabled","javaEnabled","screen_height","screen_width","time_zone_offset","Date","getTimezoneOffset","AdyenActionType","AdyenComponentType","AdyenPaymentMethodType","HTTPMethod","ResultCode","AdyenV2CardFields","isCardState","encryptedSecurityCode","encryptedExpiryMonth","adyenv2","_paymentInitializeOptions","originKey","clientKey","paymentMethodsResponse","clientSideAuthentication","translations","_adyenClient","_mountPaymentComponent","_paymentComponent","CreditCard","Bancontact","_mountCardVerificationComponent","_cardVerificationComponent","_validateCardData","componentState","_componentState","bigpayToken","encryptedCardNumber","encryptedExpiryYear","credit_card_number_confirmation","expiry_month","expiry_year","verification_value","browser_info","_processAdditionalAction","credit_card_token","finalize","_getAdyenClient","_getPaymentInitializeOptions","_getThreeDS2ChallengeWidgetSize","additionalActionOptions","threeDS2Options","widgetSize","_handleAction","threeDS2ContainerId","onBeforeLoad","onLoad","adyenAction","additionalActionComponent","createFromAction","onAdditionalDetails","additionalActionState","paymentPayload","paymentMethodType","ThreeDS2Challenge","QRCode","_mapAdyenPlaceholderData","prefillCardHolderName","holderName","street","houseNumberOrName","cardVerificationComponent","adyenClient","cardVerificationContainerId","SecuredFields","caretColor","onChange","_updateComponentState","validateState","validateCardFields","onFieldValid","paymentComponent","ACH","IDEAL","SEPA","hasVaultedInstruments","AliPay","GiroPay","Sofort","Klarna","KlarnaPayNow","KlarnaAccount","Vipps","WeChatPayQR","provider_data","cardComponent","componentRef","showValidation","issuer","_mapCardErrors","cardStateErrors","_stylesheetLoader","configuration","loadStylesheet","AdyenCheckout","getStylesheetLoader","isHostedInstrumentLike","AdyenV3CardFields","adyenv3","paymentMethodsConfiguration","klarna","useKlarnaWidget","klarna_account","klarna_paynow","showPayButton","challengeWindowSize","showBrandsUnderCardNumber","onSubmit","HostedFieldType","isHostedCardFieldOptionsMap","isHostedStoredCardFieldOptionsMap","_blueSnapDirectHostedForm","creditCard","is3dsEnabled","_paymentFieldsToken","_shouldUseHostedFields","form","_getPaymentFieldsToken","pfToken","_getBlueSnapDirectThreeDSecureData","bluesnapSubmitedForm","cardHolderName","billingFirstName","billingLastName","billingCountry","billingState","billingCity","trim","billingZip","shippingFirstName","shippingLastName","shippingCountry","shippingState","shippingCity","shippingZip","BlueSnapDirectCardType","BlueSnapDirectEventOrigin","BlueSnapDirectErrorDescription","BlueSnapDirectErrorCode","BlueSnapDirectHostedFieldTagId","BlueSnapHostedFieldType","CREDIT_CARD_ERRORS","fieldType","invalid","_nameOnCardInput","_hostedInputValidator","_blueSnapSdk","initializeValidationFields","initializeValidationCVVFields","paymentFieldsToken","enable3DS","callbacksAndStyles","blueSnapSdk","_getBlueSnapSdk","_onValidate","_setCustomBlueSnapAttributes","_setCustomStoredCardsBlueSnapAttributes","_getHostedPaymentFieldsOptions","hostedPaymentFieldsCreate","threeDSecureData","shouldSendName","hostedPaymentFieldsSubmitData","_isBlueSnapDirectCallbackError","statusCode","errorDescription","cardData","getValue","onEnter","onFieldEventHandler","setupComplete","_usetUiEventCallback","onType","_tagId","onValid","tagId","ccnPlaceHolder","cvvPlaceHolder","expPlaceHolder","_mapStyles","focus","selector","declaration","declarationBlock","property","kebabCase","errorCode","eventOrigin","EMPTY","INVALID","cardNumberContainer","cardExpiryContainer","cardCodeContainer","cardNameContainer","dataset","bluesnap","_errors","_updateErrors","errorData","_style","_create","_getInput","_handleFocus","_handleBlur","_input","_applyStyles","HTMLInputElement","allowedStyle","fontSize","fontWeight","styleKeys","_configureInput","autocomplete","inputMode","backgroundColor","margin","outline","padding","BlueSnapDirectSdkEnv","SANDBOX","PRODUCTION","isBlueSnapDirectEcpInstrument","assertBlueSnapDirectEcpInstrument","ecp","account_number","accountNumber","account_type","accountType","shopper_permission","shopperPermission","routing_number","routingNumber","bluesnapdirect","_initializeOptions","_isBlueSnapDirectRedirectResponse","partialValue","merchantid","isBlueSnapDirectRedirectResponseProviderData","providerData","providerDataQuery","URLSearchParams","_mountAPMFrame","redirect_url","frame","iframe","createIframe","partialResponse","partialBody","storage","saveExtraItemsData","category","setItem","getStorageKey","readExtraItemsData","getItem","itemsData","isObject","hasNotExtraItems","isExtraItemsData","clearExtraItemData","removeItem","ORDER_ITEMS_STORAGE_KEY","isAnalyticsTrackerWindow","isWithAccountCreation","BoltError","getError","analyticsExtraItemsManager","useBoltClient","useBoltEmbedded","onPaymentSelect","useBigCommerceCheckout","boltEmbedded","mountBoltEmbeddedField","embeddedField","setExtraItemsForAnalytics","isBoltPaymentData","getBoltClientPaymentPayload","getBoltEmbeddedPaymentPayload","getBoltFullCheckoutPaymentPayload","isStoreCreditApplied","success","transaction","reference","open","boltTransaction","validateTokenizeResultOrThrow","tokenizeResult","last_four_digits","iin","expiration_month","expiration","expiration_year","create_account","shouldCreateAccount","embedded_checkout","setBoltOrderId","getTransactionReference","transactionReference","getBoltEmbeddedOrThrow","setOrderId","renderSeparateFields","lastFourDigits","expirationMonth","expirationYear","Number","isNaN","isAnalyticsEnabled","isUsBankAccountInstrumentLike","getMandateText","braintreeach","orderRequest","isSubmittingWithVaultingInstrument","tokenizePaymentForVaultedInstrument","preparePaymentDataForVaultedInstrument","preparePaymentData","submitPaymentPayload","tokenized_bank_account","masked_account_number","getUsBankAccountOrThrow","mandateText","bankDetails","getBankDetails","isVaultingEnabled","ownershipType","businessName","loadingIndicator","braintreelocalmethods","loadingIndicatorContainer","toggleLoadingIndicator","startPayment","paymentType","fallback","buttonText","onPaymentStart","start","paymentId","startPaymentError","payloadData","show","hide","DEFAULT_STYLES","ROTATION_ANIMATION","defineAnimation","buildContainer","indicator","buildIndicator","parentId","opacity","handleTransitionEnd","bottom","left","position","right","top","transition","borderRadius","transformStyle","animation","head","sheet","CSSStyleSheet","insertRule","_isHostedPaymentFormEnabled","_shouldRenderHostedForm","_executeWithHostedForm","_executeWithoutHostedForm","_isHostedFieldAvailable","formOptions","_hostedForm","isHostedFormEnabled","_isAdditionalActionRequired","redirectUrl","PaymentStatusTypes","orderPayload","_shouldSubmitFullPayload","onRenderButton","handleClick","handleApprove","onCancel","paypalOptions","pollingInterval","maxPollingTime","pollingTimer","stopPolling","paypalcommercealternativemethods","shouldRenderFields","renderFields","isNonInstantPaymentMethod","deinitializePollingMechanism","reinitializeStrategy","resetPollingMechanism","initializePollingMechanism","apmFieldsContainer","apmFieldsStyles","fieldContainerElement","fieldsOptions","PaymentFields","setTimeout","clearTimeout","orderStatus","isOrderApproved","Approved","isOrderPending","Created","PayerActionRequired","toUpperCase","isCreditCardFormFields","paypalcommercecreditcards","hostedFormOptions","isCreditCardForm","executionPaymentData","validateHostedFormOrThrow","submitHostedForm","hostedFieldsOptions","mapFieldOptions","mapStyleOptions","paymentsSDK","getInstrumentParams","HostedFields","setFormFieldEvents","renderCardNameField","cardNameFiledStylesPreset","defaultCardNameFiledStyles","focusCardNameFiledStyles","defaultStyleProperties","getValidStyleString","focusStyleProperties","cardNameField","setFieldStyleAttribute","eventsData","eventName","formCallback","eventHandler","getFieldTypeByEmittedField","getCardTypeByEvent","getValidityData","emittedBy","mapFieldType","cards","getHostedFieldsOrThrow","cardholderName","contingencies","liabilityShift","hostedFieldState","validationData","mapValidationErrors","fieldsKeys","fieldsErrors","getInvalidErrorByFieldType","validationErrors","expirationDate","cvv","mapStyles","newObject","applicationId","locationId","square","_payments","_formValidationSubscription","unsubscribe","_card","destroy","initializeCard","onValidationChange","_getPayments","_subscribeToFormValidation","_getCard","errorMessage","verifyBuyer","_mapToSquareBillingContact","blacklist","Set","eventObservables","eventType","isCompletelyValid","distinctUntilChanged","_squareV2PaymentProcessor","squarev2","_shouldVerify","SquareV2WebPaymentsSdkEnv","LIVE","isSquareV2Window","assertSquareV2Window","Square","CountryActionType","_countryRequestSender","loadCountries","LoadCountriesRequested","LoadCountriesSucceeded","LoadCountriesFailed","_config","createPaymentStrategyRegistry","paymentStrategyFactories","createPaymentStrategy","PaymentStrategyActionType","PaymentStrategyType","FinalizeRequested","_loadOrderPaymentsIfNeeded","FinalizeSucceeded","FinalizeFailed","paymentStrategies","getByMethod","_namespace","rawValue","withNamespace","getItemOnce","isPPSDKPaymentMethod","initializationStrategy","checkoutcomStrategies","credit_card","sepa","ideal","fawry","_getToken","_hasFactoryForMethod","saveExternalId","externalId","_affirmScriptLoader","publicKey","affirm","_affirm","_getCheckoutInformation","onFail","failObject","reason","successObject","ui","checkout_token","_getBillingAddress","merchant","user_confirmation_url","checkoutLink","user_cancel_url","user_confirmation_url_action","_getShippingAddress","_getItems","metadata","shipping_type","_getShippingType","platform_type","platform_version","platform_affirm","discounts","_getDiscounts","shipping_amount","tax_amount","first","last","full","zipcode","display_name","unit_price","qty","item_image_url","item_url","categories","_getCategories","line","discount_amount","discount_display_name","DISCOUNTED_AMOUNT","categoryTree","apikey","scriptURI","_getScriptURI","m","g","h","c","k","p","getElementsByTagName","l","arguments","f","a1","c1","a2","c2","insertBefore","public_api_key","script","_afterpayScriptLoader","_mapCurrencyToISO2","_afterpaySdk","_loadPaymentMethod","_redirectToAfterpay","redirect","AUD","NZD","CAD","USD","AfterPay","_paymentStrategyActionCreator","paymentToken","_isReadyToPay","editButtonId","_bindEditButton","_isModalFlow","_createContainer","_amazonPayButton","_isOneTimeTransaction","_getAmazonPayButton","click","isModalFlow","clone","cloneNode","replaceChild","_showLoadingSpinner","_options","_threeDSecureFlow","prepare","ACKNOWLEDGE","FINALIZE","_createIframe","bluesnapv2","_createElements","closeElement","mainElement","_element","_closeElement","_mainElement","_registerClick","_unregisterClick","_removeAfterTransition","classLayout","classClose","classOverlayText","background","transitionDuration","hasCloseButton","innerHtml","overlayText","addClassLayout","innerText","getOverlayStyle","_addEventListener","_removeEventListener","handleTransition","propertyName","BraintreeFormFieldType","off","isBraintreeFormFieldsMap","BraintreeHostedFormType","_isInitializedHostedForm","_formOptions","_mapFieldType","_mapErrors","_handleNameBlur","CardName","_handleNameFocus","_handleCardTypeChange","_handleInputSubmitRequest","_handleValidityChange","_mapValidationErrors","StoredCardVerification","_mapFieldOptions","isEmpty","_mapStyleOptions","_cardFields","_cardNameField","_mapBillingAddress","_mapTokenizeError","tokenizeForStoredCardVerification","countryName","internalLabel","CardNumberVerification","CardNumber","CardExpiry","CardCodeVerification","CardCode","_isValidParam","isPotentiallyValid","fieldKey","_createInvalidError","isStoredCard","cvvValidation","_createRequiredError","expirationDateValidation","cardNumberValidation","invalidFieldKeys","formErrorDataKey","_braintreeHostedForm","_overlay","_threeDSecureOptions","preloadPaypal","tokenizeCard","_getErrorsRequiredFields","requestData","_mapToCreditCard","verifyCard","challenge3DSVerification","newWindowFlow","supportsPopups","focusWindow","useraction","appendSessionId","processedPayment","initializeHostedForm","isInitializedHostedForm","deinitializeHostedForm","tokenizeHostedForm","tokenizeHostedFormForStoredCardVerification","verifyCardWithHostedForm","_present3DSChallenge","addFrame","removeFrame","cancelVerifyCard","verification","roundedAmount","challengeRequested","onLookupComplete","_data","countryCodeAlpha2","endpoint","_braintreePaymentProcessor","_isHostedFormInitialized","_is3dsEnabled","_deviceSessionId","_prepareHostedPaymentData","_preparePaymentData","commonPaymentData","_isSubmittingWithStoredCard","_isStoringNewCard","_shouldPerform3DSVerification","storedCreditCardNonce","three_ds_result","_credit","braintreeOptions","_loadPaypal","getOutstandingBalance","_formattedPayload","vaultPaymentInstrument","_initializeBraintreeVenmo","_braintreeVenmoCheckout","_braintreeVenmoTokenize","visaInitOptions","_cardinalClient","hostedForm","xid","payer_auth_request","_getBin","runBinProcess","_submitPayment","threeDsResult","getThreeDSecureData","_getOrderData","isCreditCardLike","CardinalInitializationType","CardinalEventType","CardinalValidatedAction","CardinalPaymentType","CardinalTriggerEvents","CardinalPaymentBrand","CardinalSignatureVerification","CardinalSignatureValidationErrors","_provider","_configurationToken","_sdk","now","_getClientSDK","SetupCompleted","ActionCode","ErrorNumber","ErrorDescription","setup","Init","jwt","binNumber","BinProcess","Status","orderData","Success","NoAction","Payment","ExtendedData","SignatureVerification","Yes","Failure","continueObject","AcsUrl","acs_url","Payload","merchant_data","partialOrder","_mapToPartialOrder","continue","CCA","transactionId","consumer","BillingAddress","_mapToCardinalAddress","Account","_mapToCardinalAccount","Email1","ShippingAddress","Consumer","OrderDetails","OrderNumber","Amount","CurrencyCode","OrderChannel","TransactionId","AccountNumber","ExpirationMonth","ExpirationYear","NameOnAccount","cardinalAddress","FirstName","LastName","Address1","City","State","PostalCode","CountryCode","Address2","Phone1","Cardinal","_getClientToken","_CBAMGPSScriptLoader","_sessionId","isTestModeFlagEnabled","_threeDSjs","isConfigured","wsVersion","newPaymentData","storeId","_initiateAuthentication","initiateAuthentication","msg","gatewayRecommendation","restApiResponse","authenticationStatus","_authenticatePayer","attempt","_resolve","authenticatePayer","cause","fullScreenRedirect","ThreeDS","ChasePayEventType","_wepayRiskClient","_walletEvent$","chasepay","walletButton","_chasePayClient","_getPayment","_displayWallet","_createOrder","logoContainer","insertBrandings","CancelCheckout","CompleteCheckout","_setSessionToken","showLoadingAnimation","getRiskToken","riskToken","paymentCryptogram","cryptogramId","eci","reqTokenId","expDate","accountNum","accountMask","extraData","AdditionalActionType","_processResponse","additionalActionRequired","OffsiteRedirect","_performRedirect","DOCUMENT_SUPPORTED_APMS","_createFormattedPayload","ccDocument","customerMobile","bic","iban","_clearpayScriptLoader","_clearpaySdk","_isCountrySupported","_redirectToClearpay","_getScriptUrl","PaReq","TermUrl","callback_url","MD","AuthenticationSourceStatus","_digitalRiverScriptLoader","_digitalRiverInitializeOptions","digitalriver","_getDigitalRiverInitializeOptions","_digitalRiverJS","_loadWidget","_unsubscribe","_digitalRiverCheckoutData","_submitVaultedInstrument","checkoutData","_isAuthenticateSourceAction","_authenticateSource","_loadSuccessResponse","readyForStorage","_getDigitalRiverJs","_getErrorMessage","_onSuccessResponse","_submitFormEvent","browserInfo","owner","reusable","billingAddressPayPal","_onReadyResponse","paymentMethodConfiguration","_mountComplianceSection","sellingEntity","onSubmitForm","disabledPaymentMethods","digitalRiverConfiguration","showSavePaymentAgreement","onReady","descriptiveError","createDropin","_digitalRiverDropComponent","authenticateSource","sourceId","source_id","sourceClientSecret","source_client_secret","authenticateSourceResponse","failed","authentication_not_required","confirm","complianceDiv","complianceOptions","classes","base","compliance","entity","drfooter","cssText","classList","add","DigitalRiver","_googlePayProviderProcessor","isThreeDSecureEnabled","_googlePayOptions","_buttonClickEventHandler","_handleButtonClickedEvent","_verifyCard","newPayment","processAdditionalAction","_braintreePresent3DSChallenge","requireRenewNonce","_encodeNonce","googlePayToken","processable","_isOffsiteRedirectResponse","_handleOffsiteRedirectResponse","supportedCountries","supportedCountriesRequiringStates","_klarnaScriptLoader","klarnaCredit","_klarnaCredit","_authorize","authorizationToken","client_token","_getUpdateSessionData","_mapToKlarnaAddress","_needsStateCode","klarnaAddress","street_address","family_name","street_address2","updateSessionData","authorize","res","approved","show_form","Credit","_klarnav2ScriptLoader","_klarnav2TokenUpdater","klarnaPayments","_klarnaPayments","_loadPaymentsWidget","klarnav2","updateClientToken","payment_method_category","Payments","_masterpassClient","_createMasterpassPayload","MolliePaymentMethodType","methodsNotAllowedWhenDigitalOrder","_mollieScriptLoader","mollie","controllers","each","controller","isCreditCard","shouldShowTSVHostedForm","_mountCardVerificationfields","_loadMollieJs","_mollieClient","_mountElements","disableButton","_loadPaymentMethodsAllowed","executeWithVaulted","executeWithCC","executeWithAPM","_cardHolderElement","_cardNumberElement","_verificationCodeElement","_expiryDateElement","_getMollieClient","createToken","shopper_locale","_getShopperLocale","creditcard","_getInitializeOptions","testmode","cardNumberId","cardCvcId","cardExpiryId","cardHolderId","mollieClient","createComponent","cartDigitalItems","paragraph","unsupportedMethodMessage","_isMollieWindow","Mollie","monerisOptions","profileId","_shouldShowTSVHostedForm","_executeWithVaulted","_executeWithCC","_windowEventListener","instrumentSettings","frameref","_monerisURL","_handleMonerisResponse","definedFields","monerisQueryParams","pmmsg","display_labels","enable_exp","enable_cvd","css_body","cssBody","css_textbox","cssTextbox","css_textbox_pan","cssTextboxCardNumber","css_textbox_exp","cssTextboxExpiryDate","css_textbox_cvd","cssTextboxCVV","css_input_label","cssInputLabel","pan_label","creditCardLabel","exp_label","expiryDateLabel","cvd_label","cvdLabel","queryString","monerisResponse","responseCode","dataKey","ActionTypes","OpyErrorType","isOpyPaymentMethod","widgetConfig","InvalidCart","_storefrontPaymentRequestSender","opy","_installWidget","nextAction","FORM_POST","formPost","formPostUrl","formFields","fieldName","fieldValue","append","decodeURI","widgetContainer","loadOpyWidget","Config","OpyRegion","AU_REGION_URL","SOURCES","AU","UK","US","OpenpayWidgets","_useRedirectFlow","paypalexpress","useRedirectFlow","_isInContextEnabled","_paypalSdk","closeFlow","_isAcknowledgedOrFinalized","initXO","startFlow","scriptSrc","SubStrategyType","PENDING_REDIRECT_PARAM","_isRedirecting","currentUrlHasRedirectingParam","isRedirecting","setRedirecting","setRedirectingParamOnUrl","removeRedirectingParamFromUrl","getCurrentUrl","replaceCurrentUrl","history","replaceState","currentUrl","updatedUrl","stringifyUrl","exclude","isAnyContinue","overSome","x","isString","isUndefined","availableMethods","_humanVerificationHandler","form_fields","redirectionState","RedirectionState","handleRedirect","humanVerificationHandler","available_methods","handleHumanVerification","humanVerification","_continueHandler","isSuccess","isContinue","isFailure","failureResponse","handleFailure","isError","createStepHandler","StepHandler","ContinueHandler","COMPLETED_PAYMENTS_KEY","_browserStorage","isCompleted","getCompletedPayments","setCompleted","completedPayments","setCompletedPayments","_subStrategyRegistry","_paymentResumer","browserStorage","_completedPayments","PPSDKCompletedPayments","subStrategy","resume","getPPSDKMethod","_subStrategy","getToken","cond","constant","CARD","NONE","stubTrue","UNSUPPORTED","_ppsdkStepHandler","humanVerificationCallback","_stepHandler","payment_method_id","createSubStrategyRegistry","stepHandler","SubStrategyRegistry","CardSubStrategy","NoneSubStrategy","auth_token","_prepareForReferredRegistration","_isThreeDSTwoExperimentOn","creq","SquareIntent","CardBrand","DigitalWalletType","squareOptions","_squareOptions","_syncPaymentMethod","createSquareForm","_paymentForm","_getFormOptions","_getPaymentForm","build","_getNonceInstrument","_getCountryCode","_deferredRequestNonce","requestCardNonce","deferred","cardNonceResponseReceived","deferredRequest","_getDeferredRequestNonce","digital_wallet_type","none","_handleWalletNonceResponse","_is3DSExperimentOn","_getVerificationDetails","verificationResults","createPaymentRequest","_paymentRequestPayload","paymentFormLoaded","_setPostalCode","unsupportedBrowserDetected","requestShippingAddress","requestBillingInfo","storeCountry","pending","setPostalCode","_getBillingContact","_getAmountAndCurrencyCode","CHARGE","_isSquareWindow","SqPaymentForm","bg","cs","da","el","et","fi","fil","he","hu","ja","ko","lt","lv","mt","nb","ro","ru","sk","sl","th","tr","vi","APM_REDIRECT","SOFORT","EPS","GRABPAY","BANCONTACT","GIROPAY","ALIPAY","KLARNA","_stripeScriptLoader","_isMounted","_isDeinitialize","_loadStripeElement","_state","PAYMENT","_stripeUPEClient","_executeWithAPM","_executeWithoutRedirect","_isCancellationError","stripeError","payment_intent","last_payment_error","_throwDisplayableStripeError","_processVaultedAdditionalAction","shopperLanguage","_loadStripeJs","colorIcon","stripeElement","billingDetails","NEVER","AUTO","wallets","applePay","confirmPayment","_mapStripePaymentData","paymentIntent","catchedConfirmError","stripePaymentData","retrievePaymentIntent","confirmCardPayment","_mapStripeAddress","IF_REQUIRED","confirmParams","payment_method_data","billing_details","return_url","IconStyle","StripeV3ErrorType","isIndividualCardElementOptions","individualCardElementOptions","cardNumberElementOptions","cardCvcElementOptions","cardExpiryElementOptions","AuthFailure","stripev3","useIndividualCardFields","_useIndividualCardFields","_stripeV3Client","_isCreditCard","_mountCardVerificationFields","_mountCardFields","_stripeElement","shouldSubmitOrderBeforeLoadingAPM","_confirmStripePayment","_buildPaymentPayload","_handleEmptyPaymentIntentError","_unmountElement","_isAuthError","_getStripeJs","confirmAlipayPayment","handleActions","confirmIdealPayment","confirmSepaDebitPayment","_getStripeCardElements","_getStripeElement","_mapStripeBillingDetails","createPaymentMethod","_stripeCardElements","zipCodeElementOptions","stripePaymentMethodType","cardNumberElement","cardExpiryElement","cardCvcElement","isAdditionalActionError","isThreeDSecureRequiredError","needsConfirm","_getPaymentToken","_riskClient","WePay","risk","generate_risk_token","get_risk_token","payloadWithToken","PAYMENT_CANNOT_CONTINUE","worldpay","_submitAdditionalAction","iframeHidden","messageEvent","_isValidJsonWithSessionId","removeEvent","SessionId","_createHiddenIframe","formId","inputBin","inputJWT","userAgent","match","srcdoc","outerHTML","str","InstrumentActionType","_instrumentRequestSender","loadInstruments","LoadInstrumentsRequested","session","_getSessionContext","_getCurrentAccessToken","_getValidAccessToken","currentToken","LoadInstrumentsSucceeded","LoadInstrumentsFailed","deleteInstrument","DeleteInstrumentRequested","DeleteInstrumentSucceeded","DeleteInstrumentFailed","_isValidVaultAccessToken","date","valueOf","isFuture","vaultAccessExpiry","newDate","getTime","setMinutes","getMinutes","getVaultAccessToken","shopperCurrency","isTransactional","transformResponse","vaultedInstruments","_transformVaultedInstruments","vaulted_instruments","transformErrorResponse","transformVaultAccessResponse","expires_at","_isPayPalInstrument","defaultInstrument","default_instrument","external_id","trustedShippingAddress","trusted_shipping_address","mapToPayPalInstrument","_isBankInstrument","mapToBankInstrument","last_4","expiryMonth","expiryYear","untrustedShippingCardVerificationMode","untrusted_shipping_address_card_verification_mode","mapToCardInstrument","method_type","_transformer","requestContext","_loadInstrumentsWithAddress","_loadInstruments","deleteShopperInstrument","errorResponse","loadInstrumentsWithAddress","PickupOptionActionType","_pickupOptionRequestSender","loadPickupOptions","apiQuery","_hydrateApiQuery","LoadPickupOptionsRequested","fetchPickupOptions","LoadPickupOptionsSucceeded","LoadPickupOptionsFailed","getConsignmentById","consignmentLineItems","cartItems","searchArea","ShippingCountryActionType","_shippingCountryRequestSender","LoadShippingCountriesRequested","LoadShippingCountriesSucceeded","LoadShippingCountriesFailed","ShippingStrategyActionType","UpdateAddressRequested","UpdateAddressSucceeded","UpdateAddressFailed","selectOption","SelectOptionRequested","SelectOptionSucceeded","SelectOptionFailed","mergedOptions","shippingStrategies","_shippingStrategyActionCreator","updateAddressRequestBody","editAddressButtonId","shouldShowLoadingSpinner","_shouldShowLoadingSpinner","onChangeShipping","availableCountries","getStripeState","getShippingAddressFields","shippingFields","spacingUnit","shippingPhoneField","allowedCountries","validation","SPLIT","stripeState","shippingAddressElement","isNewAddress","sendData","phoneFieldRequired","SignInEmailActionType","sendSignInEmail","emailRequest","SendSignInEmailRequested","SendSignInEmailSucceeded","SendSignInEmailFailed","withMemoizedCombiner","creator","combiner","pop","combinerArgs","createSelectorCreator","defaultMemoize","_messageCustomizer","_countryActionCreator","_couponActionCreator","_errorActionCreator","_giftCertificateActionCreator","_instrumentActionCreator","_pickupOptionActionCreator","_shippingCountryActionCreator","_signInEmailActionCreator","_subscriptionsActionCreator","_extensionActionCreator","isDevelopment","getShippingOptions","getSelectedShippingOption","getShippingCountries","getBillingCountries","getPaymentMethods","getSelectedPaymentMethod","getCoupons","getGiftCertificates","getSignInEmail","isPaymentDataSubmitted","getInstruments","getCustomerAccountFields","getBillingAddressFields","getFlashMessages","getPickupOptions","getUserExperienceSettings","getExtensions","getSelectShippingOptionError","isPending","isSelectingShippingOption","isCustomerStepPending","isShippingStepPending","isPaymentStepPending","isSubmittingOrder","createCheckoutStoreSelector","createCheckoutStoreErrorSelector","createCheckoutStoreStatusSelector","_errorTransformer","isCheckoutServiceError","_selectorsFactory","shippingConsignment","val","getCountries","getEmail","getInstrumentsByPaymentMethod","checkoutUserExperienceSettings","memoizeOne","getSelectOptionError","getUpdateShippingOptionError","getLoadCheckoutError","getLoadError","getUpdateCheckoutError","getUpdateError","getSubmitOrderError","getExecuteError","getFinalizeOrderError","getFinalizeError","getLoadOrderError","getLoadCartError","getLoadBillingCountriesError","countries","getLoadShippingCountriesError","shippingCountries","getLoadPaymentMethodsError","getLoadPaymentMethodError","getLoadMethodError","getInitializePaymentError","getInitializeError","getSignInError","getSignOutError","getInitializeCustomerError","getLoadShippingOptionsError","getContinueAsGuestError","getUpdateBillingAddressError","getUpdateSubscriptionsError","getUpdateShippingAddressError","getUpdateAddressError","getDeleteConsignmentError","getDeleteError","getUpdateConsignmentError","getCreateConsignmentsError","getCreateError","getInitializeShippingError","getApplyStoreCreditError","getApplyError","getApplyCouponError","getRemoveCouponError","getRemoveError","getApplyGiftCertificateError","getRemoveGiftCertificateError","getLoadInstrumentsError","getDeleteInstrumentError","getLoadConfigError","getSignInEmailError","signInEmail","getSendError","getCreateCustomerAccountError","getCreateAccountError","getCreateCustomerAddressError","getCreateAddressError","getPickupOptionsError","pickupOptions","getLoadExtensionsError","isSelectingOption","isUpdatingShippingOption","isInitializing","isSigningIn","isSigningOut","isExecutingPaymentMethodCheckout","isWidgetInteracting","isUpdatingAddress","isExecuting","isFinalizing","isExecutingSpamCheck","isLoadingCheckout","isUpdatingCheckout","isUpdating","isFinalizingOrder","isLoadingOrder","isLoadingCart","isLoadingBillingCountries","isLoadingShippingCountries","isLoadingPaymentMethods","isLoadingPaymentMethod","isLoadingMethod","isInitializingPayment","isInitializingCustomer","isInitializedCustomer","isLoadingShippingOptions","isUpdatingBillingAddress","isUpdatingSubscriptions","isCreatingCustomerAccount","isCreatingCustomerAddress","isContinuingAsGuest","isUpdatingShippingAddress","isUpdatingConsignment","isDeletingConsignment","isDeleting","isCreatingConsignments","isCreating","isInitializingShipping","isApplyingStoreCredit","isApplying","isApplyingCoupon","isRemovingCoupon","isRemoving","isApplyingGiftCertificate","isRemovingGiftCertificate","isLoadingInstruments","isDeletingInstrument","isLoadingConfig","isSendingSignInEmail","isSending","isLoadingPickupOptions","selectors","statuses","notifyState","_dispatch","loadCheckoutAction","formFieldsAction","loadConfigAction","finalizeOrderIfNeeded","deinitializePayment","loadBillingCountries","loadShippingCountries","loadBillingAddressFields","loadShippingAddressFields","initializeCustomer","deinitializeCustomer","signInEmailRequest","createCustomerAccount","createCustomerAddress","deinitializeShipping","assignItemsToAddress","unassignItemsToAddress","selectConsignmentShippingOption","initializeSpamProtection","executeSpamCheck","CheckoutService","_factoryMethods","mapFromInternalErrorResponse","mapFromStorefrontErrorResponse","factoryMethod","createError","_getType","_isStorefrontErrorResponseBody","_isInternalErrorResponseBody","internalType","storefrontErrorResponse","internalErrorResponse","omitDeep","predicate","clearErrorReducer","isClearErrorAction","objectA","objectB","isArrayEqual","isDateEqual","isRegExpEqual","keyFilter","keysA","keysB","isObjectEqual","currentValue","newValue","objectSet","DEFAULT_STATE","billingAddressReducer","combineReducers","dataReducer","composeReducers","errorsReducer","statusesReducer","reducer","arrayReplace","currentArray","newArray","matchObject","sameAsCurrentCount","sameAsNewCount","countSameAsReplaced","replacedValue","newItem","currentItem","objectMerge","currentObject","CheckoutButtonActionType","cartReducer","DEFAULT_DATA_STATE","initializedContainers","DEFAULT_ERROR_STATE","DEFAULT_STATUS_STATE","checkoutButtonReducer","InitializeButtonSucceeded","DeinitializeButtonSucceeded","InitializeButtonRequested","InitializeButtonFailed","DeinitializeButtonRequested","DeinitializeButtonFailed","configReducer","couponReducer","giftCertificateReducer","customerReducer","customerStrategyReducer","initializeErrors","initializeMethodId","deinitializeError","deinitializeMethodId","signInError","signInMethodId","signOutError","signOutMethodId","executePaymentMethodCheckoutError","executePaymentMethodCheckoutMethodId","widgetInteractionError","widgetInteractionMethodId","isDeinitializing","extensionReducer","formFieldsReducer","countryReducer","orderReducer","metaReducer","orderBillingAddressReducer","paymentReducer","paymentMethodReducer","array","defaultPredicate","findIndex","mergeOrPush","methodA","methodB","loadMethodId","loadMethodError","paymentStrategyReducer","initializeError","executeError","executeMethodId","finalizeError","finalizeMethodId","instrumentReducer","deleteError","failedInstrument","deletingInstrument","remoteCheckoutReducer","updateShippingOptionError","updateError","consignmentReducer","objectFlatten","parent","flattened","keyString","objectWithSortedKeys","sortedArray","current","pickupOptionReducer","sortedflattenedMeta","shippingCountryReducer","shippingStrategyReducer","updateAddressError","updateAddressMethodId","selectOptionError","selectOptionMethodId","signInEmailReducer","storeCreditReducer","subscriptionsReducer","checkoutReducer","createFreezeProxy","trap","proxy","iteratee","getPrototypeOf","traversePrototypeOf","charAt","deepFreeze","createProxy","barclays","authorizenet","elavon","checkoutcom","sagepay","cybersource","cybersourcev2","bnz","converge","orbital","paymetric","moneris","cba_mpgs","worldpayaccess","normalize","identity","createInternalCheckoutSelectorsFactory","getDeinitializeError","getOrderBillingAddress","getInternalPayment","getGatewayPayment","getHostedPayment","createBillingAddressSelector","continueAsGuestError","loadError","createCartSelector","createCartSelectorFactory","createCheckoutButtonSelector","createConfigSelector","filterType","flashMessages","formState","createConfigSelectorFactory","createCountrySelector","createCountrySelectorFactory","createCouponSelector","removeCouponError","applyCouponError","createCustomerSelector","createAddressError","isCreatingAddress","createCustomerStrategySelector","getExecutePaymentMethodCheckoutError","getWidgetInteractionError","createCustomerStrategySelectorFactory","createGiftCertificateSelector","removeGiftCertificateError","applyGiftCertificateError","createGiftCertificateSelectorFactory","createInstrumentSelector","paymentMethodKey","currentMethod","isMatch","supportedProvider","createInstrumentSelectorFactory","createFormSelector","selectedCountry","processField","itemtype","processCountry","subdivisions","requiresState","processProvince","hasPostalCodes","processsPostCode","createFormSelectorFactory","createPaymentMethodSelector","createPaymentMethodSelectorFactory","createPaymentStrategySelector","getWidgetInteractingError","createPaymentStrategySelectorFactory","createPickupOptionSelector","sortedFlattenedParams","createPickupOptionSelectorFactory","createRemoteCheckoutSelector","createShippingAddressSelector","shippingConsignments","createShippingCountrySelector","createShippingCountrySelectorFactory","createShippingStrategySelector","createShippingStrategySelectorFactory","createConsignmentSelector","addressA","addressB","loadShippingOptionsError","getUnassignedItems","assignedLineItemIds","itemIds","getItemAssignmentError","isAssigningItems","createConsignmentSelectorFactory","createCheckoutSelector","createCheckoutSelectorFactory","createOrderSelector","currentPayment","createOrderSelectorFactory","createOrderBillingAddressSelector","createPaymentSelector","internalPayment","MissingPaymentId","MissingPaymentStatus","MissingPaymentRedirectUrl","createStoreCreditSelector","applyError","createStoreCreditSelectorFactory","createSubscriptionsSelector","createSubscriptionsSelectorFactory","createSignInEmailSelector","sendError","createExtensionSelector","createExtensionSelectorFactory","checkoutButton","orderBillingAddress","remoteCheckout","shouldWarnMutation","createCheckoutStore","initialState","requestErrorFactory","actionTransformer","action$","createInternalCheckoutSelectors","createCheckoutService","checkoutVariantIdentificationToken","orderRequestSender","checkoutRequestSender","configActionCreator","subscriptionsActionCreator","formFieldsActionCreator","registryV2","customerRegistryV2","extensionActionCreator","ExtensionActionCreator","ExtensionRequestSender","remoteCheckoutRequestSender","remoteCheckoutActionCreator","paymentRequestTransformer","paymentRequestSender","braintreePaymentProcessor","braintreeHostedForm","overlay","createBraintreePaymentProcessor","checkoutValidator","paymentHumanVerificationHandler","paymentStrategyActionCreator","storefrontPaymentRequestSender","PPSDKStrategy","PaymentResumer","consignmentRequestSender","createShippingStrategyRegistry","isTerminalCacheKeyMap","_lastId","_map","maps","_usedMaps","maxSize","onExpire","getKey","_resolveMap","parentMap","usedCount","_generateMap","_removeLeastUsedMap","getUsedCount","isMatched","mapIndex","unshift","terminalMap","recentlyUsedMap","_removeMap","isRootCacheKeyMap","selectorDecorator","resolver","memoizedMethod","cachedValue","isPrivate","selectorMethodDecorator","_checkoutButton","getInitializeButtonError","getDeinitializeButtonError","CheckoutButtonErrorSelector","isInitializingButton","isDeinitializingButton","CheckoutButtonStatusSelector","createCheckoutButtonSelectors","_buttonStrategyActionCreator","initializeButton","containerIds","idPrefix","uniqueId","setUniqueElementId","deinitializeButton","CheckoutButtonInitializer","_registryV2","paymentMethodRequestParams","paymentMethodRequestOptions","isWithBuyNowFeatures","_amazonPayV2ConfigRequestSender","initializeAmazonButtonOptions","Cart","_getCheckoutCreationRequestConfig","_createBuyNowCart","_createCheckoutConfig","public_key","rest","payloadJSON","buyNowCart","fundingicons","layout","tagline","messagingContainerId","_renderPayPalComponents","_renderPayPalMessages","shouldProcessPayment","onAuthorizeError","validButtonStyle","isMessageContainerAvailable","Messages","onPaymentError","_buyNowCart","venmoButtonStyle","backgroundPosition","backgroundSize","backgroundImage","backgroundRepeat","cursor","minHeight","minWidth","braintreevenmo","_handleInitializationVenmoSuccess","_handleInitializationVenmoError","_renderVenmoButton","_removeVenmoContainer","buttonContainer","venmoButton","buyBowCart","removeAttribute","_handlePostForm","_getGooglePayClientOptions","paymentDataCallbacks","onPaymentDataChanged","callbackTrigger","INITIALIZE","newTransactionInfo","googlePayButton","ESTIMATED","callbackIntents","OFFER","_paypalScriptLoader","_host","fundingCreditOption","allowedSources","allowCredit","disallowedSources","Button","funding","allowed","disallowed","onAuthorize","paymentID","payerID","payerId","payerInfo","payer_info","buttonClassName","_requiresShipping","_buyNowInitializeOptions","_getRequestWithEmptyTotal","onpaymentmethodselected","_handlePaymentMethodSelected","completePaymentMethodSelection","BoltConnect","setupProductPageCheckout","addButtonContainer","boltButtonContainer","boltButtonObject","getBoltObjectData","domainUrl","getButtonHeight","buttonBorderRadius","getButtonBorderRadius","publishable_key","variant","border_radius","buttonSize","Small","Large","Medium","buttonShape","Pill","Rect","buyNowFlowCallbacks","renderMessages","paypalMessagesOptions","getValidVenmoButtonStyles","paypalExpressScriptLoader","loadPaypalSDK","paypalSDK","getStyle","CheckoutButtonNotInitialized","getPaymentData","createCheckoutButtonInitializer","checkoutButtonStrategyFactories","createCheckoutButtonStrategy","braintreeSdkCreator","amazonPayV2RequestSender","createCheckoutButtonRegistry","EmbeddedCheckoutEventType","NotEmbeddableErrorType","UnknownError","EmbeddedContentEventType","IS_COOKIE_ALLOWED_KEY","LAST_ALLOW_COOKIE_ATTEMPT_KEY","_iframeCreator","_messageListener","_messagePoster","_loadingIndicator","_storage","_location","_isAttached","CheckoutComplete","CheckoutError","CheckoutLoaded","onFrameLoad","FrameLoaded","onSignOut","SignedOut","_configureStyles","_allowCookie","_attemptLogin","createFrame","_retryAllowCookie","FrameError","iFrameResizer","StyleConfigured","encodeURIComponent","lastAttempt","MissingContent","EmbeddedCheckout","MissingContainer","allowPaymentRequest","_toResizableFrame","timeoutInterval","handleMessage","iframes","scrolling","sizeWidth","heightCalculationMethod","contentId","originalIframeResizer","STORAGE_PREFIX","embedCheckout","handleFrameLoadedEvent","hasAttribute","_untargetedMessagePoster","_messageHandlers","postComplete","_postMessage","postError","_transformError","postFrameError","untargeted","postFrameLoaded","postLoaded","postSignedOut","receiveStyles","handler","_notifyMessageHandlers","IframeEmbeddedCheckoutMessenger","NoopEmbeddedCheckoutMessenger","createEmbeddedCheckoutMessenger","parentWindow","parentOrigin","DEFAULT_LOCALE","KEY_PREFIX","_logger","_transformConfig","locales","_locales","_translations","_formatters","mapKeys","translationKey","_hasTranslations","translate","prefixedKey","messageFormat","compile","_transformData","defaultLocale","defaultTranslations","_flattenObject","fallbackTranslations","union","fallbackLocale","parentKey","resultKey","LanguageService","createLanguageService","currencySettings","symbolLocation","symbol","thousandsSeparator","decimalSeparator","parseInt","_symbolLocation","_symbol","_thousandsSeparator","_decimalSeparator","formattedNumber","_formatNumber","formattedCurrency","_formatCurrency","positiveAmount","abs","_toFixed","decimalAmount","parsedIntegerAmount","precision","_storeConfig","_customerFormatter","_storeFormatter","toCustomerCurrency","exchangeRate","toStoreCurrency","CurrencyService","createCurrencyService","isAnalyticsTrackerWindowGA","ga","sendGoogleAnalytics","nonInteraction","isPayloadSizeLimitReached","serializeAnalyticsEventPayload","acc","AnalyticStepId","ANALYTIC_STEPS","CUSTOMER","BILLING","checkoutService","analytics","checkoutSteps","_checkoutStarted","_completedSteps","_viewedSteps","_analyticStepOrder","trackCheckoutStarted","extraItemsData","track","getTrackingPayload","revenue","trackOrderComplete","isMissingOrdersExperimentEnabled","affiliation","products","product","trackStepViewed","stepId","getIdFromStep","hasStepViewed","trackViewed","backfill","trackStepCompleted","hasStepCompleted","trackCompleted","i","shippingMethod","getShopperCurrency","getPaymentMethodName","shippingMethodId","completedStepId","getStoreProfile","toShopperCurrency","getProducts","product_id","giftCertificateItems","physicalAndDigitalItems","itemAttributes","image_url","createStepTracker","stepTrackerConfig","AnalyticStepType","AnalyticStepOrder","bodlEvents","_emailEntryBegan","_shippingOptionsShown","setState","checkoutBegin","_getCommonCheckoutData","emitCheckoutBeginEvent","orderPurchased","channelId","emitOrderPurchasedEvent","event_id","channel_id","cart_value","coupon_codes","shipping_cost","line_items","_getProducts","stepCompleted","currentStep","_hasStepCompleted","_trackCompletedStep","customerEmailEntry","emit","customerSuggestionInit","customerSuggestionExecute","customerPaymentMethodExecuted","showShippingMethods","selectedPaymentMethod","paymentOption","commonData","emitPaymentDetailsProvidedEvent","clickPayButton","paymentRejected","paymentComplete","exitCheckout","_trackShippingStepCompleted","emitShippingDetailsProvidedEvent","shipping_method","base_price","sale_price","purchase_price","product_name","gift_certificate_id","gift_certificate_name","gift_certificate_theme","theme","variant_id","brand_name","category_names","flatten","retail_price","retailPrice","createBodlService","isBodlEnabled"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"checkout-sdk.js","mappings":"kCAAAA,EAAOC,QAAUC,QAAQ,iB,UCAzBF,EAAOC,QAAUC,QAAQ,gD,GCCrBC,EAA2B,CAAC,EAGhC,SAASC,EAAoBC,GAE5B,IAAIC,EAAeH,EAAyBE,GAC5C,QAAqBE,IAAjBD,EACH,OAAOA,EAAaL,QAGrB,IAAID,EAASG,EAAyBE,GAAY,CAGjDJ,QAAS,CAAC,GAOX,OAHAO,EAAoBH,GAAUL,EAAQA,EAAOC,QAASG,GAG/CJ,EAAOC,OACf,CCrBAG,EAAoBK,EAAKT,IACxB,IAAIU,EAASV,GAAUA,EAAOW,WAC7B,IAAOX,EAAiB,QACxB,IAAM,EAEP,OADAI,EAAoBQ,EAAEF,EAAQ,CAAEG,EAAGH,IAC5BA,CAAM,ECLdN,EAAoBQ,EAAI,CAACX,EAASa,KACjC,IAAI,IAAIC,KAAOD,EACXV,EA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,QAAQ8lE,GAAf,e,EAA7B,KAAwB,IAcnC,OAAOjpD,CACX,C,SChCA,YACI,mBACI,YAAM,mEAAiE,K,OAEvE,EAAKrpB,KAAO,oCACZ,EAAKX,KAAO,kC,CAChB,CACJ,OAP+D,oBAO/D,EAPA,CAA+D,GCF/D,IAAYmzE,GCJPC,IDIL,SAAYD,GACR,kDACA,wDACA,wDACA,oDACA,0DACA,0DACA,wDACA,8DACA,8DACA,4DACA,kEACA,kEACA,yEACA,2EACA,sEACH,CAhBD,CAAYA,KAAAA,GAAyB,KCJrC,SAAKC,GACD,oBACA,uCACA,oBACA,uCACA,kBACA,sBACA,kDACA,wBACA,sBACA,sBACA,0BACA,cACA,sBACA,4BACA,mCACA,uCACA,qCACA,uCACA,2BACA,gDACA,sBACA,sBACA,4BACA,gCACA,YACA,+BACA,8BACA,oDACA,cACA,kBACA,sBACA,kBACA,kBACA,kBACA,oBACA,mDACA,oBACA,oBACA,YACA,wCACA,kBACA,iCACA,8CACA,mCACA,gDACA,0DACA,yEACA,8CACA,2BACA,oBACA,qBACA,oBACA,sBACA,yBACA,6CACA,wBACA,qCACA,mCACA,kDACA,kDACA,4CACA,uBACA,iBACA,kCACA,sDACA,0BACA,sCACA,kBACA,WACH,CAtED,CAAKA,KAAAA,GAAmB,KAwExB,YCtCA,kBACI,WACYtnD,EACAC,EACA6V,EACArX,GAHA,KAAAuB,kBAAAA,EACA,KAAAC,oBAAAA,EACA,KAAA6V,oBAAAA,EACA,KAAArX,6BAAAA,CACT,CA+PP,OA7PI,YAAAU,QAAA,SACIzqB,EACA8B,GAFJ,WAIY,EAA4D9B,EAAO,QAAnE0V,OAAO,IAAG,GAAC,EAA4B,EAAEe,EAAmBzW,EAAO,eACrEN,EAAO,CAAE6O,SAAUmH,EAAQnH,UAEjC,OAAO,SAACxM,GACI,IACAw+B,EADax+B,EAAME,WAAU,SACOyO,qBAAoB,uBAEhE,OAAO,IAAA9Q,QACH2gC,EACM,EAAKxW,6BAA6B9a,8B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J,IASR1wB,EAASve,SACL,4BACA,WACI,WAAI,GACAlJ,EACA2yC,EACAK,EACAs3E,EACAr3E,EACAJ,EACAkN,GAAgC//C,EAAO,IAAI,IAP/C,IAWRynB,EAASve,SACL,aACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EACA,IAAI,GACA5yC,EACAizC,EACA,IAAI,GAAe,IAAI,GAAqBh7B,KARpD,IAaRwP,EAASve,SACL,eACA,WAAM,WAAI,GAA0BlJ,EAAO6yC,EAAoBI,EAAzD,IAGVxrB,EAASve,SACL,cACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAD,EACAg3E,EALJ,IASRviG,EAASve,SACL,yBACA,WACI,WAAI,GACAlJ,EACA2yC,EACAK,EACAs3E,EACAr3E,EACAJ,EACAkN,GACI//C,EACA,IAAI,GACA,IAAI,GAAoB,IAAI,GAAsBiY,WAG1Dhc,EACA,IAAI,GAAoB,IAAI,GAAsBgc,IAdtD,IAkBRwP,EAASve,SACL,qBACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAD,EACAg3E,EALJ,IASRviG,EAASve,SACL,oBACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAD,EACAg3E,EALJ,IASRviG,EAASve,SACL,4BACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAD,EACAg3E,GACA,EANJ,IAURviG,EAASve,SACL,4BACA,WACI,WAAI,GACAlJ,EACA2yC,EACAK,EACAs3E,EACAr3E,EACAJ,EACAkJ,GAA4C9jC,EAAcmM,GAC1D,IAAI,GAAyBnM,GARjC,IAYRwP,EAASve,SACL,aACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EACAI,EACA,IAAI,GAAoB/6B,GACxB0iC,EAPJ,IAWRlzB,EAASve,SACL,aACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EACA70B,EALJ,IASR0J,EAASve,SACL,aACA,WACI,WAAI,GACAlJ,EACAoqH,EACAv3E,EACAI,EACAD,EACA42E,EACAz2E,EACA,IAAI,GAAqBl7B,GAR7B,IAYRwP,EAASve,SACL,gBACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EACA,IAAI,GACA5yC,EACAizC,EACAD,EACA,IAAI,GAAe,IAAI,GAAqB/6B,KATpD,IAcRwP,EAASve,SACL,kBACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EACA,IAAI,GACA5yC,EACAizC,EACA,IAAI,GAAe,IAAI,GAAqBh7B,KARpD,IAaRwP,EAASve,SACL,QACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EACA,IAAI,GACA5yC,EACAizC,EACA,IAAI,GAAe,IAAI,GAAqBh7B,KARpD,IAaRwP,EAASve,SACL,6BACA,WACI,WAAI,GACAlJ,EACA2yC,EACAK,EACAs3E,EACAr3E,EACAJ,EACAkN,GAAgC//C,EAAO,IAAI,IAP/C,IAWRynB,EAASve,SACL,kBACA,WACI,WAAI,GACAlJ,EACA2yC,EACAK,EACAs3E,EACAr3E,EACAJ,EACAkN,GAAgC//C,EAAO,IAAI,IAP/C,IAWRynB,EAASve,SACL,gBACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EACA70B,EALJ,IASR0J,EAASve,SACL,oBACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EAJJ,IAQRnrB,EAASve,SACL,sBACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EAJJ,IAQRnrB,EAASve,SACL,2BACA,WACI,WAAI,GACAlJ,EACA2yC,EACAK,EACAs3E,EACAr3E,EACAJ,EACAkN,GACI//C,EACA,IAAI,GAAgCokB,IAExC,IAAI,GAXR,IAeRqD,EAASve,SACL,sBACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EAJJ,IAQRnrB,EAASve,SACL,qBACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EAJJ,IAQRnrB,EAASve,SACL,cACA,WACI,WAAI,GACAlJ,EACA2yC,EACAE,EACAI,EACAD,EACAs3E,EACAlmG,EACA,IAAI,GAAqBnM,GACzB,IAAI,GAAgBA,GATxB,IAaRwP,EAASve,SACL,iBACA,WACI,WAAI,GACAlJ,EACAgzC,EACAH,EACAI,EACAE,EACA,IAAI,GAAyBl7B,GAAc,IAAA6/C,wBAC3ChlB,EAPJ,IAWRrrB,EAASve,SACL,WACA,WACI,WAAI,GACAlJ,EACA6yC,EACAG,EACA62E,EACA,IAAI,GAAmB5xG,GAL3B,IASRwP,EAASve,SACL,aACA,WACI,WAAI,GACAlJ,EACA6yC,EACAg3E,EACA,IAAI,GAAqB5xG,GACzB,IAAI,GAAqBmM,GAL7B,IASRqD,EAASve,SACL,SACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAl1B,EACAi1B,EALJ,IASRvrB,EAASve,SACL,eACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACA,IAAI,GAAuBh7B,GAC3B0iC,EALJ,IASRlzB,EAASve,SACL,WACA,WACI,WAAI,GACA0pC,EACA5yC,EACA,IAAI,GAAmBiY,GACvB46B,EACAI,EALJ,IASRxrB,EAASve,SACL,YACA,WACI,WAAI,GACA0pC,EACA5yC,EACA6yC,EACAI,EACAE,EALJ,IASR1rB,EAASve,SACL,QACA,WACI,WAAI,GACAlJ,EACA6yC,EACAG,EACAu3E,EACAt3E,EACA,IAAI,GAAgBh7B,GANxB,IAURwP,EAASve,SACL,uBACA,WACI,WAAI,GACAlJ,EACA2yC,EACAK,EACAs3E,EACAr3E,EACAJ,EACAkN,GAAgC//C,EAAO,IAAI,IAP/C,IAWRynB,EAASve,SACL,WACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EACA,IAAI,GACA5yC,EACAizC,EACAD,EACA,IAAI,GAAe,IAAI,GAAqB/6B,KATpD,IAcRwP,EAASve,SACL,mBACA,WACI,WAAI,GACAlJ,EACA6yC,EACA,IAAI,GAAmB56B,GAH3B,IAORwP,EAASve,SACL,0BACA,WACI,WAAI,GACAlJ,EACA6yC,EACA,IAAI,GAAmB56B,GAH3B,IAORwP,EAASve,SACL,UACA,WACI,WAAIshH,GACAxqH,EACA6yC,EACAmoD,GACIh7F,EACA6yC,EACAzuB,EACA62E,EACAroD,GAEJ,IAAI63E,GAAermG,EAAe62E,GAClC,IAAI,GAAe,SAXvB,IAeRxzE,EAASve,SACL,YACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAD,EACAG,EACA02E,EACAU,EAPJ,IAWR9iG,EAASve,SACL,aACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EACA70B,EALJ,IASR0J,EAASve,SACL,WACA,WACI,WAAI,GACAlJ,EACA2yC,EACAE,EACAI,EACAD,EACAs3E,EACAlmG,EACA,IAAI,GAAmBnM,GAR3B,IAYRwP,EAASve,SACL,sBACA,WACI,WAAI,GACAlJ,EACA2yC,EACAK,EACAs3E,EACAr3E,EACAJ,EACAkN,GAAgC//C,EAAO,IAAI,IAP/C,IAWRynB,EAASve,SACL,0BACA,WACI,WAAI,GACAlJ,EACA2yC,EACAK,EACAs3E,EACAr3E,EACAJ,EACAkN,GAAgC//C,EAAO,IAAI,IAP/C,IAWRynB,EAASve,SACL,aACA,WACI,WAAI,GACAlJ,EACAgzC,EACAC,EACAJ,EACA,IAAI,GAAqB56B,GACzBk7B,EACAP,EACA+H,EARJ,IAYRlzB,EAASve,SACL,eACA,WACI,WAAI,GACAlJ,EACAgzC,EACAC,EACAJ,EACA,IAAI,GAAsB56B,GAC1Bk7B,EACAL,EAPJ,IAWRrrB,EAASve,SACL,WACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EACA,IAAI,GAAgB36B,GALxB,IASRwP,EAASve,SACL,mBACA,WACI,WAAI,GACAlJ,EACA6yC,EACAI,EACAL,EAJJ,IAQRnrB,EAASve,SACL,8BACA,WACI,WAAI,GACAlJ,EACA2yC,EACAK,EACAs3E,EACAr3E,EACAJ,EACAkN,GAAgC//C,EAAO,IAA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EACA2yC,EACAY,EACA+gF,EACAv2G,EACAvS,OANJ,IAURic,EAASve,SACL,oBACA,WACI,WAAI,GACAlJ,EACAgzC,EACAO,EACA+gF,EACAv2G,EALJ,IASR0J,EAASve,SACL,sBACA,WACI,WAAI,GACAlJ,EACA+d,EACA40B,EACAoN,GAAgC//C,EAAO,IAAI,IAC3CuzC,EALJ,IASR9rB,EAASve,SACL,sBACA,WACI,WAAI,GACAlJ,EACA+d,EACA40B,EACAoN,GAAgC//C,EAAO,IAAI,IAC3CuzC,EALJ,IASR9rB,EAASve,SACL,2BACA,WACI,WAAI,GACAlJ,EACA+d,EACA40B,EACAoN,GAAgC//C,EAAO,IAAI,IAC3CuzC,EALJ,IASR9rB,EAASve,SACL,kBACA,WACI,WAAI,GACAlJ,EACA+d,EACA40B,EACAoN,GAAgC//C,EAAO,IAAI,IAC3CuzC,EALJ,IASR9rB,EAASve,SACL,wBACA,WACI,WAAI,GACAlJ,EACA+d,EACA40B,EACAoN,GACI//C,EACA,IAAI,GAA8Bs0H,IAEtC/gF,EARJ,IAYR9rB,EAASve,SACL,0BACA,WACI,WAAI,GACAlJ,EACA+d,EACA40B,EACAoN,GACI//C,EACA,IAAI,GAAgCokB,IAExCmvB,EARJ,IAYR9rB,EAASve,SACL,4BACA,WACI,WAAI,GACAlJ,EACA+d,EACA40B,EACAoN,GAAgC//C,EAAO,IAAI,IAC3CuzC,EALJ,IASR9rB,EAASve,SACL,sBACA,WACI,WAAI,GACAlJ,EACA+d,EACA40B,EACAoN,GAAgC//C,EAAO,IAAI,IAC3CuzC,EALJ,IASR9rB,EAASve,SACL,qBACA,WACI,WAAI,GACAlJ,EACA+d,EACA40B,EACAoN,GAAgC//C,EAAO,IAAI,IAC3CuzC,EALJ,IASR9rB,EAASve,SACL,wBACA,WACI,WAAI,GACAlJ,EACA+d,EACA40B,EACAoN,GAAgC//C,EAAO,IAAI,IAC3CuzC,EALJ,IASR9rB,EAASve,SACL,eACA,WACI,WAAI,GACAlJ,EACA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/checkout-sdk/external commonjs \"iframe-resizer\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"iframe-resizer/js/iframeResizer.contentWindow\"","webpack://@bigcommerce/checkout-sdk/webpack/bootstrap","webpack://@bigcommerce/checkout-sdk/webpack/runtime/compat get default export","webpack://@bigcommerce/checkout-sdk/webpack/runtime/define property getters","webpack://@bigcommerce/checkout-sdk/webpack/runtime/hasOwnProperty shorthand","webpack://@bigcommerce/checkout-sdk/webpack/runtime/make namespace object","webpack://@bigcommerce/checkout-sdk/external commonjs \"@bigcommerce/request-sender\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"@bigcommerce/script-loader\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"tslib\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"@bigcommerce/data-store\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"rxjs\"","webpack://@bigcommerce/checkout-sdk/external commonjs \"rxjs/operators\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/throw-error-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/standard-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/set-prototype-of.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/missing-data-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/errors/unable-to-continue-as-guest-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/content-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/sdk-version-headers.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/error-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/error-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/get-environment.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/log/console-logger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/log/noop-logger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/log/get-default-logger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/log/create-logger.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"@bigcommerce/memoize\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/data-store/cachable-action-decorator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/data-store/is-action-options.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/data-store/cache-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/config/config-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/config/config-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/request-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/errors/checkout-not-available-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/internal-api-headers.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/config/config-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/coupon-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/coupon-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-default-includes.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-params.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"lodash\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/join-includes.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/coupon-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/gift-certificate-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/gift-certificate-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/gift-certificate-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/is-resolvable-module.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/invalid-argument-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/registry/registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/registry/resolve-id-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/to-resolvable-module.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/standard-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/set-prototype-of.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/missing-data-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/not-implemented-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/invalid-argument-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-method-cancelled-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay-session-factory.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/create-apple-pay-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-method-failed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/not-initialized-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/request-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-method-invalid-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/custom-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-method-client-unavailable-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/create-bolt-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"@bigcommerce/form-poster\"","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/is-braintree-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/paypal.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal/braintree-paypal-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal/create-braintree-paypal-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/buy-now-cart-creation-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/cart/cart-source.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/http-request/internal-api-headers.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/http-request/content-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/http-request/sdk-version-headers.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/create-paypal-commerce-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/paypal-commerce-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/create-paypal-commerce-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit/paypal-commerce-credit-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit/create-paypal-commerce-credit-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-venmo/paypal-commerce-venmo-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-venmo/create-paypal-commerce-venmo-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/create-customer-strategy-registry-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/is-spam-protection-succeeded-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-strategy-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-strategy-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/join-or-merge-includes.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/http-request/merge-includes.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/form/form-fields-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/form/form-fields-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/form/form-fields-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/apple-pay/is-apple-pay-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-comparator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/errors/cart-changed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-validator.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/cancellable-promise/cancellable-promise.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/errors/unexpected-detachment-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/detachment-observer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/mutation-observer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/url/parse-url.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/is-iframe-event.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-event-poster.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/bind-decorator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-event-listener.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/url/append-www.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/spam-protection-challenge-not-completed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/carding-protection-challenge-not-completed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/carding-protection-failed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/payment-human-verification-handler.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/not-initialized-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/spam-protection-failed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/spam-protection-not-loaded-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/google-recaptcha.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/google-recaptcha-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/create-spam-protection.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/map-from-payment-error-response.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/errors/invalid-hosted-form-config-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/errors/invalid-hosted-form-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/errors/invalid-hosted-form-value-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/hosted-field-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/iframe-content/hosted-input-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/hosted-field.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/hosted-form.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/is-vaulted-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/hosted-form-order-data-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/hosted-form-factory.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/errors/spam-protection-not-completed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/errors/cart-consistency-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/errors/order-tax-provider-unavailable-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-request-sender.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"@bigcommerce/bigpay-client\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/create-payment-client.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/is-billing-address-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/address/map-to-internal-address.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/amount-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/map-to-internal-coupon.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/generated/checkout-button-method-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/map-to-internal-gift-certificate.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/map-to-internal-line-items.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/map-gift-certificate-to-internal-line-item.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/map-to-internal-line-item.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/map-to-internal-cart.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/promotion/map-to-discount-notifications.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/map-to-internal-customer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/iframe-content/card-expiry-formatter.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"card-validator\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/hosted-form/iframe-content/card-number-formatter.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/map-to-internal-order.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/map-to-internal-shipping-option.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-request-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/spam-protection-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/spam-protection-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/spam-protection/spam-protection-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/store-credit/store-credit-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/store-credit/store-credit-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/store-credit/store-credit-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/errors/update-subscriptions-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/is-plain-object.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/clone-result.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-integration/create-payment-integration-selectors.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-integration/default-payment-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/data-store/create-data-store-projection.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-integration/payment-integration-store-projection-factory.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment-integration/create-payment-integration-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/getShippableItemsCount.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/getLineItemsCount.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/guard.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/amazon-pay-v2/amazon-pay-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/amazon-pay-v2/amazon-pay-v2-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/errors/payment-method-client-unavailable-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/amazon-pay-v2/amazon-pay-v2-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/amazon-pay-v2/create-amazon-pay-v2-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/unsupported-browser-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-sdk-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-visacheckout-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/create-braintree-visacheckout-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/visacheckout-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/chasepay/chasepay-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/errors/remote-checkout-synchronization-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-get-first-and-last-name.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/create-googlepay-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-adyenv2-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-adyenv3-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-authorizenet-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-bnz-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-braintree-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-checkoutcom-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-cybersourcev2-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-orbital-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-stripe-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-stripe-upe-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-worldpay-access-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/masterpass/masterpass-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/stripe-upe/stripe-upe-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/not-implemented-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/amazon-pay-v2/amazon-pay-v2-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/braintree/braintree-visacheckout-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/braintree/map-to-legacy-billing-address.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/braintree/map-to-legacy-shipping-address.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/map-to-braintree-shipping-address-override.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/paypal/paypal-sdk.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/braintree/braintree-paypal-credit-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/chasepay/chasepay-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/default/default-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/googlepay/googlepay-customer-method-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/googlepay/googlepay-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/masterpass/get-callback-url.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/masterpass/masterpass-supported-locales.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/masterpass/format-locale.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/masterpass/masterpass-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/square/square-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/stripe-upe/stripe-upe.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/strategies/stripe-upe/stripe-upe-customer-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/errors/extension-not-found-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/errors/invalid-extension-config-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-iframe.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-argument-invalid-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/is-vaulted-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/browser-info/get-browser-info.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/order-finalization-not-required-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/is-request-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-invalid-form-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-integration/src/adyenv2/adyenv2.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-integration/src/adyenv2/adyenv2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-integration/src/adyenv2/adyenv2-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-integration/src/adyenv2/create-adyenv2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/is-hosted-intrument-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-integration/src/adyenv3/adyenv3.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-integration/src/adyenv3/adyenv3-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-integration/src/adyenv3/adyenv3-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/adyen-integration/src/adyenv3/create-adyenv3-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/create-apple-pay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/util-types/guard.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/hosted-form/hosted-field-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/is-hosted-card-field-options-map.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/is-hosted-stored-card-field-options-map.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/types.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-constants.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-hosted-form.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/is-bluesnap-direct-input-validation-error-description.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-hosted-input-validator.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-name-on-card-input.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/is-array-of-allowed-props.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/create-bluesnap-direct-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-ecp-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/is-bluesnap-direct-ecp-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/create-bluesnap-direct-ecp-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-apm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/is-bluesnap-direct-provider-data.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/bluesnap-direct-iframe-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/bluesnap-direct-integration/src/create-bluesnap-direct-apm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"local-storage-fallback\"","webpack://@bigcommerce/checkout-sdk/./packages/analytics/src/analytics-extra-items-manager.ts","webpack://@bigcommerce/checkout-sdk/./packages/analytics/src/is-analytics-step-tracker-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/is-with-account-creation.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/is-bolt-payment-data.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/create-bolt-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/is-us-bank-account-instrument-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal-ach/braintree-paypal-ach-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-paypal-ach/create-braintree-paypal-ach-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-local-payment-methods/braintree-local-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/ui/src/loading-indicator/loading-indicator.ts","webpack://@bigcommerce/checkout-sdk/./packages/braintree-integration/src/braintree-local-payment-methods/create-braintree-local-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/credit-card-integration/src/credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/credit-card-integration/src/create-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/external-integration/src/external-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/external-integration/src/is-additional-action.ts","webpack://@bigcommerce/checkout-sdk/./packages/external-integration/src/create-external-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/legacy-integration/src/legacy-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/legacy-integration/src/create-legacy-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/no-payment-integration/src/no-payment-data-required-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/no-payment-integration/src/create-no-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/offline-integration/src/offline-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/offline-integration/src/create-offline-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/payment/payment-status-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/offsite-integration/src/offsite-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/offsite-integration/src/create-offsite-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/paypal-commerce-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/create-paypal-commerce-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit/paypal-commerce-credit-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit/create-paypal-commerce-credit-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-venmo/paypal-commerce-venmo-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-venmo/create-paypal-commerce-venmo-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/timeout-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-alternative-methods/paypal-commerce-alternative-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-alternative-methods/create-paypal-commerce-alternative-methods-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/hosted-form/is-credit-card-form-fields.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit-card/paypal-commerce-credit-cards-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/common/utility/object-with-kebab-case-keys.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit-card/create-paypal-commerce-credit-cards-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/sezzle-integration/src/sezzle-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/sezzle-integration/src/create-sezzle-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/payment-integration-api/src/errors/payment-execute-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/squarev2-integration/src/squarev2-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/squarev2-integration/src/squarev2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/squarev2-integration/src/squarev2-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/squarev2-integration/src/is-squarev2-window.ts","webpack://@bigcommerce/checkout-sdk/./packages/squarev2-integration/src/create-squarev2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/geography/country-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/geography/country-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/geography/country-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/create-payment-strategy-registry-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/errors/order-finalization-not-required-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/storage/browser-storage.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/ppsdk-payment-method.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/storefront-payment-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/adyenv2/adyenv2-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/adyenv3/adyenv3-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/errors/payment-argument-invalid-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/errors/payment-method-cancelled-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/affirm/affirm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/affirm/affirm-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/affirm/affirmJs.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/errors/order-finalization-not-completed-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/afterpay/afterpay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/afterpay/afterpay-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/amazon-pay-v2/amazon-pay-v2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/credit-card/credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/barclays/barclays-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-status-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/bluesnapv2/bluesnapv2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/bnz/bnz-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/ui/src/overlay/overlay.ts","webpack://@bigcommerce/checkout-sdk/./packages/ui/src/overlay/overlay-style.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/errors/payment-invalid-form-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-payment-options.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-regular-field.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/is-braintree-form-fields-map.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-hosted-form.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"@braintree/browser-detection\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/is-credit-card-instrument-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/is-hosted-intrument-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-credit-card-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/is-braintree-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-paypal-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-venmo-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/braintree-visacheckout-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cardinal/cardinal-three-d-secure-flow-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/is-credit-card-like.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cardinal/cardinal.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cardinal/cardinal-client.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cardinal/cardinal-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cardinal/cardinal-three-d-secure-flow.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/errors/payment-method-declined-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cba-mpgs/cba-mpgs.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cba-mpgs/cba-mpgs-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cba-mpgs/cba-mpgs-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/chasepay/chasepay.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/chasepay/chasepay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-response-body.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/checkoutcom-custom/checkoutcom-custom-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/checkoutcom-custom/checkoutcom-apm/checkoutcom-apm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/checkoutcom-custom/checkoutcom-sepa/checkoutcom-fawry-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/checkoutcom-custom/checkoutcom-ideal/checkoutcom-ideal-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/checkoutcom-custom/checkoutcom-sepa/checkoutcom-sepa-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/clearpay/clearpay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/clearpay/clearpay-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/converge/converge-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/credit-card-redirect/credit-card-redirect-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cybersource/cybersource-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/cybersourcev2/cybersourcev2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/digitalriver/digitalriver.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/digitalriver/digitalriver-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/digitalriver/digitalriver-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/digitalriver/digitalriver-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/browser-info/get-browser-info.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-adyenv2-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-adyenv3-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/googlepay/googlepay-checkoutcom-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/humm/humm-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/klarnav2/klarna-supported-countries.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/klarna/klarna-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/klarna/klarna-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/klarnav2/klarnav2-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/klarnav2/klarnav2-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/klarnav2/klarnav2-token-updater.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/masterpass/masterpass-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/mollie/mollie-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/mollie/mollie-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/moneris/moneris-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/opy/opy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/opy/opy-payment-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/opy/opy-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/opy/opy-library.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/opy/opy-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/paypal/paypal-pro-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/paypal/paypal-express-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/paypal/paypal-script-loader.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"query-string\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/continue-handler/redirect/RedirectionState.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/ppsdk-sub-strategy-type.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/continue-handler/continue-handler.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/continue-handler/redirect/redirect.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/continue-handler/human-verification/human-verification.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/step-handler.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/success.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/failure.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/step-handler/create-step-handler.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/ppsdk-completed-payments.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/ppsdk-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/get-ppsdk-payment-method.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/ppsdk-sub-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/initialization-strategies/card.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/initialization-strategies/none.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/sub-strategies/card-sub-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/sub-strategies/none-sub-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/create-ppsdk-sub-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/ppsdk/ppsdk-payment-resumer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/quadpay/quadpay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/sage-pay/sage-pay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/timeout-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/square/square-form.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/square/square-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/square/square-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/stripe-upe/stripe-upe-supported-locales.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/stripe-upe/format-locale.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/stripe-upe/stripe-upe-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/stripev3/stripev3.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/stripev3/stripev3-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/stripev3/stripev3-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/stripev3/stripev3-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/wepay/wepay-risk-client.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/wepay/wepay-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/worldpayaccess/worldpayaccess-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/zip/zip-payment-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/date-time/is-future.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/date-time/add-minutes.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-response-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/map-to-paypal-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/map-to-bank-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/map-to-card-instrument.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-country-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-country-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-country-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-strategy-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-strategy-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/strategies/amazon-pay-v2/amazon-pay-v2-shipping-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/strategies/default/default-shipping-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/strategies/stripe-upe/stripe-upe-shipping-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-request-sender.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"reselect\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/selector/with-memoized-combiner.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/selector/create-selector.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"shallowequal\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/selector/create-shallow-equal-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/error-message-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/to-single-line.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-checkout-service-error-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-store-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-store-error-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-store-status-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-checkout-selectors.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/unrecoverable-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/map-from-internal-error-response.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/request-error-factory.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/map-from-storefront-error-response.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/omit-deep.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/clear-error-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/is-equal.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/replace.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/object-set.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/array-replace.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/object-merge.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-actions.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/config/config-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/config/config-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/coupon-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/coupon-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/gift-certificate-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/gift-certificate-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-strategy-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-strategy-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/form/form-fields-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/form/form-fields-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/geography/country-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/geography/country-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order-billing-address/order-billing-address-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order-billing-address/order-billing-address-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/merge-or-push.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/object-flatten.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/object-with-sorted-keys.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-country-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-country-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-strategy-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-strategy-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/store-credit/store-credit-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/create-freeze-proxy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/supported-payment-instruments.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/address/is-address-equal.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/store-credit/store-credit-state.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-internal-checkout-selectors.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/billing/billing-address-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/coupon-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/remote-checkout/remote-checkout-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-address-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order-billing-address/order-billing-address-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/signin-email/signin-email-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/cart-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/config/config-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/geography/country-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/customer-strategy-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/coupon/gift-certificate-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/instrument/instrument-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/form/form-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-method-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/payment-strategy-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/pickup-option-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-country-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/shipping-strategy-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/consignment-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/checkout-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/order/order-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/store-credit/store-credit-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/subscription/subscriptions-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/extension/extension-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-checkout-store.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/create-request-error-factory.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-action-transformer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-checkout-store-reducer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout/create-checkout-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/customer/create-customer-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/create-payment-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/payment/strategies/braintree/create-braintree-payment-processor.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/shipping/create-shipping-strategy-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/cache-key-maps.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/cache-key-resolver.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/selector/selector-decorator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/utility/is-private.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-error-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-status-selector.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/create-checkout-button-selectors.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/is-element-id.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/dom/set-unique-element-id.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/checkout-button-strategy-action-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/cart/errors/buy-now-cart-creation-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/amazon-pay-v2/amazon-pay-v2-button-options.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/amazon-pay-v2/errors/amazon-pay-v2-config-creation-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/amazon-pay-v2/amazon-pay-v2-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/amazon-pay-v2/amazon-pay-v2-request-sender.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/braintree/get-valid-button-style.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/braintree/braintree-paypal-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/braintree/braintree-paypal-credit-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/braintree/braintree-venmo-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/googlepay/googlepay-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/masterpass/masterpass-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/strategies/paypal/paypal-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/apple-pay-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/apple-pay-integration/src/create-apple-pay-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/bolt-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/bolt-integration/src/create-bolt-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/paypal-commerce-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce/create-paypal-commerce-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit/paypal-commerce-credit-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-credit/create-paypal-commerce-credit-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-venmo/paypal-commerce-venmo-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-venmo/create-paypal-commerce-venmo-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-alternative-methods/paypal-commerce-alternative-methods-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-commerce-integration/src/paypal-commerce-alternative-methods/create-paypal-commerce-alternative-methods-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-express-integration/src/paypal-express-types.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-express-integration/src/paypal-express-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-express-integration/src/paypal-express-script-loader.ts","webpack://@bigcommerce/checkout-sdk/./packages/paypal-express-integration/src/create-paypal-express-button-strategy.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/create-checkout-button-initializer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/create-checkout-button-registry-v2.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/checkout-buttons/create-checkout-button-registry.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/embedded-checkout-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/errors/invalid-login-token-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/errors/not-embeddable-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/iframe-content/embedded-content-events.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/embedded-checkout.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/resizable-iframe-creator.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/iframe/iframe-resizer.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/embed-checkout.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/iframe-content/handle-frame-loaded-event.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/common/error/errors/custom-error.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/iframe-content/iframe-embedded-checkout-messenger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/iframe-content/noop-embedded-checkout-messenger.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/embedded-checkout/iframe-content/create-embedded-checkout-messenger.ts","webpack://@bigcommerce/checkout-sdk/external commonjs \"messageformat\"","webpack://@bigcommerce/checkout-sdk/./packages/core/src/locale/language-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/locale/create-language-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/currency/currency-formatter.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/currency/currency-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/currency/create-currency-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/analytics/analytics-tracker-ga.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/analytics/analytics-step-tracker.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/analytics/noop-step-tracker.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/analytics/create-step-tracker.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/bodl/analytics-steps.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/bodl/bodl-emitter-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/bodl/noop-bodl-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/bodl/create-bodl-service.ts","webpack://@bigcommerce/checkout-sdk/./packages/core/src/bodl/is-bodl-enabled.ts"],"sourcesContent":["module.exports = require(\"iframe-resizer\");","module.exports = require(\"iframe-resizer/js/iframeResizer.contentWindow\");","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@bigcommerce/request-sender\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@bigcommerce/script-loader\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"tslib\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@bigcommerce/data-store\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"rxjs\");","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"rxjs/operators\");","import { Action, createErrorAction } from '@bigcommerce/data-store';\nimport { concat, Observable, of, throwError } from 'rxjs';\n\nexport default function throwErrorAction(\n type: TType,\n error?: TPayload,\n meta?: TMeta,\n): Observable> {\n if (isErrorAction(error)) {\n return concat(of(error), throwError(createErrorAction(type, error.payload, meta)));\n }\n\n return throwError(createErrorAction(type, error, meta));\n}\n\nfunction isErrorAction(action: any): action is Action {\n return action && action.type && action.error;\n}\n","import { setPrototypeOf } from '../../utility';\n\nimport CustomError from './custom-error';\n\n/**\n * This error type should not be constructed directly. It is a base class for\n * all custom errors thrown in this library.\n */\nexport default abstract class StandardError extends Error implements CustomError {\n name = 'StandardError';\n type = 'standard';\n\n constructor(message?: string) {\n super(message || 'An unexpected error has occurred.');\n\n setPrototypeOf(this, new.target.prototype);\n\n if (typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(this, new.target);\n } else {\n this.stack = new Error(this.message).stack;\n }\n }\n}\n","export default function setPrototypeOf(object: any, prototype: object) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(object, prototype);\n } else {\n object.__proto__ = prototype;\n }\n\n return object;\n}\n","import StandardError from './standard-error';\n\nexport enum MissingDataErrorType {\n MissingBillingAddress,\n MissingCart,\n MissingCheckout,\n MissingConsignments,\n MissingCustomer,\n MissingCheckoutConfig,\n MissingOrder,\n MissingOrderConfig,\n MissingOrderId,\n MissingPayment,\n MissingPaymentId,\n MissingPaymentInstrument,\n MissingPaymentMethod,\n MissingPaymentRedirectUrl,\n MissingPaymentStatus,\n MissingPaymentToken,\n MissingShippingAddress,\n}\n\n/**\n * Throw this error when data that is expected to exist is missing. Usually it\n * is due to the fact that certain data has not been retrieved from or saved to\n * the server yet. And such data is required to perform certain actions.\n */\nexport default class MissingDataError extends StandardError {\n constructor(public subtype: MissingDataErrorType) {\n super(getErrorMessage(subtype));\n\n this.name = 'MissingDataError';\n this.type = 'missing_data';\n }\n}\n\nfunction getErrorMessage(type: MissingDataErrorType): string {\n switch (type) {\n case MissingDataErrorType.MissingBillingAddress:\n return 'Unable to proceed because billing address data is unavailable.';\n\n case MissingDataErrorType.MissingCart:\n return 'Unable to proceed because cart data is unavailable.';\n\n case MissingDataErrorType.MissingConsignments:\n return 'Unable to proceed because consignments data is unavailable.';\n\n case MissingDataErrorType.MissingCheckout:\n return 'Unable to proceed because checkout data is unavailable.';\n\n case MissingDataErrorType.MissingCustomer:\n return 'Unable to proceed because customer data is unavailable.';\n\n case MissingDataErrorType.MissingCheckoutConfig:\n case MissingDataErrorType.MissingOrderConfig:\n return 'Unable to proceed because configuration data is unavailable.';\n\n case MissingDataErrorType.MissingOrder:\n return 'Unable to proceed because order data is unavailable.';\n\n case MissingDataErrorType.MissingOrderId:\n return 'Unable to proceed because order ID is unavailable or not generated yet.';\n\n case MissingDataErrorType.MissingPayment:\n return 'Unable to proceed because payment data is unavailable.';\n\n case MissingDataErrorType.MissingPaymentToken:\n return 'Unable to proceed because the token required to submit a payment is missing.';\n\n case MissingDataErrorType.MissingPaymentMethod:\n return 'Unable to proceed because payment method data is unavailable or not properly configured.';\n\n case MissingDataErrorType.MissingShippingAddress:\n return 'Unable to proceed because shipping address data is unavailable.';\n\n default:\n return 'Unable to proceed because the required data is unavailable.';\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Checkout } from '../checkout';\n\nexport enum BillingAddressActionType {\n UpdateBillingAddressRequested = 'UPDATE_BILLING_ADDRESS_REQUESTED',\n UpdateBillingAddressSucceeded = 'UPDATE_BILLING_ADDRESS_SUCCEEDED',\n UpdateBillingAddressFailed = 'UPDATE_BILLING_ADDRESS_FAILED',\n\n ContinueAsGuestRequested = 'CONTINUE_AS_GUEST_REQUESTED',\n ContinueAsGuestSucceeded = 'CONTINUE_AS_GUEST_SUCCEEDED',\n ContinueAsGuestFailed = 'CONTINUE_AS_GUEST_FAILED',\n}\n\nexport type BillingAddressAction = ContinueAsGuestAction | UpdateBillingAddressAction;\n\nexport type UpdateBillingAddressAction =\n | UpdateBillingAddressRequested\n | UpdateBillingAddressSucceeded\n | UpdateBillingAddressFailed;\n\nexport type ContinueAsGuestAction =\n | ContinueAsGuestRequested\n | ContinueAsGuestSucceeded\n | ContinueAsGuestFailed;\n\nexport interface UpdateBillingAddressRequested extends Action {\n type: BillingAddressActionType.UpdateBillingAddressRequested;\n}\n\nexport interface UpdateBillingAddressSucceeded extends Action {\n type: BillingAddressActionType.UpdateBillingAddressSucceeded;\n}\n\nexport interface UpdateBillingAddressFailed extends Action {\n type: BillingAddressActionType.UpdateBillingAddressFailed;\n}\n\nexport interface ContinueAsGuestRequested extends Action {\n type: BillingAddressActionType.ContinueAsGuestRequested;\n}\n\nexport interface ContinueAsGuestSucceeded extends Action {\n type: BillingAddressActionType.ContinueAsGuestSucceeded;\n}\n\nexport interface ContinueAsGuestFailed extends Action {\n type: BillingAddressActionType.ContinueAsGuestFailed;\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when a shopper tries to sign in as a guest but\n * they are already signed in as a registered customer.\n */\nexport default class UnableToContinueAsGuestError extends StandardError {\n constructor(message?: string) {\n super(\n message || 'Unable to continue as a guest because the customer is already signed in.',\n );\n\n this.name = 'UnableToContinueAsGuestError';\n this.type = 'unable_to_continue_as_guest';\n }\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Response } from '@bigcommerce/request-sender';\nimport { concat, defer, empty, merge, Observable, Observer, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { Checkout, InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\nimport { GuestCredentials } from '../customer';\nimport { SubscriptionsActionCreator, UpdateSubscriptionsAction } from '../subscription';\n\nimport { BillingAddressUpdateRequestBody } from './billing-address';\nimport {\n BillingAddressActionType,\n ContinueAsGuestAction,\n UpdateBillingAddressAction,\n} from './billing-address-actions';\nimport { UnableToContinueAsGuestError } from './errors';\n\nimport { BillingAddressRequestSender } from '.';\n\nexport default class BillingAddressActionCreator {\n constructor(\n private _requestSender: BillingAddressRequestSender,\n private _subscriptionActionCreator: SubscriptionsActionCreator,\n ) {}\n\n continueAsGuest(\n credentials: GuestCredentials,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const customer = state.customer.getCustomer();\n\n if (customer && !customer.isGuest) {\n throw new UnableToContinueAsGuestError();\n }\n\n const billingAddress = state.billingAddress.getBillingAddress();\n\n let billingAddressRequestBody: Partial;\n\n if (!billingAddress) {\n billingAddressRequestBody = credentials;\n } else {\n const { country, ...existingBillingAddressRequestBody } = billingAddress;\n\n billingAddressRequestBody = {\n ...existingBillingAddressRequestBody,\n ...credentials,\n };\n }\n\n return merge(\n concat(\n of(createAction(BillingAddressActionType.ContinueAsGuestRequested)),\n defer(async () => {\n const { body } = await this._createOrUpdateBillingAddress(\n checkout.id,\n billingAddressRequestBody,\n options,\n );\n\n return createAction(\n BillingAddressActionType.ContinueAsGuestSucceeded,\n body,\n );\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(BillingAddressActionType.ContinueAsGuestFailed, error),\n ),\n ),\n this._updateCustomerConsent(credentials, options),\n );\n };\n }\n\n updateAddress(\n address: Partial,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(createAction(BillingAddressActionType.UpdateBillingAddressRequested));\n\n const billingAddress = state.billingAddress.getBillingAddress();\n\n // If email is not present in the address provided by the client, then\n // fall back to the stored email as it could have been set separately\n // using a convenience method. We can't rely on billingAddress having\n // an ID to consider that there's a preexisting email, as billingAddress\n // object from Order doesn't have an ID.\n const billingAddressRequestBody = {\n ...address,\n email:\n typeof address.email === 'undefined' && billingAddress\n ? billingAddress.email\n : address.email,\n };\n\n if (billingAddress && billingAddress.id) {\n billingAddressRequestBody.id = billingAddress.id;\n }\n\n this._createOrUpdateBillingAddress(checkout.id, billingAddressRequestBody, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n BillingAddressActionType.UpdateBillingAddressSucceeded,\n body,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n BillingAddressActionType.UpdateBillingAddressFailed,\n response,\n ),\n );\n });\n });\n }\n\n private _updateCustomerConsent(\n { email, acceptsAbandonedCartEmails, acceptsMarketingNewsletter }: GuestCredentials,\n options?: RequestOptions,\n ): Observable {\n if (\n (acceptsAbandonedCartEmails === undefined || acceptsAbandonedCartEmails === null) &&\n (acceptsMarketingNewsletter === undefined || acceptsMarketingNewsletter === null)\n ) {\n return empty();\n }\n\n return this._subscriptionActionCreator.updateSubscriptions(\n {\n email,\n acceptsMarketingNewsletter: acceptsMarketingNewsletter || false,\n acceptsAbandonedCartEmails: acceptsAbandonedCartEmails || false,\n },\n options,\n );\n }\n\n private _createOrUpdateBillingAddress(\n checkoutId: string,\n address: Partial,\n options?: RequestOptions,\n ): Promise> {\n if (!address.id) {\n return this._requestSender.createAddress(checkoutId, address, options);\n }\n\n return this._requestSender.updateAddress(checkoutId, address, options);\n }\n}\n","enum ContentType {\n Json = 'application/json',\n JsonV1 = 'application/vnd.bc.v1+json',\n}\n\nexport default ContentType;\n","export const SDK_VERSION_HEADERS = { 'X-Checkout-SDK-Version': LIBRARY_VERSION };\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { AddressRequestBody } from '../address';\nimport { Checkout } from '../checkout';\nimport { ContentType, RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nimport { BillingAddressUpdateRequestBody } from './billing-address';\n\nconst DEFAULT_PARAMS = {\n include: [\n 'cart.lineItems.physicalItems.options',\n 'cart.lineItems.digitalItems.options',\n 'customer',\n 'promotions.banners',\n ].join(','),\n};\n\nexport default class BillingAddressRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n createAddress(\n checkoutId: string,\n address: Partial,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/billing-address`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, {\n body: address,\n params: DEFAULT_PARAMS,\n headers,\n timeout,\n });\n }\n\n updateAddress(\n checkoutId: string,\n address: Partial,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const { id, ...body } = address;\n const url = `/api/storefront/checkouts/${checkoutId}/billing-address/${id}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.put(url, { params: DEFAULT_PARAMS, body, headers, timeout });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nexport enum ErrorActionType {\n ClearError = 'CLEAR_ERROR',\n}\n\nexport type ErrorAction = ClearErrorAction;\n\nexport interface ClearErrorAction extends Action {\n type: ErrorActionType.ClearError;\n payload: Error;\n}\n","import { ClearErrorAction, ErrorActionType } from './error-actions';\n\nexport default class ErrorActionCreator {\n clearError(error: Error): ClearErrorAction {\n return {\n type: ErrorActionType.ClearError,\n payload: error,\n };\n }\n}\n","export default function getEnvironment(): string {\n try {\n return process.env.NODE_ENV || 'development';\n } catch (e) {\n return 'development';\n }\n}\n","import Logger from './logger';\n\nexport default class ConsoleLogger implements Logger {\n constructor(private _console?: Console) {}\n\n log(...messages: any[]): void {\n this._logToConsole('log', ...messages);\n }\n\n info(...messages: any[]): void {\n this._logToConsole('info', ...messages);\n }\n\n warn(...messages: any[]): void {\n this._logToConsole('warn', ...messages);\n }\n\n error(...messages: any[]): void {\n this._logToConsole('error', ...messages);\n }\n\n debug(...messages: any[]): void {\n this._logToConsole('debug', ...messages);\n }\n\n private _logToConsole(type: keyof Console, ...messages: any[]): void {\n if (!this._console || !this._console[type]) {\n return;\n }\n\n this._console[type].call(this._console, ...messages);\n }\n}\n","import Logger from './logger';\n\nexport default class NoopLogger implements Logger {\n log(): void {}\n\n info(): void {}\n\n warn(): void {}\n\n error(): void {}\n\n debug(): void {}\n}\n","import { getEnvironment } from '../utility';\n\nimport createLogger from './create-logger';\nimport Logger from './logger';\n\nconst logger = createLogger(getEnvironment() !== 'test');\n\nexport default function getDefaultLogger(): Logger {\n return logger;\n}\n","import ConsoleLogger from './console-logger';\nimport Logger from './logger';\nimport NoopLogger from './noop-logger';\n\nexport default function createLogger(isEnabled = true): Logger {\n if (!isEnabled) {\n return new NoopLogger();\n }\n\n return new ConsoleLogger(console);\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@bigcommerce/memoize\");","import cacheAction from './cache-action';\nimport isActionOptions from './is-action-options';\n\nexport default function cachableActionDecorator any>(\n _: object,\n key: string,\n descriptor: TypedPropertyDescriptor,\n): TypedPropertyDescriptor {\n const memoizedMethods = new WeakMap();\n\n function decorateMethod(this: object, method: TMethod): TMethod {\n return ((...args: any[]) => {\n const lastArg = args[args.length - 1];\n const { useCache } = isActionOptions(lastArg) ? lastArg : { useCache: false };\n\n if (!useCache) {\n return method.call(this, ...args);\n }\n\n const instanceMethods = memoizedMethods.get(this) || {};\n\n if (!memoizedMethods.get(this)) {\n memoizedMethods.set(this, instanceMethods);\n }\n\n if (!instanceMethods[key]) {\n instanceMethods[key] = cacheAction(method);\n }\n\n return instanceMethods[key].call(this, ...args);\n }) as TMethod;\n }\n\n return {\n get() {\n if (typeof descriptor.value !== 'function') {\n throw new Error('Decorator should be used in functions');\n }\n\n const value = decorateMethod.call(this, descriptor.value);\n\n Object.defineProperty(this, key, { ...descriptor, value });\n\n return value;\n },\n };\n}\n","import ActionOptions from './action-options';\n\nexport default function isActionOptions(param: any): param is ActionOptions {\n return param && typeof param.useCache === 'boolean';\n}\n","import { Action, ThunkAction } from '@bigcommerce/data-store';\nimport { memoize } from '@bigcommerce/memoize';\nimport { from, Observable } from 'rxjs';\nimport { shareReplay } from 'rxjs/operators';\n\nexport default function cacheAction(fn: TFunction): TFunction {\n function decoratedFn(this: any, ...args: any[]) {\n const action = fn.call(this, ...args);\n\n if (action instanceof Observable) {\n return from(action).pipe(shareReplay());\n }\n\n if (typeof action === 'function') {\n return memoize((store) => from(action(store)).pipe(shareReplay()));\n }\n\n return action;\n }\n\n return memoize(decoratedFn as TFunction);\n}\n\ntype CreateActionFn = (...args: any[]) => Observable | ThunkAction | Action;\n","import { Action } from '@bigcommerce/data-store';\n\nimport Config from './config';\n\nexport enum ConfigActionType {\n LoadConfigRequested = 'LOAD_CONFIG_REQUESTED',\n LoadConfigSucceeded = 'LOAD_CONFIG_SUCCEEDED',\n LoadConfigFailed = 'LOAD_CONFIG_FAILED',\n}\n\nexport type LoadConfigAction =\n | LoadConfigRequestedAction\n | LoadConfigSucceededAction\n | LoadConfigFailedAction;\n\nexport interface LoadConfigRequestedAction extends Action {\n type: ConfigActionType.LoadConfigRequested;\n}\n\nexport interface LoadConfigSucceededAction extends Action {\n type: ConfigActionType.LoadConfigSucceeded;\n}\n\nexport interface LoadConfigFailedAction extends Action {\n type: ConfigActionType.LoadConfigFailed;\n}\n","import { createAction, createErrorAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { ActionOptions, cachableAction } from '../common/data-store';\nimport { RequestOptions } from '../common/http-request';\n\nimport { ConfigActionType, LoadConfigAction } from './config-actions';\n\nimport { ConfigRequestSender } from '.';\n\nexport default class ConfigActionCreator {\n constructor(private _configRequestSender: ConfigRequestSender) {}\n\n @cachableAction\n loadConfig(options?: RequestOptions & ActionOptions): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(createAction(ConfigActionType.LoadConfigRequested));\n\n this._configRequestSender\n .loadConfig(options)\n .then((response) => {\n observer.next(\n createAction(ConfigActionType.LoadConfigSucceeded, response.body),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(createErrorAction(ConfigActionType.LoadConfigFailed, response));\n });\n });\n }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport StandardError from './standard-error';\n\nconst DEFAULT_RESPONSE = {\n body: {},\n headers: {},\n status: 0,\n};\n\n/**\n * Throw this error if we are unable to make a request to the server. It wraps\n * any server response into a JS error object.\n */\nexport default class RequestError extends StandardError {\n body: TBody | {};\n headers: { [key: string]: any };\n errors: Array<{ code: string; message?: string }>;\n status: number;\n\n constructor(\n response?: Response,\n {\n message,\n errors,\n }: {\n message?: string;\n errors?: Array<{ code: string; message?: string }>;\n } = {},\n ) {\n const { body, headers, status } = response || DEFAULT_RESPONSE;\n\n super(message || 'An unexpected error has occurred.');\n\n this.name = 'RequestError';\n this.type = 'request';\n this.body = body;\n this.headers = headers;\n this.status = status;\n this.errors = errors || [];\n }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { InternalErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RequestError } from '../../common/error/errors';\n\n/**\n * Throw this error when we are unable to retrieve a checkout object from the\n * server using the provided ID. It could be because the shopper does not have\n * permission to view the object, or the ID itself is invalid.\n */\nexport default class CheckoutNotAvailableError extends RequestError {\n constructor(response: Response) {\n super(response, { message: response.body.title });\n\n this.name = 'CheckoutNotAvailableError';\n this.type = 'checkout_not_available';\n }\n}\n","export const INTERNAL_USE_ONLY =\n 'This API endpoint is for internal use only and may change in the future';\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { CheckoutNotAvailableError } from '../checkout/errors';\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport Config from './config';\n\nexport default class ConfigRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n loadConfig({ timeout, params }: RequestOptions = {}): Promise> {\n const url = '/api/storefront/checkout-settings';\n\n return this._requestSender\n .get(url, {\n timeout,\n headers: {\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n params,\n })\n .catch((error) => {\n if (error.status >= 400 && error.status < 500) {\n throw new CheckoutNotAvailableError(error);\n }\n\n throw error;\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Checkout } from '../checkout';\nimport { RequestError } from '../common/error/errors';\n\nexport enum CouponActionType {\n ApplyCouponRequested = 'APPLY_COUPON_REQUESTED',\n ApplyCouponSucceeded = 'APPLY_COUPON_SUCCEEDED',\n ApplyCouponFailed = 'APPLY_COUPON_FAILED',\n\n RemoveCouponRequested = 'REMOVE_COUPON_REQUESTED',\n RemoveCouponSucceeded = 'REMOVE_COUPON_SUCCEEDED',\n RemoveCouponFailed = 'REMOVE_COUPON_FAILED',\n}\n\nexport type CouponAction = ApplyCouponAction | RemoveCouponAction;\n\nexport type ApplyCouponAction =\n | ApplyCouponRequestedAction\n | ApplyCouponSucceededAction\n | ApplyCouponFailedAction;\n\nexport type RemoveCouponAction =\n | RemoveCouponRequestedAction\n | RemoveCouponSucceededAction\n | RemoveCouponFailedAction;\n\nexport interface ApplyCouponRequestedAction extends Action {\n type: CouponActionType.ApplyCouponRequested;\n}\n\nexport interface ApplyCouponSucceededAction extends Action {\n type: CouponActionType.ApplyCouponSucceeded;\n}\n\nexport interface ApplyCouponFailedAction extends Action> {\n type: CouponActionType.ApplyCouponFailed;\n}\n\nexport interface RemoveCouponRequestedAction extends Action {\n type: CouponActionType.RemoveCouponRequested;\n}\n\nexport interface RemoveCouponSucceededAction extends Action {\n type: CouponActionType.RemoveCouponSucceeded;\n}\n\nexport interface RemoveCouponFailedAction extends Action {\n type: CouponActionType.RemoveCouponFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\n\nimport {\n ApplyCouponAction,\n CouponAction,\n CouponActionType,\n RemoveCouponAction,\n} from './coupon-actions';\nimport CouponRequestSender from './coupon-request-sender';\n\nexport default class CouponActionCreator {\n constructor(private _couponRequestSender: CouponRequestSender) {}\n\n applyCoupon(\n code: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(createAction(CouponActionType.ApplyCouponRequested));\n\n this._couponRequestSender\n .applyCoupon(checkout.id, code, options)\n .then(({ body }) => {\n observer.next(createAction(CouponActionType.ApplyCouponSucceeded, body));\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(CouponActionType.ApplyCouponFailed, response),\n );\n });\n });\n }\n\n removeCoupon(\n code: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(createAction(CouponActionType.RemoveCouponRequested));\n\n this._couponRequestSender\n .removeCoupon(checkout.id, code, options)\n .then(({ body }) => {\n observer.next(createAction(CouponActionType.RemoveCouponSucceeded, body));\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(CouponActionType.RemoveCouponFailed, response),\n );\n });\n });\n }\n}\n","const CHECKOUT_DEFAULT_INCLUDES = [\n 'cart.lineItems.physicalItems.options',\n 'cart.lineItems.digitalItems.options',\n 'customer',\n 'customer.customerGroup',\n 'payments',\n 'promotions.banners',\n];\n\nexport default CHECKOUT_DEFAULT_INCLUDES;\n","export enum CheckoutIncludes {\n AvailableShippingOptions = 'consignments.availableShippingOptions',\n PhysicalItemsCategoryNames = 'cart.lineItems.physicalItems.categoryNames',\n DigitalItemsCategoryNames = 'cart.lineItems.digitalItems.categoryNames',\n}\n\nexport default interface CheckoutParams {\n include?: CheckoutIncludes[] | CheckoutIncludeParam;\n}\n\nexport type CheckoutIncludeParam = {\n [key in CheckoutIncludes]?: boolean;\n};\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"lodash\");","import { uniq } from 'lodash';\n\nexport default function joinIncludes(includes: T[]): string {\n return uniq(includes).join(',');\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Checkout, CHECKOUT_DEFAULT_INCLUDES, CheckoutIncludes } from '../checkout';\nimport {\n ContentType,\n joinIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nexport default class CouponRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n applyCoupon(\n checkoutId: string,\n couponCode: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/coupons`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes([\n ...CHECKOUT_DEFAULT_INCLUDES,\n CheckoutIncludes.AvailableShippingOptions,\n ]),\n },\n body: { couponCode },\n });\n }\n\n removeCoupon(\n checkoutId: string,\n couponCode: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/coupons/${couponCode}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.delete(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes([\n ...CHECKOUT_DEFAULT_INCLUDES,\n CheckoutIncludes.AvailableShippingOptions,\n ]),\n },\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Checkout } from '../checkout';\nimport { RequestError } from '../common/error/errors';\n\nexport enum GiftCertificateActionType {\n ApplyGiftCertificateRequested = 'APPLY_GIFT_CERTIFICATE_REQUESTED',\n ApplyGiftCertificateSucceeded = 'APPLY_GIFT_CERTIFICATE_SUCCEEDED',\n ApplyGiftCertificateFailed = 'APPLY_GIFT_CERTIFICATE_FAILED',\n\n RemoveGiftCertificateRequested = 'REMOVE_GIFT_CERTIFICATE_REQUESTED',\n RemoveGiftCertificateSucceeded = 'REMOVE_GIFT_CERTIFICATE_SUCCEEDED',\n RemoveGiftCertificateFailed = 'REMOVE_GIFT_CERTIFICATE_FAILED',\n}\n\nexport type GiftCertificateAction = ApplyGiftCertificateAction | RemoveGiftCertificateAction;\n\nexport type ApplyGiftCertificateAction =\n | ApplyGiftCertificateRequestedAction\n | ApplyGiftCertificateSucceededAction\n | ApplyGiftCertificateFailedAction;\n\nexport type RemoveGiftCertificateAction =\n | RemoveGiftCertificateRequestedAction\n | RemoveGiftCertificateSucceededAction\n | RemoveGiftCertificateFailedAction;\n\nexport interface ApplyGiftCertificateRequestedAction extends Action {\n type: GiftCertificateActionType.ApplyGiftCertificateRequested;\n}\n\nexport interface ApplyGiftCertificateSucceededAction extends Action {\n type: GiftCertificateActionType.ApplyGiftCertificateSucceeded;\n}\n\nexport interface ApplyGiftCertificateFailedAction\n extends Action> {\n type: GiftCertificateActionType.ApplyGiftCertificateFailed;\n}\n\nexport interface RemoveGiftCertificateRequestedAction extends Action {\n type: GiftCertificateActionType.RemoveGiftCertificateRequested;\n}\n\nexport interface RemoveGiftCertificateSucceededAction extends Action {\n type: GiftCertificateActionType.RemoveGiftCertificateSucceeded;\n}\n\nexport interface RemoveGiftCertificateFailedAction\n extends Action> {\n type: GiftCertificateActionType.RemoveGiftCertificateFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\n\nimport {\n ApplyGiftCertificateAction,\n GiftCertificateActionType,\n RemoveGiftCertificateAction,\n} from './gift-certificate-actions';\n\nimport { GiftCertificateRequestSender } from '.';\n\nexport default class GiftCertificateActionCreator {\n constructor(private _giftCertificateRequestSender: GiftCertificateRequestSender) {}\n\n applyGiftCertificate(\n giftCertificate: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(\n createAction(GiftCertificateActionType.ApplyGiftCertificateRequested),\n );\n\n this._giftCertificateRequestSender\n .applyGiftCertificate(checkout.id, giftCertificate, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n GiftCertificateActionType.ApplyGiftCertificateSucceeded,\n body,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n GiftCertificateActionType.ApplyGiftCertificateFailed,\n response,\n ),\n );\n });\n });\n }\n\n removeGiftCertificate(\n giftCertificate: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(\n createAction(GiftCertificateActionType.RemoveGiftCertificateRequested),\n );\n\n this._giftCertificateRequestSender\n .removeGiftCertificate(checkout.id, giftCertificate, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n GiftCertificateActionType.RemoveGiftCertificateSucceeded,\n body,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n GiftCertificateActionType.RemoveGiftCertificateFailed,\n response,\n ),\n );\n });\n });\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Checkout, CHECKOUT_DEFAULT_INCLUDES } from '../checkout';\nimport {\n ContentType,\n joinIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nexport default class GiftCertificateRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n applyGiftCertificate(\n checkoutId: string,\n giftCertificateCode: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/gift-certificates`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n },\n body: { giftCertificateCode },\n });\n }\n\n removeGiftCertificate(\n checkoutId: string,\n giftCertificateCode: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/gift-certificates/${giftCertificateCode}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.delete(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n },\n });\n }\n}\n","import ResolvableModule from './resolvable-module';\n\nexport default function isResolvableModule(\n module: TModule,\n): module is ResolvableModule {\n return 'resolveIds' in module;\n}\n","import StandardError from './standard-error';\n\n/**\n * This error should be thrown when a method is unable to proceed because the\n * caller has not provided all the arguments according to their requirements,\n * i.e.: if an argument is missing or it is not the expected data type.\n */\nexport default class InvalidArgumentError extends StandardError {\n constructor(message?: string) {\n super(message || 'Invalid arguments have been provided.');\n\n this.name = 'InvalidArgumentError';\n this.type = 'invalid_argument';\n }\n}\n","import { InvalidArgumentError } from '../error/errors';\n\nimport Factory from './factory';\n\nexport default class Registry {\n private _factories: { [key: string]: Factory };\n private _instances: { [key: string]: T };\n private _defaultToken: string;\n private _useFallback: string | boolean;\n private _tokenResolver: (token: string, registeredTokens: string[]) => string | undefined;\n\n constructor(options?: RegistryOptions) {\n this._factories = {};\n this._instances = {};\n this._defaultToken = options?.defaultToken ?? 'default';\n this._useFallback = options?.useFallback ?? true;\n this._tokenResolver = options?.tokenResolver ?? ((token) => token);\n }\n\n get(token?: K, cacheToken?: string): T {\n try {\n return this._getInstance(\n token || this._defaultToken,\n cacheToken || token || this._defaultToken,\n );\n } catch (error) {\n if (!this._useFallback) {\n throw error;\n }\n\n return this._getInstance(this._defaultToken, cacheToken || this._defaultToken);\n }\n }\n\n register(token: K, factory: Factory): void {\n if (this._hasFactory(token)) {\n throw new InvalidArgumentError(`'${token}' is already registered.`);\n }\n\n this._factories[token] = factory;\n }\n\n protected _hasFactory(token: string): boolean {\n return !!this._factories[token];\n }\n\n private _hasInstance(token: string): boolean {\n return !!this._instances[token];\n }\n\n private _getInstance(token: string, cacheToken: string): T {\n if (!this._hasInstance(cacheToken)) {\n const resolvedToken = this._tokenResolver(token, Object.keys(this._factories));\n const factory = resolvedToken && this._factories[resolvedToken];\n\n if (!factory) {\n throw new InvalidArgumentError(`'${token}' is not registered.`);\n }\n\n this._instances[cacheToken] = factory();\n }\n\n return this._instances[cacheToken];\n }\n}\n\nexport interface RegistryOptions {\n defaultToken?: string;\n useFallback?: boolean;\n tokenResolver?(token: string, registeredTokens: string[]): string | undefined;\n}\n","import { getDefaultLogger } from '../log';\nimport { getEnvironment } from '../utility';\n\nimport Factory from './factory';\nimport Registry from './registry';\n\nexport default class ResolveIdRegistry {\n private _registry: Registry;\n\n constructor(private _useFallback = false) {\n this._registry = new Registry({\n tokenResolver: this._resolveToken.bind(this),\n useFallback: this._useFallback,\n });\n }\n\n get(resolveId: TToken): TType {\n return this._registry.get(this._encodeToken(resolveId));\n }\n\n register(resolveId: TToken, factory: Factory): void {\n this._registry.register(this._encodeToken(resolveId), factory);\n }\n\n private _encodeToken(resolveId: TToken): string {\n return btoa(JSON.stringify(resolveId));\n }\n\n private _decodeToken(token: string): TToken {\n return JSON.parse(atob(token));\n }\n\n private _resolveToken(token: string, registeredTokens: string[]): string | undefined {\n const query = this._decodeToken(token);\n\n const results: Array<{ token: string; matches: number; default: boolean }> = [];\n\n registeredTokens.forEach((registeredToken) => {\n const resolverId = this._decodeToken(registeredToken);\n\n const result = { token: registeredToken, matches: 0, default: false };\n\n for (const [key, value] of Object.entries(resolverId)) {\n if (key in query && query[key] !== value) {\n result.matches = 0;\n break;\n }\n\n if (key in query && query[key] === value) {\n result.matches++;\n }\n\n if (key === 'default' && value === true) {\n result.default = true;\n }\n }\n\n results.push(result);\n });\n\n const matchedResults = results\n .sort((a, b) => b.matches - a.matches)\n .filter((result) => result.matches > 0);\n\n if (matchedResults.length > 1 && matchedResults[0].matches === matchedResults[1].matches) {\n if (getEnvironment() === 'development') {\n getDefaultLogger().warn(\n 'The provided query matches at least two strategies with the same specificity. This warning can be resolved by making their resolve ID more specific.',\n );\n }\n }\n\n const matched = matchedResults[0];\n\n if (matched && matched.token) {\n return matched.token;\n }\n\n if (this._useFallback) {\n const defaultToken = results.find((result) => result.default)?.token;\n\n if (defaultToken) {\n return defaultToken;\n }\n }\n\n throw new Error('Unable to resolve to a registered token with the provided token.');\n }\n}\n","import ResolvableModule from './resolvable-module';\n\nexport default function toResolvableModule(\n module: TModule,\n resolveIds: TIdentifier[],\n): ResolvableModule {\n return Object.assign(module, { resolveIds });\n}\n","import CustomError from './custom-error';\nimport setPrototypeOf from './set-prototype-of';\n\n/**\n * This error type should not be constructed directly. It is a base class for\n * all custom errors thrown in this library.\n */\nexport default abstract class StandardError extends Error implements CustomError {\n name = 'StandardError';\n type = 'standard';\n\n constructor(message?: string) {\n super(message || 'An unexpected error has occurred.');\n\n setPrototypeOf(this, new.target.prototype);\n\n if (typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(this, new.target);\n } else {\n this.stack = new Error(this.message).stack;\n }\n }\n}\n","export default function setPrototypeOf(object: any, prototype: object) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(object, prototype);\n } else {\n object.__proto__ = prototype;\n }\n\n return object;\n}\n","import StandardError from './standard-error';\n\nexport enum MissingDataErrorType {\n MissingBillingAddress,\n MissingCart,\n MissingCheckout,\n MissingConsignments,\n MissingCustomer,\n MissingCheckoutConfig,\n MissingOrder,\n MissingOrderConfig,\n MissingOrderId,\n MissingPayment,\n MissingPaymentId,\n MissingPaymentInstrument,\n MissingPaymentMethod,\n MissingPaymentRedirectUrl,\n MissingPaymentStatus,\n MissingPaymentToken,\n MissingShippingAddress,\n}\n\n/**\n * Throw this error when data that is expected to exist is missing. Usually it\n * is due to the fact that certain data has not been retrieved from or saved to\n * the server yet. And such data is required to perform certain actions.\n */\nexport default class MissingDataError extends StandardError {\n constructor(public subtype: MissingDataErrorType) {\n super(getErrorMessage(subtype));\n\n this.name = 'MissingDataError';\n this.type = 'missing_data';\n }\n}\n\nfunction getErrorMessage(type: MissingDataErrorType): string {\n switch (type) {\n case MissingDataErrorType.MissingBillingAddress:\n return 'Unable to proceed because billing address data is unavailable.';\n\n case MissingDataErrorType.MissingCart:\n return 'Unable to proceed because cart data is unavailable.';\n\n case MissingDataErrorType.MissingConsignments:\n return 'Unable to proceed because consignments data is unavailable.';\n\n case MissingDataErrorType.MissingCheckout:\n return 'Unable to proceed because checkout data is unavailable.';\n\n case MissingDataErrorType.MissingCustomer:\n return 'Unable to proceed because customer data is unavailable.';\n\n case MissingDataErrorType.MissingCheckoutConfig:\n case MissingDataErrorType.MissingOrderConfig:\n return 'Unable to proceed because configuration data is unavailable.';\n\n case MissingDataErrorType.MissingOrder:\n return 'Unable to proceed because order data is unavailable.';\n\n case MissingDataErrorType.MissingOrderId:\n return 'Unable to proceed because order ID is unavailable or not generated yet.';\n\n case MissingDataErrorType.MissingPayment:\n return 'Unable to proceed because payment data is unavailable.';\n\n case MissingDataErrorType.MissingPaymentToken:\n return 'Unable to proceed because the token required to submit a payment is missing.';\n\n case MissingDataErrorType.MissingPaymentMethod:\n return 'Unable to proceed because payment method data is unavailable or not properly configured.';\n\n case MissingDataErrorType.MissingShippingAddress:\n return 'Unable to proceed because shipping address data is unavailable.';\n\n default:\n return 'Unable to proceed because the required data is unavailable.';\n }\n}\n","import StandardError from './standard-error';\n\n/**\n * Throw this error if we try to call a method that is only a stub and has not\n * been fully implemented.\n */\nexport default class NotImplementedError extends StandardError {\n constructor(message?: string) {\n super(message || 'Not implemented.');\n\n this.name = 'NotImplementedError';\n this.type = 'not_implemented';\n }\n}\n","import StandardError from './standard-error';\n\n/**\n * This error should be thrown when a method is unable to proceed because the\n * caller has not provided all the arguments according to their requirements,\n * i.e.: if an argument is missing or it is not the expected data type.\n */\nexport default class InvalidArgumentError extends StandardError {\n constructor(message?: string) {\n super(message || 'Invalid arguments have been provided.');\n\n this.name = 'InvalidArgumentError';\n this.type = 'invalid_argument';\n }\n}\n","import StandardError from './standard-error';\n\n/**\n * This error should be thrown when the payment flow is cancelled. It could be\n * due to a deliberate user interaction, i.e.: the user clicks on a cancel\n * button which dismisses the payment modal.\n */\nexport default class PaymentMethodCancelledError extends StandardError {\n constructor(message?: string) {\n super(message || 'Payment process was cancelled.');\n\n this.name = 'PaymentMethodCancelledError';\n this.type = 'payment_cancelled';\n }\n}\n","interface ApplePayWindow extends Window {\n ApplePaySession: ApplePaySession;\n}\n\nfunction isApplePayWindow(window: Window): window is ApplePayWindow {\n return 'ApplePaySession' in window;\n}\n\nexport function assertApplePayWindow(window: Window): asserts window is ApplePayWindow {\n if (!isApplePayWindow(window)) {\n throw new Error('Apple pay is not supported');\n }\n}\n\nexport default class ApplePaySessionFactory {\n create(request: ApplePayJS.ApplePayPaymentRequest): ApplePaySession {\n assertApplePayWindow(window);\n\n return new ApplePaySession(1, request);\n }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\nimport { noop } from 'lodash';\n\nimport {\n AddressRequestBody,\n Cart,\n Checkout,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotImplementedError,\n Payment,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n ShippingOption,\n StoreConfig,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithApplePayCustomerInitializeOptions } from './apple-pay-customer-initialize-options';\nimport ApplePaySessionFactory, { assertApplePayWindow } from './apple-pay-session-factory';\n\nconst validationEndpoint = (bigPayEndpoint: string) =>\n `${bigPayEndpoint}/api/public/v1/payments/applepay/validate_merchant`;\n\nenum DefaultLabels {\n Subtotal = 'Subtotal',\n Shipping = 'Shipping',\n}\n\nfunction isShippingOptions(options: ShippingOption[] | undefined): options is ShippingOption[] {\n return options instanceof Array;\n}\n\nexport default class ApplePayCustomerStrategy implements CustomerStrategy {\n private _paymentMethod?: PaymentMethod;\n private _applePayButton?: HTMLElement;\n private _onAuthorizeCallback = noop;\n private _onError = noop;\n private _subTotalLabel: string = DefaultLabels.Subtotal;\n private _shippingLabel: string = DefaultLabels.Shipping;\n\n constructor(\n private _requestSender: RequestSender,\n private _paymentIntegrationService: PaymentIntegrationService,\n private _sessionFactory: ApplePaySessionFactory,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithApplePayCustomerInitializeOptions,\n ): Promise {\n const { methodId, applepay } = options;\n\n assertApplePayWindow(window);\n\n if (!methodId || !applepay) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n container,\n shippingLabel,\n subtotalLabel,\n onError = noop,\n onPaymentAuthorize,\n } = applepay;\n\n this._shippingLabel = shippingLabel || DefaultLabels.Shipping;\n this._subTotalLabel = subtotalLabel || DefaultLabels.Subtotal;\n this._onAuthorizeCallback = onPaymentAuthorize;\n this._onError = onError;\n\n await this._paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this._paymentIntegrationService.getState();\n\n this._paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n await this._paymentIntegrationService.verifyCheckoutSpamProtection();\n\n this._applePayButton = this._createButton(container);\n this._applePayButton.addEventListener('click', this._handleWalletButtonClick.bind(this));\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via Apple, the shopper must click on \"Apple Pay\" button.',\n );\n }\n\n signOut(): Promise {\n throw new NotImplementedError('Need to do signout via apple.');\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n private _createButton(containerId: string): HTMLElement {\n const container = document.getElementById(containerId);\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to create sign-in button without valid container ID.',\n );\n }\n\n const button = document.createElement('button');\n\n button.setAttribute('type', 'button');\n button.setAttribute('aria-label', 'Apple Pay');\n container.appendChild(button);\n\n return button;\n }\n\n private _handleWalletButtonClick(event: Event) {\n event.preventDefault();\n\n const state = this._paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const config = state.getStoreConfigOrThrow();\n const checkout = state.getCheckoutOrThrow();\n\n if (!this._paymentMethod || !this._paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const request = this._getBaseRequest(cart, checkout, config, this._paymentMethod);\n const applePaySession = this._sessionFactory.create(request);\n\n this._handleApplePayEvents(applePaySession, this._paymentMethod, config);\n\n applePaySession.begin();\n }\n\n private _getBaseRequest(\n cart: Cart,\n checkout: Checkout,\n config: StoreConfig,\n paymentMethod: PaymentMethod,\n ): ApplePayJS.ApplePayPaymentRequest {\n const {\n storeProfile: { storeCountryCode, storeName },\n } = config;\n const {\n currency: { code, decimalPlaces },\n } = cart;\n\n const {\n initializationData: { merchantCapabilities, supportedNetworks },\n } = paymentMethod;\n\n const requiresShipping = cart.lineItems.physicalItems.length > 0;\n const total: ApplePayJS.ApplePayLineItem = requiresShipping\n ? {\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n type: 'pending',\n }\n : {\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n type: 'final',\n };\n\n const request: ApplePayJS.ApplePayPaymentRequest = {\n requiredBillingContactFields: ['postalAddress'],\n requiredShippingContactFields: ['email', 'phone'],\n countryCode: storeCountryCode,\n currencyCode: code,\n merchantCapabilities,\n supportedNetworks,\n lineItems: [],\n total,\n };\n\n if (requiresShipping) {\n request.requiredShippingContactFields?.push('postalAddress');\n } else {\n const lineItems: ApplePayJS.ApplePayLineItem[] = [\n {\n label: this._subTotalLabel,\n amount: `${checkout.subtotal.toFixed(decimalPlaces)}`,\n },\n ];\n\n checkout.taxes.forEach((tax) =>\n lineItems.push({\n label: tax.name,\n amount: `${tax.amount.toFixed(decimalPlaces)}`,\n }),\n );\n\n request.lineItems = lineItems;\n }\n\n return request;\n }\n\n private _handleApplePayEvents(\n applePaySession: ApplePaySession,\n paymentMethod: PaymentMethod,\n config: StoreConfig,\n ) {\n applePaySession.onvalidatemerchant = async (event) => {\n try {\n const { body: merchantSession } = await this._onValidateMerchant(\n paymentMethod,\n event,\n );\n\n applePaySession.completeMerchantValidation(merchantSession);\n } catch (err) {\n this._onError(err);\n }\n };\n\n applePaySession.onshippingcontactselected = async (event) =>\n this._handleShippingContactSelected(applePaySession, config, event);\n\n applePaySession.onshippingmethodselected = async (event) =>\n this._handleShippingMethodSelected(applePaySession, config, event);\n\n applePaySession.oncancel = async () => {\n try {\n const url = `/remote-checkout/${paymentMethod.id}/signout`;\n\n await this._requestSender.get(url);\n\n return await this._paymentIntegrationService.loadCheckout();\n } catch (error) {\n return this._onError(new PaymentMethodCancelledError());\n }\n };\n\n applePaySession.onpaymentauthorized = async (event) =>\n this._onPaymentAuthorized(event, applePaySession, paymentMethod);\n }\n\n private async _handleShippingContactSelected(\n applePaySession: ApplePaySession,\n config: StoreConfig,\n event: ApplePayJS.ApplePayShippingContactSelectedEvent,\n ) {\n const shippingAddress = this._transformContactToAddress(event.shippingContact);\n\n try {\n await this._paymentIntegrationService.updateShippingAddress(shippingAddress);\n } catch (error) {\n applePaySession.abort();\n\n return this._onError(error);\n }\n\n const {\n storeProfile: { storeName },\n } = config;\n let state = this._paymentIntegrationService.getState();\n const {\n currency: { decimalPlaces },\n } = state.getCartOrThrow();\n let checkout = state.getCheckoutOrThrow();\n const selectionShippingOptionId = checkout.consignments[0].selectedShippingOption?.id;\n const availableOptions = checkout.consignments[0].availableShippingOptions;\n const selectedOption = availableOptions?.find(({ id }) => id === selectionShippingOptionId);\n const unselectedOptions = availableOptions?.filter(\n (option) => option.id !== selectionShippingOptionId,\n );\n const shippingOptions: ApplePayJS.ApplePayShippingMethod[] = selectedOption\n ? [\n {\n label: selectedOption.description,\n amount: `${selectedOption.cost.toFixed(decimalPlaces)}`,\n detail: selectedOption.additionalDescription,\n identifier: selectedOption.id,\n },\n ]\n : [];\n\n if (unselectedOptions) {\n [\n ...unselectedOptions.filter((option) => option.isRecommended),\n ...unselectedOptions.filter((option) => !option.isRecommended),\n ].forEach((option) =>\n shippingOptions.push({\n label: option.description,\n amount: `${option.cost.toFixed(decimalPlaces)}`,\n detail: option.additionalDescription,\n identifier: option.id,\n }),\n );\n }\n\n if (!isShippingOptions(availableOptions)) {\n throw new Error('Shipping options not available.');\n }\n\n if (availableOptions.length === 0) {\n applePaySession.completeShippingContactSelection(\n ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,\n [],\n {\n type: 'pending',\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n },\n [],\n );\n\n return;\n }\n\n const recommendedOption = availableOptions.find((option) => option.isRecommended);\n\n const optionId = recommendedOption ? recommendedOption.id : availableOptions[0].id;\n const selectedOptionId = selectedOption ? selectedOption.id : optionId;\n\n try {\n await this._updateShippingOption(selectedOptionId);\n } catch (error) {\n return this._onError(error);\n }\n\n state = this._paymentIntegrationService.getState();\n checkout = state.getCheckoutOrThrow();\n\n applePaySession.completeShippingContactSelection({\n newShippingMethods: shippingOptions,\n newTotal: {\n type: 'final',\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n },\n newLineItems: this._getUpdatedLineItems(checkout, decimalPlaces),\n });\n }\n\n private async _handleShippingMethodSelected(\n applePaySession: ApplePaySession,\n config: StoreConfig,\n event: ApplePayJS.ApplePayShippingMethodSelectedEvent,\n ) {\n const {\n storeProfile: { storeName },\n } = config;\n const {\n shippingMethod: { identifier: optionId },\n } = event;\n\n try {\n await this._updateShippingOption(optionId);\n } catch (error) {\n applePaySession.abort();\n\n return this._onError(error);\n }\n\n const state = this._paymentIntegrationService.getState();\n const {\n currency: { decimalPlaces },\n } = state.getCartOrThrow();\n const checkout = state.getCheckoutOrThrow();\n\n applePaySession.completeShippingMethodSelection({\n newTotal: {\n type: 'final',\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n },\n newLineItems: this._getUpdatedLineItems(checkout, decimalPlaces),\n });\n }\n\n private _getUpdatedLineItems(\n checkout: Checkout,\n decimalPlaces: number,\n ): ApplePayJS.ApplePayLineItem[] {\n const lineItems: ApplePayJS.ApplePayLineItem[] = [\n {\n label: this._subTotalLabel,\n amount: `${checkout.subtotal.toFixed(decimalPlaces)}`,\n },\n ];\n\n checkout.taxes.forEach((tax) =>\n lineItems.push({\n label: tax.name,\n amount: `${tax.amount.toFixed(decimalPlaces)}`,\n }),\n );\n lineItems.push({\n label: this._shippingLabel,\n amount: `${checkout.shippingCostTotal.toFixed(decimalPlaces)}`,\n });\n\n return lineItems;\n }\n\n private async _updateShippingOption(optionId: string) {\n return this._paymentIntegrationService.selectShippingOption(optionId);\n }\n\n private async _onValidateMerchant(\n paymentData: PaymentMethod,\n event: ApplePayJS.ApplePayValidateMerchantEvent,\n ) {\n const body = [\n `validationUrl=${event.validationURL}`,\n `merchantIdentifier=${paymentData.initializationData.merchantId}`,\n `displayName=${paymentData.initializationData.storeName}`,\n `domainName=${window.location.hostname}`,\n ].join('&');\n\n return this._requestSender.post(\n validationEndpoint(paymentData.initializationData.paymentsUrl),\n {\n credentials: false,\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'X-XSRF-TOKEN': null,\n },\n body,\n },\n );\n }\n\n private async _onPaymentAuthorized(\n event: ApplePayJS.ApplePayPaymentAuthorizedEvent,\n applePaySession: ApplePaySession,\n paymentMethod: PaymentMethod,\n ) {\n const { token, billingContact, shippingContact } = event.payment;\n const state = this._paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const requiresShipping = cart.lineItems.physicalItems.length > 0;\n const payment: Payment = {\n methodId: paymentMethod.id,\n paymentData: {\n formattedPayload: {\n apple_pay_token: {\n payment_data: token.paymentData,\n payment_method: token.paymentMethod,\n transaction_id: token.transactionIdentifier,\n },\n },\n },\n };\n\n const transformedBillingAddress = this._transformContactToAddress(billingContact);\n const transformedShippingAddress = this._transformContactToAddress(shippingContact);\n const emailAddress = shippingContact?.emailAddress;\n const phone = shippingContact?.phoneNumber || '';\n\n try {\n await this._paymentIntegrationService.updateBillingAddress({\n ...transformedBillingAddress,\n email: emailAddress,\n phone,\n });\n\n if (requiresShipping) {\n await this._paymentIntegrationService.updateShippingAddress(\n transformedShippingAddress,\n );\n }\n\n await this._paymentIntegrationService.submitOrder({\n useStoreCredit: false,\n });\n\n await this._paymentIntegrationService.submitPayment(payment);\n applePaySession.completePayment(ApplePaySession.STATUS_SUCCESS);\n\n return this._onAuthorizeCallback();\n } catch (error) {\n applePaySession.completePayment(ApplePaySession.STATUS_FAILURE);\n\n return this._onError(error);\n }\n }\n\n private _transformContactToAddress(\n contact?: ApplePayJS.ApplePayPaymentContact,\n ): AddressRequestBody {\n return {\n firstName: contact?.givenName || '',\n lastName: contact?.familyName || '',\n city: contact?.locality || '',\n company: '',\n address1: (contact?.addressLines && contact.addressLines[0]) || '',\n address2: (contact?.addressLines && contact.addressLines[1]) || '',\n postalCode: contact?.postalCode || '',\n countryCode: contact?.countryCode || '',\n phone: contact?.phoneNumber || '',\n stateOrProvince: contact?.administrativeArea || '',\n stateOrProvinceCode: contact?.administrativeArea || '',\n customFields: [],\n };\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ApplePayCustomerStrategy from './apple-pay-customer-strategy';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst createApplePayCustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new ApplePayCustomerStrategy(\n createRequestSender({ host: getHost() }),\n paymentIntegrationService,\n new ApplePaySessionFactory(),\n );\n};\n\nexport default toResolvableModule(createApplePayCustomerStrategy, [{ id: 'applepay' }]);\n","import StandardError from './standard-error';\n\n/**\n * This error should be thrown when a payment method experiences some kind of\n * failure (i.e.: its client library returns a rejected promise). And there is\n * no other error type that is more specific than this one.\n */\nexport default class PaymentMethodFailedError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Unable to proceed because the client library of a payment method has thrown an unexpected error.',\n );\n\n this.name = 'PaymentMethodFailedError';\n this.type = 'payment_method_client_invalid';\n }\n}\n","import StandardError from './standard-error';\n\nexport enum NotInitializedErrorType {\n CheckoutButtonNotInitialized,\n CustomerNotInitialized,\n PaymentNotInitialized,\n ShippingNotInitialized,\n SpamProtectionNotInitialized,\n}\n\n/**\n * Throw this error if a method requires a certain initialization call to be\n * made first. Some objects can be constructed but they cannot be used until a\n * separate initialization call is made.\n */\nexport default class NotInitializedError extends StandardError {\n constructor(public subtype: NotInitializedErrorType) {\n super(getErrorMessage(subtype));\n\n this.name = 'NotInitializedError';\n this.type = 'not_initialized';\n }\n}\n\nfunction getErrorMessage(type: NotInitializedErrorType): string {\n switch (type) {\n case NotInitializedErrorType.CustomerNotInitialized:\n return 'Unable to proceed because the customer step of checkout has not been initialized.';\n\n case NotInitializedErrorType.PaymentNotInitialized:\n return 'Unable to proceed because the payment step of checkout has not been initialized.';\n\n case NotInitializedErrorType.ShippingNotInitialized:\n return 'Unable to proceed because the shipping step of checkout has not been initialized.';\n\n case NotInitializedErrorType.SpamProtectionNotInitialized:\n return 'Unable to proceed because the checkout spam protection has not been initialized.';\n\n default:\n return 'Unable to proceed because the required component has not been initialized.';\n }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport StandardError from './standard-error';\n\nconst DEFAULT_RESPONSE = {\n body: {},\n headers: {},\n status: 0,\n};\n\n/**\n * Throw this error if we are unable to make a request to the server. It wraps\n * any server response into a JS error object.\n */\nexport default class RequestError extends StandardError {\n body: TBody | {};\n headers: { [key: string]: any };\n errors: Array<{ code: string; message?: string }>;\n status: number;\n\n constructor(\n response?: Response,\n {\n message,\n errors,\n }: {\n message?: string;\n errors?: Array<{ code: string; message?: string }>;\n } = {},\n ) {\n const { body, headers, status } = response || DEFAULT_RESPONSE;\n\n super(message || 'An unexpected error has occurred.');\n\n this.name = 'RequestError';\n this.type = 'request';\n this.body = body;\n this.headers = headers;\n this.status = status;\n this.errors = errors || [];\n }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport RequestError from './request-error';\n\n/**\n * Throw this error if we are unable to successfully submit a server request\n * using a payment method because the method has invalid configuration or is in\n * an invalid state.\n */\nexport default class PaymentMethodInvalidError extends RequestError {\n constructor(response?: Response) {\n super(response, {\n message: 'There is a problem processing your payment. Please try again later.',\n });\n\n this.name = 'PaymentMethodInvalidError';\n this.type = 'payment_method_invalid';\n }\n}\n","import { noop } from 'rxjs';\n\nimport {\n CheckoutPaymentMethodExecutedOptions,\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n isCustomError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodFailedError,\n PaymentMethodInvalidError,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BoltCheckout, BoltHostWindow, BoltInitializationData } from './bolt';\nimport { WithBoltCustomerInitializeOptions } from './bolt-customer-initialize-options';\nimport BoltScriptLoader from './bolt-script-loader';\n\nexport default class BoltCustomerStrategy implements CustomerStrategy {\n private boltHostWindow: BoltHostWindow = window;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private boltScriptLoader: BoltScriptLoader,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithBoltCustomerInitializeOptions,\n ): Promise {\n const { methodId, bolt } = options;\n const { onInit } = bolt || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const paymentMethod: PaymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId);\n\n if (!paymentMethod.initializationData?.publishableKey) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { developerConfig, publishableKey } = paymentMethod.initializationData;\n\n await this.boltScriptLoader.loadBoltClient(\n publishableKey,\n paymentMethod.config.testMode,\n developerConfig,\n );\n\n if (onInit && typeof onInit === 'function') {\n const email = this.getCustomerEmail();\n const hasBoltAccount = await this.hasBoltAccount(email);\n\n onInit(hasBoltAccount, email);\n }\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n\n return Promise.resolve();\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n\n return Promise.resolve();\n }\n\n async executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n const {\n continueWithCheckoutCallback = noop,\n checkoutPaymentMethodExecuted,\n methodId,\n } = options || {};\n const email = this.getCustomerEmail();\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n if (typeof continueWithCheckoutCallback !== 'function') {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"continueWithCheckoutCallback\" argument is not provided and it must be a function.',\n );\n }\n\n if (!email) {\n continueWithCheckoutCallback();\n\n return;\n }\n\n return this.openBoltCheckoutModalOrThrow(\n email,\n methodId,\n continueWithCheckoutCallback,\n checkoutPaymentMethodExecuted,\n );\n }\n\n private async openBoltCheckoutModalOrThrow(\n email: string,\n methodId: string,\n continueWithCheckoutCallback: () => void,\n checkoutPaymentMethodExecuted?: (payload: CheckoutPaymentMethodExecutedOptions) => void,\n ): Promise {\n const boltClient = this.getBoltClientOrThrow();\n const paymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethod(methodId);\n\n try {\n if (paymentMethod?.initializationData?.embeddedOneClickEnabled) {\n const hasBoltAccount = await this.hasBoltAccount(email);\n\n if (hasBoltAccount) {\n const callbacks = {\n close: () => {\n continueWithCheckoutCallback();\n },\n };\n\n await boltClient.openCheckout(email, callbacks);\n } else {\n continueWithCheckoutCallback();\n }\n\n if (typeof checkoutPaymentMethodExecuted === 'function') {\n checkoutPaymentMethodExecuted({ hasBoltAccount });\n }\n } else {\n continueWithCheckoutCallback();\n }\n } catch (error) {\n if (\n isCustomError(error) &&\n error.name !== 'MissingDataError' &&\n error.name !== 'NotInitializedError'\n ) {\n throw new PaymentMethodFailedError(error.message);\n }\n\n throw error;\n }\n }\n\n private getBoltClientOrThrow(): BoltCheckout {\n const boltClient = this.boltHostWindow.BoltCheckout;\n\n if (!boltClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return boltClient;\n }\n\n private async hasBoltAccount(email: string) {\n const boltClient = this.getBoltClientOrThrow();\n\n try {\n return await boltClient.hasBoltAccount(email);\n } catch {\n throw new PaymentMethodInvalidError();\n }\n }\n\n private getCustomerEmail() {\n const state = this.paymentIntegrationService.getState();\n const customer = state.getCustomer();\n const billingAddress = state.getBillingAddress();\n\n return customer?.email || billingAddress?.email || '';\n }\n}\n","export default interface CustomError extends Error {\n message: string;\n type: string;\n subtype?: string;\n}\n\nexport function isCustomError(error: any): error is CustomError {\n return (\n typeof error.message === 'string' &&\n typeof error.type === 'string' &&\n (typeof error.subtype === 'string' || !error.subtype) &&\n error instanceof Error\n );\n}\n","import StandardError from './standard-error';\n\n/**\n * This error should be thrown when the client library of a payment method fails\n * to load, or for some reason, it is inaccessible.\n */\nexport default class PaymentMethodClientUnavailableError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Unable to proceed because the client library of a payment method is not loaded or ready to be used.',\n );\n\n this.name = 'PaymentMethodClientUnavailableError';\n this.type = 'payment_method_client_unavailable';\n }\n}\n","import {\n BuyNowCartRequestBody,\n NonceInstrument,\n PaymentMethod,\n WithAccountCreation,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport interface BoltHostWindow extends Window {\n BoltCheckout?: BoltCheckout;\n BoltConnect?: BoltConnect;\n Bolt?(publicKey: string): BoltEmbedded;\n}\n\nexport interface BoltCheckout {\n configure(cart: BoltCart, hints: Record, callbacks?: BoltCallbacks): BoltClient;\n hasBoltAccount(email: string): Promise;\n getTransactionReference(): Promise;\n openCheckout(email: string, callbacks?: BoltOpenCheckoutCallbacks): Promise;\n setClientCustomCallbacks(callbacks: BoltCallbacks): void;\n setOrderId(orderId: number): Promise;\n}\n\nexport interface BoltConnect {\n setupProductPageCheckout?(): void;\n}\n\nexport interface BoltOpenCheckoutCallbacks {\n close?(): void;\n}\n\nexport interface BoltEmbeddedOptions {\n styles: { backgroundColor: string };\n renderSeparateFields?: boolean;\n}\n\nexport interface BoltEmbedded {\n create(name: string, options?: BoltEmbeddedOptions): BoltEmbededField;\n}\n\nexport interface BoltEmbededField {\n mount(element: string): void;\n unmount(): void;\n tokenize(): Promise;\n}\n\nexport interface BoltDeveloperModeParams {\n developerMode: BoltDeveloperMode;\n developerDomain: string;\n}\n\nexport enum BoltDeveloperMode {\n SandboxMode = 'bolt_sandbox',\n StagingMode = 'bolt_staging',\n DevelopmentMode = 'bolt_development',\n}\n\nexport interface BoltClient {\n open(): void;\n}\n\nexport interface BoltCart {\n orderToken: string;\n}\n\nexport interface BoltCallbacks {\n check?(): boolean;\n onCheckoutStart?(): void;\n onPaymentSubmit?(): void;\n success(transaction: BoltTransaction, callback: () => void): void;\n close?(): void;\n}\n\nexport interface BoltTransaction {\n id: string;\n type: string;\n processor: string;\n date: number;\n reference: string;\n status: string;\n authorization: BoltAuthorization;\n}\n\nexport interface BoltAuthorization {\n status: string;\n reason: string;\n}\n\nexport interface BoltEmbeddedTokenize {\n bin: string;\n expiration: string;\n last4: string;\n postal_code?: string;\n token: string;\n token_type: string;\n}\n\nexport interface BoltPaymentMethod extends PaymentMethod {\n initializationData?: BoltInitializationData;\n}\n\nexport interface BoltInitializationData {\n publishableKey: string;\n developerConfig: BoltDeveloperModeParams;\n embeddedOneClickEnabled: boolean;\n}\n\nexport type BoltPaymentData = WithAccountCreation & NonceInstrument;\n\nexport interface BoltBuyNowInitializeOptions {\n storefrontApiToken?: string;\n getBuyNowCartRequestBody(): BuyNowCartRequestBody;\n}\n\nexport enum StyleButtonSize {\n Small = 'small',\n Medium = 'medium',\n Large = 'large',\n}\n\nexport enum StyleButtonShape {\n Pill = 'pill',\n Rect = 'rect',\n}\n\nexport interface BoltButtonStyleOptions {\n shape?: StyleButtonShape;\n size?: StyleButtonSize;\n}\n","import { LoadScriptOptions, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n InvalidArgumentError,\n PaymentMethodClientUnavailableError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n BoltCheckout,\n BoltDeveloperMode,\n BoltDeveloperModeParams,\n BoltEmbedded,\n BoltHostWindow,\n} from './bolt';\n\nexport default class BoltScriptLoader {\n constructor(\n private scriptLoader: ScriptLoader,\n public boltHostWindow: BoltHostWindow = window,\n ) {}\n\n async loadBoltClient(\n publishableKey?: string,\n testMode?: boolean,\n developerModeParams?: BoltDeveloperModeParams,\n cartId?: string,\n storefrontApiToken?: string,\n ): Promise {\n if (this.boltHostWindow.BoltCheckout) {\n return this.boltHostWindow.BoltCheckout;\n }\n\n if (!publishableKey) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"publishableKey\" argument is not provided.',\n );\n }\n\n await this.scriptLoader.loadScript(\n `//${this.getDomainURL(!!testMode, developerModeParams)}/connect-bigcommerce.js`,\n this.getScriptOptions('bolt-connect', publishableKey, cartId, storefrontApiToken),\n );\n await this.scriptLoader.loadScript(\n `//${this.getDomainURL(!!testMode, developerModeParams)}/track.js`,\n this.getScriptOptions('bolt-track', publishableKey),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!this.boltHostWindow.BoltCheckout) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.boltHostWindow.BoltCheckout;\n }\n\n async loadBoltEmbedded(\n publishableKey: string,\n testMode?: boolean,\n developerModeParams?: BoltDeveloperModeParams,\n ): Promise {\n const options: LoadScriptOptions = {\n async: true,\n attributes: {\n id: 'bolt-embedded',\n },\n };\n\n await this.scriptLoader.loadScript(\n `//${this.getDomainURL(!!testMode, developerModeParams)}/embed.js`,\n options,\n );\n\n if (!this.boltHostWindow.Bolt) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.boltHostWindow.Bolt(publishableKey);\n }\n\n getDomainURL(testMode: boolean, developerModeParams?: BoltDeveloperModeParams): string {\n if (!testMode) {\n return 'connect.bolt.com';\n }\n\n if (developerModeParams) {\n switch (developerModeParams.developerMode) {\n case BoltDeveloperMode.StagingMode:\n return 'connect-staging.bolt.com';\n\n case BoltDeveloperMode.DevelopmentMode:\n return `connect.${developerModeParams.developerDomain}`;\n }\n }\n\n return 'connect-sandbox.bolt.com';\n }\n\n private getScriptOptions(\n id: string,\n publishableKey: string,\n cartId?: string,\n storefrontApiToken?: string,\n ): LoadScriptOptions {\n return {\n async: true,\n attributes: {\n id,\n 'data-publishable-key': publishableKey,\n ...(cartId && { 'data-shopping-cart-id': cartId }),\n ...(storefrontApiToken && { 'data-storefront-api-token': storefrontApiToken }),\n },\n };\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BoltCustomerStrategy from './bolt-customer-strategy';\nimport BoltScriptLoader from './bolt-script-loader';\n\nconst createBoltCustomerStrategy: CustomerStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new BoltCustomerStrategy(\n paymentIntegrationService,\n new BoltScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createBoltCustomerStrategy, [{ id: 'bolt' }]);\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@bigcommerce/form-poster\");","import { PaypalAuthorizeData, PaypalButtonOptions, PaypalButtonRender, PaypalSDK } from './paypal';\nimport {\n BraintreeLocalMethods,\n LocalPaymentInstance,\n} from './braintree-local-payment-methods/braintree-local-methods-options';\n\n/**\n *\n * Constants\n *\n */\nexport enum BraintreeEnv {\n Sandbox = 'sandbox',\n Production = 'production',\n}\n\n/**\n *\n * Common\n *\n */\nexport interface BraintreeModuleCreator<\n TInstance,\n TOptions = BraintreeModuleCreatorConfig,\n TError = BraintreeError,\n> {\n create(\n config: TOptions,\n callback?: (error: TError, instance: TInstance) => void,\n ): Promise;\n}\n\nexport interface BraintreeModuleCreatorConfig {\n client?: BraintreeClient;\n authorization?: string;\n}\n\nexport interface BraintreeModule {\n teardown(): Promise;\n}\n\nexport interface BraintreeSDK {\n client?: BraintreeClientCreator;\n dataCollector?: BraintreeDataCollectorCreator;\n // googlePayment?: GooglePayCreator; // TODO: should be added in future migration\n hostedFields?: BraintreeHostedFieldsCreator;\n paypal?: BraintreePaypalCreator;\n paypalCheckout?: BraintreePaypalCheckoutCreator;\n threeDSecure?: BraintreeThreeDSecureCreator;\n venmo?: BraintreeVenmoCheckoutCreator;\n // visaCheckout?: BraintreeVisaCheckoutCreator; // TODO: should be added in future migration\n usBankAccount?: BraintreeBankAccountCreator;\n localPayment?: BraintreeLocalPayment;\n}\n\nexport interface BraintreeLocalPayment {\n VERSION: string;\n create(\n config: BraintreeLocalPaymentCreateConfig,\n callback: BraintreeLocalPaymentCallback,\n ): BraintreeLocalMethods;\n}\n\nexport type BraintreeLocalPaymentCallback = (\n localPaymentError: string,\n localPaymentInstance: LocalPaymentInstance,\n) => void;\n\nexport interface BraintreeLocalPaymentCreateConfig {\n client: BraintreeClient;\n merchantAccountId: string;\n}\n\nexport interface BraintreeInitializationData {\n intent?: 'authorize' | 'order' | 'sale';\n isCreditEnabled?: boolean;\n}\n\nexport interface BraintreePaypalRequest {\n amount: string | number;\n billingAgreementDescription?: string;\n currency?: string;\n displayName?: string;\n enableShippingAddress: true;\n flow: 'checkout' | 'vault';\n intent?: 'authorize' | 'order' | 'sale';\n landingPageType?: 'login' | 'billing';\n locale?: string;\n offerCredit?: boolean;\n shippingAddressEditable?: boolean;\n shippingAddressOverride?: BraintreeShippingAddressOverride;\n useraction?: 'commit';\n}\n\nexport interface BraintreeShippingAddressOverride {\n line1: string;\n line2?: string;\n city: string;\n state: string;\n postalCode: string;\n countryCode: string;\n phone?: string;\n recipientName?: string;\n}\n\nexport interface BraintreeTokenizePayload {\n nonce: string;\n type: 'PaypalAccount' | 'VenmoAccount';\n details: BraintreeDetails;\n creditFinancingOffered?: {\n totalCost: {\n value: string;\n currency: string;\n };\n term: number;\n monthlyPayment: {\n value: string;\n currency: string;\n };\n totalInsterest: {\n value: string;\n currency: string;\n };\n payerAcceptance: boolean;\n cartAmountImmutable: boolean;\n };\n}\n\nexport interface BraintreeDetails {\n username?: string;\n email?: string;\n payerId?: string;\n firstName?: string;\n lastName?: string;\n countryCode?: string;\n phone?: string;\n shippingAddress?: BraintreeShippingAddress;\n billingAddress?: BraintreeAddress;\n}\n\nexport interface BraintreeAddress {\n line1: string;\n line2: string;\n city: string;\n state: string;\n postalCode: string;\n countryCode: string;\n}\n\nexport interface BraintreeShippingAddress extends BraintreeAddress {\n recipientName: string;\n}\n\nexport interface BraintreeVerifyPayload {\n nonce: string;\n details: {\n cardType: string;\n lastFour: string;\n lastTwo: string;\n };\n description: string;\n liabilityShiftPossible: boolean;\n liabilityShifted: boolean;\n}\n\nexport interface BraintreeError extends Error {\n type: 'CUSTOMER' | 'MERCHANT' | 'NETWORK' | 'INTERNAL' | 'UNKNOWN';\n code: string;\n details?: unknown;\n}\n\n/**\n *\n * Braintree Client\n *\n */\nexport type BraintreeClientCreator = BraintreeModuleCreator;\n\nexport interface BraintreeClient {\n request(payload: BraintreeRequestData): Promise;\n getVersion(): string | void;\n}\n\nexport interface BraintreeRequestData {\n data: {\n creditCard: {\n billingAddress?: {\n countryCodeAlpha2: string;\n locality: string;\n countryName: string;\n postalCode: string;\n streetAddress: string;\n };\n cardholderName: string;\n cvv?: string;\n expirationDate: string;\n number: string;\n options: {\n validate: boolean;\n };\n };\n };\n endpoint: string;\n method: string;\n}\n\nexport interface BraintreeTokenizeResponse {\n creditCards: Array<{ nonce: string }>;\n}\n\n/**\n *\n * Braintree Data Collector\n *\n */\nexport type BraintreeDataCollectorCreator = BraintreeModuleCreator<\n BraintreeDataCollector,\n BraintreeDataCollectorCreatorConfig\n>;\n\nexport interface BraintreeDataCollectorCreatorConfig extends BraintreeModuleCreatorConfig {\n kount?: boolean;\n paypal?: boolean;\n}\n\nexport interface BraintreeDataCollector extends BraintreeModule {\n deviceData?: string;\n}\n\n/**\n *\n * Braintree Google Pay\n *\n */\nexport interface BraintreeGooglePayThreeDSecure {\n verifyCard(options: BraintreeGooglePayThreeDSecureOptions): Promise;\n}\n\nexport interface BraintreeGooglePayThreeDSecureOptions {\n nonce: string;\n amount: number;\n showLoader?: boolean;\n onLookupComplete(data: BraintreeThreeDSecureVerificationData, next: () => void): void;\n}\n\n/**\n *\n * Braintree Hosted Fields\n *\n */\nexport type BraintreeHostedFieldsCreator = BraintreeModuleCreator<\n BraintreeHostedFields,\n BraintreeHostedFieldsCreatorConfig\n>;\n\nexport interface BraintreeHostedFields {\n teardown(): Promise;\n tokenize(\n options?: BraintreeHostedFieldsTokenizeOptions,\n ): Promise;\n on(eventName: string, callback: (event: BraintreeHostedFieldsState) => void): void;\n}\n\nexport interface BraintreeHostedFieldsCreatorConfig extends BraintreeModuleCreatorConfig {\n fields: {\n number?: BraintreeHostedFieldOption;\n expirationDate?: BraintreeHostedFieldOption;\n expirationMonth?: BraintreeHostedFieldOption;\n expirationYear?: BraintreeHostedFieldOption;\n cvv?: BraintreeHostedFieldOption;\n postalCode?: BraintreeHostedFieldOption;\n };\n styles?: {\n input?: { [key: string]: string };\n '.invalid'?: { [key: string]: string };\n '.valid'?: { [key: string]: string };\n ':focus'?: { [key: string]: string };\n };\n}\n\nexport interface BraintreeHostedFieldOption {\n container: string | HTMLElement;\n placeholder?: string;\n type?: string;\n formatInput?: boolean;\n maskInput?: boolean | { character?: string; showLastFour?: string };\n select?: boolean | { options?: string[] };\n maxCardLength?: number;\n maxlength?: number;\n minlength?: number;\n prefill?: string;\n rejectUnsupportedCards?: boolean;\n supportedCardBrands?: { [key: string]: boolean };\n}\n\nexport interface BraintreeHostedFieldsState {\n cards: BraintreeHostedFieldsCard[];\n emittedBy: string;\n fields: {\n number?: BraintreeHostedFieldsFieldData;\n expirationDate?: BraintreeHostedFieldsFieldData;\n expirationMonth?: BraintreeHostedFieldsFieldData;\n expirationYear?: BraintreeHostedFieldsFieldData;\n cvv?: BraintreeHostedFieldsFieldData;\n postalCode?: BraintreeHostedFieldsFieldData;\n };\n}\n\nexport interface BraintreeHostedFieldsCard {\n type: string;\n niceType: string;\n code: { name: string; size: number };\n}\n\nexport interface BraintreeHostedFieldsFieldData {\n container: HTMLElement;\n isFocused: boolean;\n isEmpty: boolean;\n isPotentiallyValid: boolean;\n isValid: boolean;\n}\n\nexport interface BraintreeHostedFieldsTokenizeOptions {\n vault?: boolean;\n fieldsToTokenize?: string[];\n cardholderName?: string;\n billingAddress?: BraintreeBillingAddressRequestData;\n}\n\nexport interface BraintreeHostedFieldsTokenizePayload {\n nonce: string;\n details: {\n bin: string;\n cardType: string;\n expirationMonth: string;\n expirationYear: string;\n lastFour: string;\n lastTwo: string;\n };\n description: string;\n type: string;\n binData: {\n commercial: string;\n countryOfIssuance: string;\n debit: string;\n durbinRegulated: string;\n healthcare: string;\n issuingBank: string;\n payroll: string;\n prepaid: string;\n productId: string;\n };\n}\n\nexport interface BraintreeBillingAddressRequestData {\n postalCode?: string;\n firstName?: string;\n lastName?: string;\n company?: string;\n streetAddress?: string;\n extendedAddress?: string;\n locality?: string;\n region?: string;\n countryCodeNumeric?: string;\n countryCodeAlpha2?: string;\n countryCodeAlpha3?: string;\n countryName?: string;\n}\n\nexport interface BraintreeHostedFormError extends BraintreeError {\n details?: {\n invalidFieldKeys?: string[];\n };\n}\n\n/**\n *\n * Braintree 3D Secure\n *\n */\nexport type BraintreeThreeDSecureCreator = BraintreeModuleCreator<\n BraintreeThreeDSecure,\n BraintreeThreeDSecureCreatorConfig\n>;\n\nexport interface BraintreeThreeDSecure extends BraintreeModule {\n verifyCard(options: BraintreeThreeDSecureOptions): Promise;\n cancelVerifyCard(): Promise;\n}\n\nexport interface BraintreeThreeDSecureCreatorConfig extends BraintreeModuleCreatorConfig {\n version?: number;\n}\n\nexport interface BraintreeThreeDSecureOptions {\n nonce: string;\n amount: number;\n challengeRequested: boolean;\n showLoader?: boolean;\n addFrame(error: Error | undefined, iframe: HTMLIFrameElement): void;\n removeFrame(): void;\n onLookupComplete(data: BraintreeThreeDSecureVerificationData, next: () => void): void;\n}\n\ninterface BraintreeThreeDSecureVerificationData {\n lookup: {\n threeDSecureVersion: string;\n };\n paymentMethod: BraintreeVerifyPayload;\n requiresUserAuthentication: boolean;\n threeDSecureInfo: {\n liabilityShiftPossible: boolean;\n liabilityShifted: boolean;\n };\n}\n\n/**\n *\n * Braintree PayPal\n *\n */\nexport type BraintreePaypalCreator = BraintreeModuleCreator;\n\nexport interface BraintreePaypal {\n closeWindow(): void;\n focusWindow(): void;\n tokenize(options: BraintreePaypalRequest): Promise;\n Buttons?(options: PaypalButtonOptions): PaypalButtonRender;\n}\n\n/**\n *\n * Braintree PayPal Checkout\n *\n */\nexport type BraintreePaypalCheckoutCreator = BraintreeModuleCreator;\n\nexport interface BraintreePaypalCheckout {\n loadPayPalSDK(\n config: BraintreePaypalSdkCreatorConfig,\n callback: (instance: BraintreePaypalCheckout) => void,\n ): void;\n createPayment(options: BraintreePaypalRequest): Promise;\n teardown(): Promise;\n tokenizePayment(options: PaypalAuthorizeData): Promise;\n}\n\nexport interface BraintreePaypalSdkCreatorConfig {\n components?: string;\n currency?: string;\n intent?: string;\n isCreditEnabled?: boolean;\n}\n\n/**\n *\n * Braintree Venmo\n *\n */\nexport type BraintreeVenmoCheckoutCreator = BraintreeModuleCreator<\n BraintreeVenmoCheckout,\n BraintreeVenmoCreatorConfig\n>;\n\nexport interface BraintreeVenmoCheckout extends BraintreeModule {\n tokenize(callback: (error: BraintreeError, payload: BraintreeTokenizePayload) => void): void;\n isBrowserSupported(): boolean;\n}\n\nexport interface BraintreeVenmoCreatorConfig extends BraintreeModuleCreatorConfig {\n allowDesktop: boolean;\n paymentMethodUsage: string;\n}\n\n/**\n *\n * Braintree Visa Checkout\n *\n */\n// TODO: should be added in future migration\n// export type BraintreeVisaCheckoutCreator = BraintreeModuleCreator;\n\n// export interface BraintreeVisaCheckout extends BraintreeModule {\n// tokenize(payment: VisaCheckoutPaymentSuccessPayload): Promise;\n// createInitOptions(options: Partial): VisaCheckoutInitOptions;\n// }\n\n/**\n *\n * Braintree US Bank Account\n *\n */\n\nexport interface BankAccountSuccessPayload {\n accountNumber: string;\n routingNumber: string;\n ownershipType: string;\n accountType: string;\n firstName?: string;\n lastName?: string;\n businessName?: string;\n billingAddress: {\n streetAddress: string;\n extendedAddress: string;\n locality: string;\n region: string;\n postalCode: string;\n };\n}\n\nexport type BraintreeBankAccountCreator = BraintreeModuleCreator;\n\nexport interface BraintreeBankAccount extends BraintreeModule {\n tokenize(payload: {\n bankDetails: BankAccountSuccessPayload;\n mandateText: string;\n }): Promise<{ nonce: string; details: BraintreeDetails }>;\n}\n\n/**\n *\n * Other\n *\n */\nexport interface BraintreeHostWindow extends Window {\n braintree?: BraintreeSDK;\n paypal?: PaypalSDK;\n}\n","import { BraintreeError } from './braintree';\n\nexport default function isBraintreeError(error: unknown): error is BraintreeError {\n return Boolean(\n typeof error === 'object' &&\n error !== null &&\n ('type' in error || 'message' in error || 'code' in error),\n );\n}\n","// the PayPal side of things uses uppercase keys instead of camel case\n\n/**\n *\n * PayPal constants\n *\n */\nexport const PAYPAL_COMPONENTS = ['buttons', 'messages'];\n\nexport enum PaypalButtonStyleLayoutOption {\n HORIZONTAL = 'horizontal',\n VERTICAL = 'vertical',\n}\n\nexport enum PaypalButtonStyleSizeOption {\n SMALL = 'small',\n MEDIUM = 'medium',\n LARGE = 'large',\n RESPONSIVE = 'responsive',\n}\n\nexport enum PaypalButtonStyleColorOption {\n GOLD = 'gold',\n BLUE = 'blue',\n SIlVER = 'silver',\n BLACK = 'black',\n}\n\nexport enum PaypalButtonStyleLabelOption {\n CHECKOUT = 'checkout',\n PAY = 'pay',\n BUYNOW = 'buynow',\n PAYPAL = 'paypal',\n CREDIT = 'credit',\n}\n\nexport enum PaypalButtonStyleShapeOption {\n PILL = 'pill',\n RECT = 'rect',\n}\n\n/**\n *\n * PayPal interfaces\n *\n */\nexport interface PaypalSDK {\n Button: PaypalButton;\n checkout: PaypalExpressCheckout;\n FUNDING: PaypalFundingTypeList;\n Buttons(options: PaypalButtonOptions): PaypalButtonRender;\n Messages(options: MessagingOptions): MessagingRender;\n}\n\nexport interface PaypalButton {\n render(options: PaypalButtonOptions, container: string): void;\n}\n\nexport interface PaypalExpressCheckout {\n initXO(): void;\n startFlow(url: string): void;\n closeFlow(): void;\n setup(merchantId: string, options: PaypalExpressCheckoutOptions): void;\n}\n\nexport interface PaypalExpressCheckoutOptions {\n button: string;\n environment: string;\n}\n\nexport interface MessagingOptions {\n amount: number;\n placement: string;\n}\n\nexport interface MessagingRender {\n render(container: string): void;\n}\n\nexport interface PaypalButtonOptions {\n env?: string;\n commit?: boolean;\n style?: PaypalStyleOptions;\n funding?: PaypalFundingType;\n fundingSource?: string;\n client?: PaypalClientToken;\n payment?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onAuthorize?(data: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n createOrder?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onApprove?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n}\n\nexport interface PaypalStyleOptions {\n layout?: PaypalButtonStyleLayoutOption;\n size?: PaypalButtonStyleSizeOption;\n color?: PaypalButtonStyleColorOption;\n label?: PaypalButtonStyleLabelOption;\n shape?: PaypalButtonStyleShapeOption;\n tagline?: boolean;\n fundingicons?: boolean;\n height?: number;\n}\n\nexport interface PaypalClientToken {\n production?: string;\n sandbox?: string;\n}\n\nexport interface PaypalFundingType {\n allowed?: string[];\n disallowed?: string[];\n}\n\nexport interface PaypalActions {\n payment: PaypalPaymentActions;\n request: PaypalRequestActions;\n}\n\nexport interface PaypalButtonRender {\n render(container: string): void;\n isEligible(): boolean;\n}\n\nexport interface PaypalAuthorizeData {\n payerId: string;\n paymentId?: string;\n billingToken?: string;\n payerID?: string;\n paymentID?: string;\n}\n\nexport interface PaypalFundingTypeList {\n CARD?: string;\n CREDIT?: string;\n PAYPAL?: string;\n PAYLATER?: string;\n}\n\nexport interface PaypalPaymentActions {\n get(id: string): Promise;\n}\n\nexport interface PaypalRequestActions {\n post(url: string, payload?: object, options?: object): Promise<{ id: string }>;\n}\n","import {\n Address,\n LegacyAddress,\n NotInitializedError,\n NotInitializedErrorType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n BraintreeBankAccount,\n BraintreeClient,\n BraintreeDataCollector,\n BraintreeDetails,\n BraintreeEnv,\n BraintreeError,\n BraintreeHostWindow,\n BraintreeModule,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeShippingAddressOverride,\n} from './braintree';\nimport BraintreeScriptLoader from './braintree-script-loader';\nimport isBraintreeError from './is-braintree-error';\nimport { PAYPAL_COMPONENTS } from './paypal';\nimport {\n BraintreeLocalMethods,\n GetLocalPaymentInstance,\n LocalPaymentInstance,\n} from './braintree-local-payment-methods/braintree-local-methods-options';\n\nexport default class BraintreeIntegrationService {\n private client?: Promise;\n private clientToken?: string;\n private dataCollectors: {\n default?: BraintreeDataCollector;\n paypal?: BraintreeDataCollector;\n } = {};\n private paypalCheckout?: BraintreePaypalCheckout;\n private usBankAccount?: Promise;\n private braintreeLocalMethods?: BraintreeLocalMethods;\n\n constructor(\n private braintreeScriptLoader: BraintreeScriptLoader,\n private braintreeHostWindow: BraintreeHostWindow,\n ) {}\n\n initialize(clientToken: string) {\n this.clientToken = clientToken;\n }\n\n async getClient(): Promise {\n if (!this.clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!this.client) {\n const clientCreator = await this.braintreeScriptLoader.loadClient();\n\n this.client = clientCreator.create({ authorization: this.clientToken });\n }\n\n return this.client;\n }\n\n async getPaypalCheckout(\n config: Partial,\n onSuccess: (instance: BraintreePaypalCheckout) => void,\n onError: (error: BraintreeError) => void,\n ): Promise {\n const client = await this.getClient();\n const paypalCheckout = await this.braintreeScriptLoader.loadPaypalCheckout();\n\n const paypalCheckoutConfig = { client };\n const paypalCheckoutCallback = (\n error: BraintreeError | undefined,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n if (error) {\n return onError(error);\n }\n\n const paypalSdkLoadCallback = () => onSuccess(braintreePaypalCheckout);\n const paypalSdkLoadConfig = {\n currency: config.currency,\n ...(config.isCreditEnabled && { 'enable-funding': 'paylater' }),\n components: PAYPAL_COMPONENTS.toString(),\n intent: config.intent,\n };\n\n if (!this.braintreeHostWindow.paypal) {\n braintreePaypalCheckout.loadPayPalSDK(paypalSdkLoadConfig, paypalSdkLoadCallback);\n } else {\n onSuccess(braintreePaypalCheckout);\n }\n };\n\n this.paypalCheckout = await paypalCheckout.create(\n paypalCheckoutConfig,\n paypalCheckoutCallback,\n );\n\n return this.paypalCheckout;\n }\n\n async loadBraintreeLocalMethods(\n getLocalPaymentInstance: GetLocalPaymentInstance,\n merchantAccountId: string,\n ) {\n const client = await this.getClient();\n const braintreeLocalMethods = await this.braintreeScriptLoader.loadBraintreeLocalMethods();\n\n if (!this.braintreeLocalMethods) {\n this.braintreeLocalMethods = braintreeLocalMethods.create(\n {\n client,\n merchantAccountId,\n },\n (localPaymentErr: string, localPaymentInstance: LocalPaymentInstance) => {\n if (localPaymentErr) {\n throw new Error(localPaymentErr);\n }\n getLocalPaymentInstance(localPaymentInstance);\n },\n );\n }\n\n return this.braintreeLocalMethods;\n }\n\n async getUsBankAccount() {\n if (!this.usBankAccount) {\n const client = await this.getClient();\n const usBankAccount = await this.braintreeScriptLoader.loadUsBankAccount();\n\n this.usBankAccount = usBankAccount.create({ client });\n }\n\n return this.usBankAccount;\n }\n\n async getDataCollector(options?: { paypal: boolean }): Promise {\n const cacheKey = options?.paypal ? 'paypal' : 'default';\n let cached = this.dataCollectors[cacheKey];\n\n if (!cached) {\n try {\n const client = await this.getClient();\n const dataCollector = await this.braintreeScriptLoader.loadDataCollector();\n\n cached = await dataCollector.create({ client, kount: true, ...options });\n } catch (error) {\n if (isBraintreeError(error) && error.code === 'DATA_COLLECTOR_KOUNT_NOT_ENABLED') {\n cached = {\n deviceData: undefined,\n teardown: () => Promise.resolve(),\n };\n } else {\n throw error;\n }\n }\n\n this.dataCollectors[cacheKey] = cached;\n }\n\n return cached;\n }\n\n getBraintreeEnv(isTestMode = false): BraintreeEnv {\n return isTestMode ? BraintreeEnv.Sandbox : BraintreeEnv.Production;\n }\n\n mapToBraintreeShippingAddressOverride(address: Address): BraintreeShippingAddressOverride {\n return {\n recipientName: `${address.firstName} ${address.lastName}`,\n line1: address.address1,\n line2: address.address2,\n city: address.city,\n state: address.stateOrProvinceCode,\n postalCode: address.postalCode,\n countryCode: address.countryCode,\n phone: address.phone,\n };\n }\n\n mapToLegacyShippingAddress(details: BraintreeDetails): Partial {\n const { email, phone, shippingAddress } = details;\n const recipientName = shippingAddress?.recipientName || '';\n const [firstName, lastName] = recipientName.split(' ');\n\n return {\n email,\n first_name: firstName || '',\n last_name: lastName || '',\n phone_number: phone,\n address_line_1: shippingAddress?.line1,\n address_line_2: shippingAddress?.line2,\n city: shippingAddress?.city,\n state: shippingAddress?.state,\n country_code: shippingAddress?.countryCode,\n postal_code: shippingAddress?.postalCode,\n };\n }\n\n mapToLegacyBillingAddress(details: BraintreeDetails): Partial {\n const { billingAddress, email, firstName, lastName, phone, shippingAddress } = details;\n\n const address = billingAddress || shippingAddress;\n\n return {\n email,\n first_name: firstName,\n last_name: lastName,\n phone_number: phone,\n address_line_1: address?.line1,\n address_line_2: address?.line2,\n city: address?.city,\n state: address?.state,\n country_code: address?.countryCode,\n postal_code: address?.postalCode,\n };\n }\n\n removeElement(elementId?: string): void {\n const element = elementId && document.getElementById(elementId);\n\n if (element) {\n element.remove();\n }\n }\n\n async getSessionId(): Promise {\n const { deviceData } = await this.getDataCollector();\n\n return deviceData;\n }\n\n async teardown(): Promise {\n await this.teardownModule(this.dataCollectors.default);\n await this.teardownModule(this.dataCollectors.paypal);\n this.dataCollectors = {};\n\n await this.teardownModule(this.paypalCheckout);\n this.paypalCheckout = undefined;\n\n // TODO: should be added in future migrations\n\n // await this.teardownModule(this._3ds);\n // this._3ds = undefined;\n\n // await this.teardownModule(this._googlePay);\n // this._googlePay = undefined;\n\n // await this.teardownModule(this._venmoCheckout);\n // this._venmoCheckout = undefined;\n\n // await this.teardownModule(this._visaCheckout);\n // this._visaCheckout = undefined;\n }\n\n private teardownModule(module?: BraintreeModule) {\n return module ? module.teardown() : Promise.resolve();\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n BraintreeBankAccountCreator,\n BraintreeClientCreator,\n BraintreeDataCollectorCreator,\n BraintreeHostWindow,\n BraintreePaypalCheckoutCreator,\n} from './braintree';\n\nconst VERSION = '3.81.0';\n\nexport default class BraintreeScriptLoader {\n constructor(\n private scriptLoader: ScriptLoader,\n private braintreeHostWindow: BraintreeHostWindow,\n ) {}\n\n async loadClient(): Promise {\n await this.scriptLoader.loadScript(\n `//js.braintreegateway.com/web/${VERSION}/js/client.min.js`,\n );\n\n if (!this.braintreeHostWindow.braintree?.client) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.braintreeHostWindow.braintree.client;\n }\n\n async loadPaypalCheckout(): Promise {\n await this.scriptLoader.loadScript(\n `//js.braintreegateway.com/web/${VERSION}/js/paypal-checkout.min.js`,\n );\n\n if (!this.braintreeHostWindow.braintree?.paypalCheckout) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.braintreeHostWindow.braintree.paypalCheckout;\n }\n\n async loadBraintreeLocalMethods() {\n await this.scriptLoader.loadScript(\n `//js.braintreegateway.com/web/${VERSION}/js/local-payment.min.js`,\n );\n\n if (!this.braintreeHostWindow.braintree?.localPayment) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.braintreeHostWindow.braintree.localPayment;\n }\n\n async loadDataCollector(): Promise {\n await this.scriptLoader.loadScript(\n `//js.braintreegateway.com/web/${VERSION}/js/data-collector.min.js`,\n );\n\n if (!this.braintreeHostWindow.braintree?.dataCollector) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.braintreeHostWindow.braintree.dataCollector;\n }\n\n async loadUsBankAccount(): Promise {\n await this.scriptLoader.loadScript(\n `//js.braintreegateway.com/web/${VERSION}/js/us-bank-account.min.js`,\n );\n\n if (\n !this.braintreeHostWindow.braintree ||\n !this.braintreeHostWindow.braintree.usBankAccount\n ) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.braintreeHostWindow.braintree.usBankAccount;\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethod,\n RequestOptions,\n StandardError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n BraintreeError,\n BraintreeHostWindow,\n BraintreeInitializationData,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeTokenizePayload,\n} from '../braintree';\nimport BraintreeIntegrationService from '../braintree-integration-service';\nimport isBraintreeError from '../is-braintree-error';\nimport { PaypalAuthorizeData } from '../paypal';\n\nimport BraintreePaypalCustomerInitializeOptions, {\n WithBraintreePaypalCustomerInitializeOptions,\n} from './braintree-paypal-customer-options';\n\nexport default class BraintreePaypalCustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private formPoster: FormPoster,\n private braintreeIntegrationService: BraintreeIntegrationService,\n private braintreeHostWindow: BraintreeHostWindow,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithBraintreePaypalCustomerInitializeOptions,\n ): Promise {\n const { braintreepaypal, methodId } = options;\n const { container, buttonHeight, onError } = braintreepaypal || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!braintreepaypal) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypal\" argument is not provided.`,\n );\n }\n\n if (!container) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypal.container\" argument is not provided.`,\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod: PaymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const currencyCode = state.getCartOrThrow().currency.code;\n const paypalCheckoutOptions: Partial = {\n currency: currencyCode,\n intent: paymentMethod.initializationData?.intent,\n isCreditEnabled: paymentMethod.initializationData?.isCreditEnabled,\n };\n\n const paypalCheckoutSuccessCallback = (\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n this.renderPayPalButton(\n braintreePaypalCheckout,\n braintreepaypal,\n container,\n methodId,\n Boolean(paymentMethod.config.testMode),\n buttonHeight,\n );\n };\n const paypalCheckoutErrorCallback = (error: BraintreeError) =>\n this.handleError(error, container, onError);\n\n this.braintreeIntegrationService.initialize(paymentMethod.clientToken);\n await this.braintreeIntegrationService.getPaypalCheckout(\n paypalCheckoutOptions,\n paypalCheckoutSuccessCallback,\n paypalCheckoutErrorCallback,\n );\n }\n\n async deinitialize(): Promise {\n await this.braintreeIntegrationService.teardown();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n private renderPayPalButton(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypal: BraintreePaypalCustomerInitializeOptions,\n containerId: string,\n methodId: string,\n testMode: boolean,\n buttonHeight = 40,\n ): void {\n const { paypal } = this.braintreeHostWindow;\n const fundingSource = paypal?.FUNDING.PAYPAL;\n\n if (paypal && fundingSource) {\n const paypalButtonRender = paypal.Buttons({\n env: this.braintreeIntegrationService.getBraintreeEnv(testMode),\n commit: false,\n fundingSource,\n style: {\n height: buttonHeight,\n },\n createOrder: () =>\n this.setupPayment(braintreePaypalCheckout, braintreepaypal, methodId),\n onApprove: (authorizeData: PaypalAuthorizeData) =>\n this.tokenizePayment(\n authorizeData,\n braintreePaypalCheckout,\n methodId,\n braintreepaypal,\n ),\n });\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${containerId}`);\n }\n } else {\n this.braintreeIntegrationService.removeElement(containerId);\n }\n }\n\n private async setupPayment(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypal: BraintreePaypalCustomerInitializeOptions,\n methodId: string,\n ): Promise {\n try {\n await this.paymentIntegrationService.loadDefaultCheckout();\n\n const state = this.paymentIntegrationService.getState();\n const amount = state.getCheckoutOrThrow().outstandingBalance;\n const currency = state.getCartOrThrow().currency.code;\n const customer = state.getCustomer();\n const paymentMethod: PaymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const address = customer?.addresses[0];\n const shippingAddressOverride = address\n ? this.braintreeIntegrationService.mapToBraintreeShippingAddressOverride(address)\n : undefined;\n\n return await braintreePaypalCheckout.createPayment({\n flow: 'checkout',\n enableShippingAddress: true,\n shippingAddressEditable: false,\n shippingAddressOverride,\n amount,\n currency,\n offerCredit: false,\n intent: paymentMethod.initializationData?.intent,\n });\n } catch (error) {\n const { container, onError } = braintreepaypal;\n\n this.handleError(error, container, onError);\n }\n }\n\n private async tokenizePayment(\n authorizeData: PaypalAuthorizeData,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n methodId: string,\n braintreepaypal: BraintreePaypalCustomerInitializeOptions,\n ): Promise {\n try {\n const { deviceData } = await this.braintreeIntegrationService.getDataCollector({\n paypal: true,\n });\n const tokenizePayload = await braintreePaypalCheckout.tokenizePayment(authorizeData);\n const { details, nonce } = tokenizePayload;\n const billingAddress =\n this.braintreeIntegrationService.mapToLegacyBillingAddress(details);\n const shippingAddress =\n this.braintreeIntegrationService.mapToLegacyShippingAddress(details);\n\n this.formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n provider: methodId,\n action: 'set_external_checkout',\n nonce,\n device_data: deviceData,\n billing_address: JSON.stringify(billingAddress),\n shipping_address: JSON.stringify(shippingAddress),\n });\n\n return tokenizePayload;\n } catch (error) {\n const { container, onError } = braintreepaypal;\n\n this.handleError(error, container, onError);\n }\n }\n\n private handleError(\n error: unknown,\n buttonContainerId: string,\n onErrorCallback?: (error: BraintreeError | StandardError) => void,\n ): void {\n this.braintreeIntegrationService.removeElement(buttonContainerId);\n\n if (onErrorCallback && isBraintreeError(error)) {\n onErrorCallback(error);\n } else {\n throw error;\n }\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BraintreeHostWindow } from '../braintree';\nimport BraintreeIntegrationService from '../braintree-integration-service';\nimport BraintreeScriptLoader from '../braintree-script-loader';\n\nimport BraintreePaypalCustomerStrategy from './braintree-paypal-customer-strategy';\n\nconst createBraintreePaypalCustomerStrategy: CustomerStrategyFactory<\n BraintreePaypalCustomerStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n braintreeHostWindow,\n );\n\n return new BraintreePaypalCustomerStrategy(\n paymentIntegrationService,\n createFormPoster(),\n braintreeIntegrationService,\n braintreeHostWindow,\n );\n};\n\nexport default toResolvableModule(createBraintreePaypalCustomerStrategy, [\n { id: 'braintreepaypal' },\n]);\n","import StandardError from './standard-error';\n\n/**\n * This error should be thrown when a shopper tries to sign in as a guest but\n * they are already signed in as a registered customer.\n */\nexport default class BuyNowCartCreationError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'An unexpected error has occurred during buy now cart creation process. Please try again later.',\n );\n\n this.name = 'BuyNowCartCreationError';\n this.type = 'buy_now_cart_creation_error';\n }\n}\n","export enum CartSource {\n BuyNow = 'BUY_NOW',\n}\n","import {\n BuyNowCartRequestBody,\n HostedInstrument,\n ShippingOption,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\n/**\n *\n * PayPal Commerce Funding sources\n *\n */\nexport type FundingType = string[];\nexport type EnableFundingType = FundingType | string;\n\nexport interface PayPalCommerceSDKFunding {\n CARD: string;\n PAYPAL: string;\n CREDIT: string;\n PAYLATER: string;\n OXXO: string;\n SEPA: string;\n VENMO: string;\n}\n\n/**\n *\n * PayPal Commerce SDK\n *\n */\nexport interface PayPalSDK {\n FUNDING: PayPalCommerceSDKFunding;\n HostedFields: {\n isEligible(): boolean;\n render(data: PayPalCommerceHostedFieldsRenderOptions): Promise;\n };\n Buttons(options: PayPalCommerceButtonsOptions): PayPalCommerceButtons;\n PaymentFields(options: PayPalCommercePaymentFieldsOptions): PayPalCommercePaymentFields;\n Messages(options: PayPalCommerceMessagesOptions): PayPalCommerceMessages;\n}\n\nexport interface PayPalCommerceScriptParams {\n 'client-id'?: string;\n 'merchant-id'?: string;\n 'buyer-country'?: string;\n 'disable-funding'?: FundingType;\n 'enable-funding'?: EnableFundingType;\n 'data-client-token'?: string;\n 'data-partner-attribution-id'?: string;\n currency?: string;\n commit?: boolean;\n intent?: PayPalCommerceIntent;\n components?: ComponentsScriptType;\n}\n\nexport enum PayPalCommerceIntent {\n AUTHORIZE = 'authorize',\n CAPTURE = 'capture',\n}\n\nexport type ComponentsScriptType = Array<\n 'buttons' | 'funding-eligibility' | 'hosted-fields' | 'messages' | 'payment-fields'\n>;\n\nexport interface PayPalCommerceHostWindow extends Window {\n paypal?: PayPalSDK;\n paypalLoadScript?(options: PayPalCommerceScriptParams): Promise<{ paypal: PayPalSDK }>;\n}\n\n/**\n *\n * PayPal Commerce Initialization Data\n *\n */\nexport interface PayPalCommerceInitializationData {\n attributionId?: string;\n availableAlternativePaymentMethods: FundingType;\n buttonStyle?: PayPalButtonStyleOptions;\n buyerCountry?: string;\n clientId: string;\n clientToken?: string;\n enabledAlternativePaymentMethods: FundingType;\n isDeveloperModeApplicable?: boolean;\n intent?: PayPalCommerceIntent;\n isHostedCheckoutEnabled?: boolean;\n isPayPalCreditAvailable?: boolean;\n isVenmoEnabled?: boolean;\n merchantId?: string;\n orderId?: string;\n shouldRenderFields?: boolean;\n}\n\n/**\n *\n * PayPal Commerce BuyNow\n *\n */\nexport interface PayPalBuyNowInitializeOptions {\n getBuyNowCartRequestBody(): BuyNowCartRequestBody;\n}\n\n/**\n *\n * PayPal Commerce Hosted Fields\n *\n */\nexport interface PayPalCommerceHostedFieldsRenderOptions {\n fields?: {\n number?: PayPalCommerceHostedFieldOption;\n cvv?: PayPalCommerceHostedFieldOption;\n expirationDate?: PayPalCommerceHostedFieldOption;\n };\n paymentsSDK?: boolean;\n styles?: {\n input?: { [key: string]: string };\n '.invalid'?: { [key: string]: string };\n '.valid'?: { [key: string]: string };\n ':focus'?: { [key: string]: string };\n };\n createOrder(): Promise;\n}\n\nexport interface PayPalCommerceHostedFieldOption {\n selector: string;\n placeholder?: string;\n}\n\nexport interface PayPalCommerceHostedFields {\n submit(\n options?: PayPalCommerceHostedFieldsSubmitOptions,\n ): Promise;\n getState(): PayPalCommerceHostedFieldsState;\n on(eventName: string, callback: (event: PayPalCommerceHostedFieldsState) => void): void;\n}\n\nexport interface PayPalCommerceHostedFieldsSubmitOptions {\n contingencies?: Array<'3D_SECURE'>;\n cardholderName?: string;\n}\n\nexport interface PayPalCommerceHostedFieldsApprove {\n orderId: string;\n liabilityShift?: 'POSSIBLE' | 'NO' | 'UNKNOWN';\n}\n\nexport interface PayPalCommerceHostedFieldsState {\n cards: PayPalCommerceHostedFieldsCard[];\n emittedBy: string;\n fields: {\n number?: PayPalCommerceHostedFieldsFieldData;\n expirationDate?: PayPalCommerceHostedFieldsFieldData;\n expirationMonth?: PayPalCommerceHostedFieldsFieldData;\n expirationYear?: PayPalCommerceHostedFieldsFieldData;\n cvv?: PayPalCommerceHostedFieldsFieldData;\n postalCode?: PayPalCommerceHostedFieldsFieldData;\n };\n}\n\nexport interface PayPalCommerceHostedFieldsCard {\n type: string;\n niceType: string;\n code: {\n name: string;\n size: number;\n };\n}\n\nexport interface PayPalCommerceHostedFieldsFieldData {\n container: HTMLElement;\n isFocused: boolean;\n isEmpty: boolean;\n isPotentiallyValid: boolean;\n isValid: boolean;\n}\n\n/**\n *\n * PayPal Commerce Buttons\n *\n */\nexport interface PayPalCommerceButtons {\n render(id: string): void;\n close(): void;\n isEligible(): boolean;\n}\n\nexport interface PayPalCommerceButtonsOptions {\n experience?: string;\n style?: PayPalButtonStyleOptions;\n fundingSource: string;\n createOrder(): Promise;\n onApprove(\n data: ApproveCallbackPayload,\n actions: ApproveCallbackActions,\n ): Promise | void;\n onComplete?(data: CompleteCallbackDataPayload): Promise;\n onClick?(data: ClickCallbackPayload, actions: ClickCallbackActions): Promise;\n onError?(error: Error): void;\n onCancel?(): void;\n onShippingAddressChange?(data: ShippingAddressChangeCallbackPayload): Promise;\n onShippingOptionsChange?(data: ShippingOptionChangeCallbackPayload): Promise;\n}\n\nexport interface ClickCallbackPayload {\n fundingSource: string;\n}\n\nexport interface ClickCallbackActions {\n reject(): void;\n resolve(): void;\n}\n\nexport interface ShippingAddressChangeCallbackPayload {\n orderId: string;\n shippingAddress: PayPalAddress;\n}\n\nexport interface PayPalAddress {\n city: string;\n country_code: string;\n postal_code: string;\n state: string;\n}\n\nexport interface ShippingOptionChangeCallbackPayload {\n orderId: string;\n selectedShippingOption: PayPalSelectedShippingOption;\n}\n\nexport interface PayPalSelectedShippingOption {\n amount: {\n currency_code: string;\n value: string;\n };\n id: string;\n label: string;\n selected: boolean;\n type: string;\n}\n\nexport interface ApproveCallbackPayload {\n orderID?: string;\n}\n\nexport interface ApproveCallbackActions {\n order: {\n get: () => Promise;\n };\n}\n\nexport interface PayPalOrderDetails {\n payer: {\n name: {\n given_name: string;\n surname: string;\n };\n email_address: string;\n address: PayPalOrderAddress;\n };\n purchase_units: Array<{\n shipping: {\n address: PayPalOrderAddress;\n };\n }>;\n}\n\nexport interface PayPalOrderAddress {\n address_line_1: string;\n admin_area_2: string;\n admin_area_1?: string;\n postal_code: string;\n country_code: string;\n}\n\nexport interface CompleteCallbackDataPayload {\n intent: string;\n orderID: string;\n}\n\nexport enum StyleButtonLabel {\n paypal = 'paypal',\n checkout = 'checkout',\n buynow = 'buynow',\n pay = 'pay',\n installment = 'installment',\n}\n\nexport enum StyleButtonColor {\n gold = 'gold',\n blue = 'blue',\n silver = 'silver',\n black = 'black',\n white = 'white',\n}\n\nexport enum StyleButtonShape {\n pill = 'pill',\n rect = 'rect',\n}\n\nexport interface PayPalButtonStyleOptions {\n color?: StyleButtonColor;\n shape?: StyleButtonShape;\n height?: number;\n label?: StyleButtonLabel;\n}\n\n/**\n *\n * PayPal Commerce Payment fields\n *\n */\nexport interface PayPalCommercePaymentFields {\n render(id: string): void;\n}\n\nexport interface PayPalCommercePaymentFieldsOptions {\n style?: PayPalCommerceFieldsStyleOptions;\n fundingSource: string;\n fields: {\n name?: {\n value?: string;\n };\n email?: {\n value?: string;\n };\n };\n}\n\nexport interface PayPalCommerceFieldsStyleOptions {\n variables?: {\n fontFamily?: string;\n fontSizeBase?: string;\n fontSizeSm?: string;\n fontSizeM?: string;\n fontSizeLg?: string;\n textColor?: string;\n colorTextPlaceholder?: string;\n colorBackground?: string;\n colorInfo?: string;\n colorDanger?: string;\n borderRadius?: string;\n borderColor?: string;\n borderWidth?: string;\n borderFocusColor?: string;\n spacingUnit?: string;\n };\n rules?: {\n [key: string]: any;\n };\n}\n\n/**\n *\n * PayPalCommerce Messages\n *\n */\nexport interface PayPalCommerceMessages {\n render(id: string): void;\n}\n\nexport interface PayPalCommerceMessagesOptions {\n amount: number;\n placement: string;\n style?: PayPalCommerceMessagesStyleOptions;\n fundingSource?: string;\n}\n\nexport interface PayPalCommerceMessagesStyleOptions {\n layout?: string;\n}\n\n/**\n *\n * Other\n *\n */\nexport enum NonInstantAlternativePaymentMethods {\n OXXO = 'oxxo',\n}\n\nexport interface PayPalOrderData {\n orderId: string;\n approveUrl: string;\n}\n\nexport interface PayPalUpdateOrderRequestBody {\n availableShippingOptions?: ShippingOption[];\n cartId: string;\n selectedShippingOption?: ShippingOption;\n}\n\nexport interface PayPalCreateOrderRequestBody extends HostedInstrument, VaultedInstrument {\n cartId: string;\n}\n\nexport enum PayPalOrderStatus {\n Approved = 'APPROVED',\n Created = 'CREATED',\n PayerActionRequired = 'PAYER_ACTION_REQUIRED',\n}\n\nexport interface PayPalOrderStatusData {\n status: PayPalOrderStatus;\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { isNil, omitBy } from 'lodash';\n\nimport {\n BillingAddressRequestBody,\n BuyNowCartCreationError,\n Cart,\n CartSource,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n PaymentMethodClientUnavailableError,\n RequestError,\n ShippingOption,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceRequestSender from './paypal-commerce-request-sender';\nimport PayPalCommerceScriptLoader from './paypal-commerce-script-loader';\nimport {\n PayPalButtonStyleOptions,\n PayPalBuyNowInitializeOptions,\n PayPalCommerceInitializationData,\n PayPalCreateOrderRequestBody,\n PayPalOrderDetails,\n PayPalOrderStatus,\n PayPalSDK,\n StyleButtonColor,\n StyleButtonLabel,\n StyleButtonShape,\n} from './paypal-commerce-types';\n\nexport default class PayPalCommerceIntegrationService {\n private paypalSdk?: PayPalSDK;\n\n constructor(\n private formPoster: FormPoster,\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceRequestSender: PayPalCommerceRequestSender,\n private paypalCommerceScriptLoader: PayPalCommerceScriptLoader,\n ) {}\n\n /**\n *\n * PayPalSDK methods\n *\n */\n async loadPayPalSdk(\n methodId: string,\n providedCurrencyCode?: string,\n initializesOnCheckoutPage?: boolean,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n const currencyCode = providedCurrencyCode || state.getCartOrThrow().currency.code;\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n this.paypalSdk = await this.paypalCommerceScriptLoader.getPayPalSDK(\n paymentMethod,\n currencyCode,\n initializesOnCheckoutPage,\n );\n\n return this.paypalSdk;\n }\n\n getPayPalSdkOrThrow(): PayPalSDK {\n if (!this.paypalSdk) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.paypalSdk;\n }\n\n /**\n *\n * Buy Now cart creation methods\n *\n */\n async createBuyNowCartOrThrow(\n buyNowInitializeOptions: PayPalBuyNowInitializeOptions,\n ): Promise {\n const cartRequestBody = buyNowInitializeOptions.getBuyNowCartRequestBody();\n\n if (!cartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n return await this.paymentIntegrationService.createBuyNowCart(cartRequestBody);\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n\n /**\n *\n * Order methods\n *\n */\n async createOrder(\n providerId: string,\n requestBody?: Partial,\n ): Promise {\n const cartId = this.paymentIntegrationService.getState().getCartOrThrow().id;\n\n const { orderId } = await this.paypalCommerceRequestSender.createOrder(providerId, {\n cartId,\n ...requestBody,\n });\n\n return orderId;\n }\n\n async updateOrder(): Promise {\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const consignment = state.getConsignmentsOrThrow()[0];\n\n try {\n await this.paypalCommerceRequestSender.updateOrder({\n availableShippingOptions: consignment.availableShippingOptions,\n cartId: cart.id,\n selectedShippingOption: consignment.selectedShippingOption,\n });\n } catch (_error) {\n throw new RequestError();\n }\n }\n\n async getOrderStatus(): Promise {\n try {\n const { status } = await this.paypalCommerceRequestSender.getOrderStatus();\n\n return status;\n } catch (_error) {\n throw new RequestError();\n }\n }\n\n /**\n *\n * Payment submitting and tokenizing methods\n *\n */\n tokenizePayment(methodId: string, orderId?: string): void {\n const cart = this.paymentIntegrationService.getState().getCartOrThrow();\n\n if (!orderId) {\n throw new MissingDataError(MissingDataErrorType.MissingOrderId);\n }\n\n return this.formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n action: 'set_external_checkout',\n provider: methodId,\n order_id: orderId,\n ...(cart.source === CartSource.BuyNow && { cart_id: cart.id }),\n });\n }\n\n async submitPayment(methodId: string, orderId: string): Promise {\n const paymentData = {\n formattedPayload: {\n vault_payment_instrument: null,\n set_as_default_stored_instrument: null,\n device_info: null,\n method_id: methodId,\n paypal_account: {\n order_id: orderId,\n },\n },\n };\n\n await this.paymentIntegrationService.submitPayment({ methodId, paymentData });\n }\n\n /**\n *\n * Shipping options methods\n *\n */\n getShippingOptionOrThrow(selectedShippingOptionId?: string): ShippingOption {\n const state = this.paymentIntegrationService.getState();\n const consignment = state.getConsignmentsOrThrow()[0];\n\n const availableShippingOptions = consignment.availableShippingOptions || [];\n\n const recommendedShippingOption = availableShippingOptions.find(\n (option) => option.isRecommended,\n );\n\n const selectedShippingOption = selectedShippingOptionId\n ? availableShippingOptions.find((option) => option.id === selectedShippingOptionId)\n : availableShippingOptions.find(\n (option) => option.id === consignment.selectedShippingOption?.id,\n );\n\n const shippingOptionToSelect =\n selectedShippingOption || recommendedShippingOption || availableShippingOptions[0];\n\n if (!shippingOptionToSelect) {\n throw new Error(\"Your order can't be shipped to this address\");\n }\n\n return shippingOptionToSelect;\n }\n\n /**\n *\n * Address transforming methods\n *\n */\n getAddress(address?: Partial): BillingAddressRequestBody {\n return {\n firstName: address?.firstName || '',\n lastName: address?.lastName || '',\n email: address?.email || '',\n phone: '',\n company: '',\n address1: address?.address1 || '',\n address2: '',\n city: address?.city || '',\n countryCode: address?.countryCode || '',\n postalCode: address?.postalCode || '',\n stateOrProvince: '',\n stateOrProvinceCode: address?.stateOrProvinceCode || '',\n customFields: [],\n };\n }\n\n getBillingAddressFromOrderDetails({ payer }: PayPalOrderDetails): BillingAddressRequestBody {\n return this.getAddress({\n firstName: payer.name.given_name,\n lastName: payer.name.surname,\n email: payer.email_address,\n address1: payer.address.address_line_1,\n city: payer.address.admin_area_2,\n countryCode: payer.address.country_code,\n postalCode: payer.address.postal_code,\n stateOrProvinceCode: payer.address.admin_area_1,\n });\n }\n\n getShippingAddressFromOrderDetails(\n orderDetails: PayPalOrderDetails,\n ): BillingAddressRequestBody {\n const { payer, purchase_units } = orderDetails;\n const shippingAddress = purchase_units[0]?.shipping?.address || {};\n\n return this.getAddress({\n firstName: payer.name.given_name,\n lastName: payer.name.surname,\n email: payer.email_address,\n address1: shippingAddress.address_line_1,\n city: shippingAddress.admin_area_2,\n countryCode: shippingAddress.country_code,\n postalCode: shippingAddress.postal_code,\n stateOrProvinceCode: shippingAddress.admin_area_1,\n });\n }\n\n /**\n *\n * Buttons style methods\n *\n */\n getValidButtonStyle(style?: PayPalButtonStyleOptions): PayPalButtonStyleOptions {\n const { color, height, label, shape } = style || {};\n\n const validStyles = {\n color: color && StyleButtonColor[color] ? color : undefined,\n height: this.getValidHeight(height),\n label: label && StyleButtonLabel[label] ? label : undefined,\n shape: shape && StyleButtonShape[shape] ? shape : undefined,\n };\n\n return omitBy(validStyles, isNil);\n }\n\n getValidHeight(height?: number): number {\n const defaultHeight = 40;\n const minHeight = 25;\n const maxHeight = 55;\n\n if (!height || typeof height !== 'number') {\n return defaultHeight;\n }\n\n if (height > maxHeight) {\n return maxHeight;\n }\n\n if (height < minHeight) {\n return minHeight;\n }\n\n return height;\n }\n\n /**\n *\n * Utils methods\n *\n */\n removeElement(elementId?: string): void {\n const element = elementId && document.getElementById(elementId);\n\n if (element) {\n element.remove();\n }\n }\n}\n","export const INTERNAL_USE_ONLY =\n 'This API endpoint is for internal use only and may change in the future';\n","enum ContentType {\n Json = 'application/json',\n JsonV1 = 'application/vnd.bc.v1+json',\n}\n\nexport default ContentType;\n","export const SDK_VERSION_HEADERS = { 'X-Checkout-SDK-Version': LIBRARY_VERSION };\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n SDK_VERSION_HEADERS,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n PayPalCreateOrderRequestBody,\n PayPalOrderData,\n PayPalOrderStatusData,\n PayPalUpdateOrderRequestBody,\n} from './paypal-commerce-types';\n\nexport default class PayPalCommerceRequestSender {\n constructor(private requestSender: RequestSender) {}\n\n async createOrder(\n providerId: string,\n requestBody: Partial,\n ): Promise {\n const url = `/api/storefront/payment/${providerId}`;\n const body = requestBody;\n const headers = {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n 'Content-Type': ContentType.Json,\n ...SDK_VERSION_HEADERS,\n };\n\n const res = await this.requestSender.post(url, { headers, body });\n\n return res.body;\n }\n\n // TODO: add response type interface Promise in another task\n async updateOrder(requestBody: PayPalUpdateOrderRequestBody) {\n const url = `/api/storefront/initialization/paypalcommerce`;\n const body = requestBody;\n const headers = {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n 'Content-Type': ContentType.Json,\n ...SDK_VERSION_HEADERS,\n };\n\n const res = await this.requestSender.put(url, { headers, body });\n\n return res.body;\n }\n\n async getOrderStatus(): Promise {\n const url = '/api/storefront/initialization/paypalcommerce';\n const headers = {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n 'Content-Type': ContentType.Json,\n ...SDK_VERSION_HEADERS,\n };\n\n const res = await this.requestSender.get(url, { headers });\n\n return res.body;\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n MissingDataError,\n MissingDataErrorType,\n PaymentMethod,\n PaymentMethodClientUnavailableError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n FundingType,\n PayPalCommerceHostWindow,\n PayPalCommerceInitializationData,\n PayPalCommerceScriptParams,\n PayPalSDK,\n} from './paypal-commerce-types';\n\nconst PAYPAL_SDK_VERSION = '5.0.5';\n\nexport default class PayPalCommerceScriptLoader {\n private window: PayPalCommerceHostWindow;\n private paypalSdk?: PayPalSDK;\n\n constructor(private scriptLoader: ScriptLoader) {\n this.window = window;\n }\n\n async getPayPalSDK(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n initializesOnCheckoutPage?: boolean,\n ): Promise {\n if (!this.paypalSdk) {\n this.paypalSdk = await this.loadPayPalSDK(\n this.getPayPalSdkScriptConfigOrThrow(\n paymentMethod,\n currencyCode,\n initializesOnCheckoutPage,\n ),\n );\n }\n\n return this.paypalSdk;\n }\n\n private async loadPayPalSDK(\n paypalSdkScriptConfig: PayPalCommerceScriptParams,\n ): Promise {\n if (!this.window.paypalLoadScript) {\n const scriptSrc = `https://unpkg.com/@paypal/paypal-js@${PAYPAL_SDK_VERSION}/dist/iife/paypal-js.min.js`;\n\n await this.scriptLoader.loadScript(scriptSrc, { async: true, attributes: {} });\n\n if (!this.window.paypalLoadScript) {\n throw new PaymentMethodClientUnavailableError();\n }\n }\n\n await this.window.paypalLoadScript(paypalSdkScriptConfig);\n\n if (!this.window.paypal) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.paypal;\n }\n\n private getPayPalSdkScriptConfigOrThrow(\n paymentMethod: PaymentMethod,\n currencyCode: string,\n initializesOnCheckoutPage = true,\n ): PayPalCommerceScriptParams {\n const { id, clientToken, initializationData } = paymentMethod;\n\n if (!initializationData?.clientId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n intent,\n clientId,\n merchantId,\n buyerCountry,\n attributionId,\n isVenmoEnabled,\n isHostedCheckoutEnabled,\n isPayPalCreditAvailable,\n isDeveloperModeApplicable,\n availableAlternativePaymentMethods = [],\n enabledAlternativePaymentMethods = [],\n } = initializationData;\n\n const commit = isHostedCheckoutEnabled || initializesOnCheckoutPage;\n\n const shouldEnableCard = id === 'paypalcommercecreditcards';\n const enableCardFunding = shouldEnableCard ? ['card'] : [];\n const disableCardFunding = !shouldEnableCard ? ['card'] : [];\n\n const enableCreditFunding = isPayPalCreditAvailable ? ['credit', 'paylater'] : [];\n const disableCreditFunding = !isPayPalCreditAvailable ? ['credit', 'paylater'] : [];\n\n const shouldEnableAPMs = initializesOnCheckoutPage || !commit;\n const enableVenmoFunding = shouldEnableAPMs && isVenmoEnabled ? ['venmo'] : [];\n const disableVenmoFunding = !shouldEnableAPMs || !isVenmoEnabled ? ['venmo'] : [];\n const enableAPMsFunding = shouldEnableAPMs ? enabledAlternativePaymentMethods : [];\n const disableAPMsFunding = shouldEnableAPMs\n ? availableAlternativePaymentMethods.filter(\n (apm: string) => !enabledAlternativePaymentMethods.includes(apm),\n )\n : availableAlternativePaymentMethods;\n\n const disableFunding: FundingType = [\n ...disableCardFunding,\n ...disableCreditFunding,\n ...disableVenmoFunding,\n ...disableAPMsFunding,\n ];\n const enableFunding: FundingType = [\n ...enableCardFunding,\n ...enableCreditFunding,\n ...enableVenmoFunding,\n ...enableAPMsFunding,\n ];\n\n return {\n 'client-id': clientId,\n 'data-partner-attribution-id': attributionId,\n 'data-client-token': clientToken,\n 'merchant-id': merchantId,\n 'enable-funding': enableFunding.length > 0 ? enableFunding : undefined,\n 'disable-funding': disableFunding.length > 0 ? disableFunding : undefined,\n commit,\n components: ['buttons', 'hosted-fields', 'messages', 'payment-fields'],\n currency: currencyCode,\n intent,\n ...(isDeveloperModeApplicable && { 'buyer-country': buyerCountry }),\n };\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n PayPalCommerceIntegrationService,\n PayPalCommerceRequestSender,\n PayPalCommerceScriptLoader,\n} from './index';\n\nconst createPayPalCommerceIntegrationService = (\n paymentIntegrationService: PaymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new PayPalCommerceIntegrationService(\n createFormPoster(),\n paymentIntegrationService,\n new PayPalCommerceRequestSender(createRequestSender({ host: getHost() })),\n new PayPalCommerceScriptLoader(getScriptLoader()),\n );\n};\n\nexport default createPayPalCommerceIntegrationService;\n","import { noop } from 'lodash';\n\nimport {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceCustomerInitializeOptions, {\n WithPayPalCommerceCustomerInitializeOptions,\n} from './paypal-commerce-customer-initialize-options';\n\nexport default class PayPalCommerceCustomerStrategy implements CustomerStrategy {\n private onError = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithPayPalCommerceCustomerInitializeOptions,\n ): Promise {\n const { paypalcommerce, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!paypalcommerce) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerce\" argument is not provided.`,\n );\n }\n\n if (!paypalcommerce.container) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerce.container\" argument is not provided.`,\n );\n }\n\n this.onError = paypalcommerce.onError || noop;\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.renderButton(methodId, paypalcommerce);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n\n return Promise.resolve();\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n\n return Promise.resolve();\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n private renderButton(\n methodId: string,\n paypalcommerce: PayPalCommerceCustomerInitializeOptions,\n ): void {\n const { container, onComplete } = paypalcommerce;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled } = paymentMethod.initializationData || {};\n\n const defaultCallbacks = {\n createOrder: () => this.paypalCommerceIntegrationService.createOrder('paypalcommerce'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const hostedCheckoutCallbacks = {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(data, actions, methodId, onComplete),\n };\n\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(),\n ...defaultCallbacks,\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n };\n\n const paypalButton = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButton.isEligible()) {\n paypalButton.render(`#${container}`);\n } else {\n this.paypalCommerceIntegrationService.removeElement(container);\n }\n }\n\n private async onHostedCheckoutApprove(\n data: ApproveCallbackPayload,\n actions: ApproveCallbackActions,\n methodId: string,\n onComplete?: () => void,\n ): Promise {\n if (!data.orderID) {\n throw new MissingDataError(MissingDataErrorType.MissingOrderId);\n }\n\n const cart = this.paymentIntegrationService.getState().getCartOrThrow();\n const orderDetails = await actions.order.get();\n\n try {\n const billingAddress =\n this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.paypalCommerceIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.paypalCommerceIntegrationService.submitPayment(methodId, data.orderID);\n\n if (onComplete && typeof onComplete === 'function') {\n onComplete();\n }\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingAddressChange(\n data: ShippingAddressChangeCallbackPayload,\n ): Promise {\n const address = this.paypalCommerceIntegrationService.getAddress({\n city: data.shippingAddress.city,\n countryCode: data.shippingAddress.country_code,\n postalCode: data.shippingAddress.postal_code,\n stateOrProvinceCode: data.shippingAddress.state,\n });\n\n try {\n // Info: we use the same address to fill billing and shipping addresses to have valid quota on BE for order updating process\n // on this stage we don't have access to valid customer's address except shipping data\n await this.paymentIntegrationService.updateBillingAddress(address);\n await this.paymentIntegrationService.updateShippingAddress(address);\n\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n ): Promise {\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private handleError(error: Error) {\n if (typeof this.onError === 'function') {\n this.onError(error);\n } else {\n throw error;\n }\n }\n}\n","import {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceCustomerStrategy from './paypal-commerce-customer-strategy';\n\nconst createPayPalCommerceCustomerStrategy: CustomerStrategyFactory<\n PayPalCommerceCustomerStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCustomerStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceCustomerStrategy, [{ id: 'paypalcommerce' }]);\n","import { noop } from 'lodash';\n\nimport {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n StyleButtonColor,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceCreditCustomerInitializeOptions, {\n WithPayPalCommerceCreditCustomerInitializeOptions,\n} from './paypal-commerce-credit-customer-initialize-options';\n\nexport default class PayPalCommerceCreditCustomerStrategy implements CustomerStrategy {\n private onError = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithPayPalCommerceCreditCustomerInitializeOptions,\n ): Promise {\n const { paypalcommercecredit, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!paypalcommercecredit) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"paypalcommercecredit\" argument is not provided.`,\n );\n }\n\n if (!paypalcommercecredit.container) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"paypalcommercecredit.container\" argument is not provided.`,\n );\n }\n\n this.onError = paypalcommercecredit.onError || noop;\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.renderButton(methodId, paypalcommercecredit);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n private renderButton(\n methodId: string,\n paypalCommerceCredit: PayPalCommerceCreditCustomerInitializeOptions,\n ): void {\n const { container, onComplete } = paypalCommerceCredit;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled } = paymentMethod.initializationData || {};\n\n const defaultCallbacks = {\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder('paypalcommercecredit'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const hostedCheckoutCallbacks = {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(data, actions, methodId, onComplete),\n };\n\n const fundingSources = [paypalSdk.FUNDING.PAYLATER, paypalSdk.FUNDING.CREDIT];\n let hasRenderedSmartButton = false;\n\n fundingSources.forEach((fundingSource) => {\n if (!hasRenderedSmartButton) {\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle({\n color: StyleButtonColor.gold,\n }),\n ...defaultCallbacks,\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n };\n\n const paypalButton = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButton.isEligible()) {\n paypalButton.render(`#${container}`);\n hasRenderedSmartButton = true;\n }\n }\n });\n\n if (!hasRenderedSmartButton) {\n this.paypalCommerceIntegrationService.removeElement(container);\n }\n }\n\n private async onHostedCheckoutApprove(\n data: ApproveCallbackPayload,\n actions: ApproveCallbackActions,\n methodId: string,\n onComplete?: () => void,\n ): Promise {\n if (!data.orderID) {\n throw new MissingDataError(MissingDataErrorType.MissingOrderId);\n }\n\n const cart = this.paymentIntegrationService.getState().getCartOrThrow();\n const orderDetails = await actions.order.get();\n\n try {\n const billingAddress =\n this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.paypalCommerceIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.paypalCommerceIntegrationService.submitPayment(methodId, data.orderID);\n\n if (onComplete && typeof onComplete === 'function') {\n onComplete();\n }\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingAddressChange(\n data: ShippingAddressChangeCallbackPayload,\n ): Promise {\n const address = this.paypalCommerceIntegrationService.getAddress({\n city: data.shippingAddress.city,\n countryCode: data.shippingAddress.country_code,\n postalCode: data.shippingAddress.postal_code,\n stateOrProvinceCode: data.shippingAddress.state,\n });\n\n try {\n // Info: we use the same address to fill billing and shipping addresses to have valid quota on BE for order updating process\n // on this stage we don't have access to valid customer's address except shipping data\n await this.paymentIntegrationService.updateBillingAddress(address);\n await this.paymentIntegrationService.updateShippingAddress(address);\n\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n ): Promise {\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private handleError(error: Error) {\n if (typeof this.onError === 'function') {\n this.onError(error);\n } else {\n throw error;\n }\n }\n}\n","import {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceCreditCustomerStrategy from './paypal-commerce-credit-customer-strategy';\n\nconst createPayPalCommerceCreditCustomerStrategy: CustomerStrategyFactory<\n PayPalCommerceCreditCustomerStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditCustomerStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceCreditCustomerStrategy, [\n { id: 'paypalcommercecredit' },\n]);\n","import {\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerStrategy,\n ExecutePaymentMethodCheckoutOptions,\n InvalidArgumentError,\n PaymentIntegrationService,\n RequestOptions,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport { ApproveCallbackPayload, PayPalCommerceButtonsOptions } from '../paypal-commerce-types';\n\nimport { WithPayPalCommerceVenmoCustomerInitializeOptions } from './paypal-commerce-venmo-customer-initialize-options';\n\nexport default class PayPalCommerceVenmoCustomerStrategy implements CustomerStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CustomerInitializeOptions & WithPayPalCommerceVenmoCustomerInitializeOptions,\n ): Promise {\n const { paypalcommercevenmo, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!paypalcommercevenmo) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"paypalcommercevenmo\" argument is not provided.`,\n );\n }\n\n if (!paypalcommercevenmo.container) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"paypalcommercevenmo.container\" argument is not provided.`,\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.renderButton(methodId, paypalcommercevenmo.container);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n async signIn(credentials: CustomerCredentials, options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signInCustomer(credentials, options);\n }\n\n async signOut(options?: RequestOptions): Promise {\n await this.paymentIntegrationService.signOutCustomer(options);\n }\n\n executePaymentMethodCheckout(options?: ExecutePaymentMethodCheckoutOptions): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve();\n }\n\n private renderButton(methodId: string, containerId: string): void {\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.VENMO,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(),\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder('paypalcommercevenmo'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const paypalButtonRender = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${containerId}`);\n } else {\n this.paypalCommerceIntegrationService.removeElement(containerId);\n }\n }\n}\n","import {\n CustomerStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceVenmoCustomerStrategy from './paypal-commerce-venmo-customer-strategy';\n\nconst createPayPalCommerceVenmoCustomerStrategy: CustomerStrategyFactory<\n PayPalCommerceVenmoCustomerStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceVenmoCustomerStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceVenmoCustomerStrategy, [\n { id: 'paypalcommercevenmo' },\n]);\n","import {\n CustomerStrategy,\n CustomerStrategyFactory,\n CustomerStrategyResolveId,\n isResolvableModule,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ResolveIdRegistry } from '../common/registry';\nimport * as defaultCustomerStrategyFactories from '../generated/customer-strategies';\n\nexport interface CustomerStrategyFactories {\n [key: string]: CustomerStrategyFactory;\n}\n\nexport default function createCustomerStrategyRegistry(\n paymentIntegrationService: PaymentIntegrationService,\n customerStrategyFactories: CustomerStrategyFactories = defaultCustomerStrategyFactories,\n): ResolveIdRegistry {\n const registry = new ResolveIdRegistry();\n\n for (const [, createCustomerStrategy] of Object.entries(customerStrategyFactories)) {\n if (\n !isResolvableModule<\n CustomerStrategyFactory,\n CustomerStrategyResolveId\n >(createCustomerStrategy)\n ) {\n continue;\n }\n\n for (const resolverId of createCustomerStrategy.resolveIds) {\n registry.register(resolverId, () => createCustomerStrategy(paymentIntegrationService));\n }\n }\n\n return registry;\n}\n","import { ExecuteSucceededAction, SpamProtectionAction } from './spam-protection-actions';\n\nexport default function isSpamProtectionExecuteSucceededAction(\n action: SpamProtectionAction,\n): action is ExecuteSucceededAction {\n const succeededAction = action as ExecuteSucceededAction;\n\n return (\n typeof succeededAction === 'object' &&\n typeof succeededAction.payload === 'object' &&\n typeof succeededAction.payload.token === 'string'\n );\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { LoadCheckoutAction } from '../checkout';\nimport { SpamProtectionAction } from '../spam-protection';\n\nimport Customer from './customer';\nimport { InternalCustomerResponseData } from './internal-customer-responses';\n\nexport enum CustomerActionType {\n SignInCustomerRequested = 'SIGN_IN_CUSTOMER_REQUESTED',\n SignInCustomerSucceeded = 'SIGN_IN_CUSTOMER_SUCCEEDED',\n SignInCustomerFailed = 'SIGN_IN_CUSTOMER_FAILED',\n\n SignOutCustomerRequested = 'SIGN_OUT_CUSTOMER_REQUESTED',\n SignOutCustomerSucceeded = 'SIGN_OUT_CUSTOMER_SUCCEEDED',\n SignOutCustomerFailed = 'SIGN_OUT_CUSTOMER_FAILED',\n\n CreateCustomerRequested = 'CREATE_CUSTOMER_REQUESTED',\n CreateCustomerSucceeded = 'CREATE_CUSTOMER_SUCCEEDED',\n CreateCustomerFailed = 'CREATE_CUSTOMER_FAILED',\n\n CreateCustomerAddressRequested = 'CREATE_CUSTOMER_ADDRESS_REQUESTED',\n CreateCustomerAddressSucceeded = 'CREATE_CUSTOMER_ADDRESS_SUCCEEDED',\n CreateCustomerAddressFailed = 'CREATE_CUSTOMER_ADDRESS_FAILED',\n\n StripeLinkAuthenticated = 'STRIPE_LINK_AUTHENTICATED',\n}\n\nexport type CustomerAction =\n | SignInCustomerAction\n | SignOutCustomerAction\n | CreateCustomerAddressAction\n | CreateCustomerAction;\n\nexport type CreateCustomerAction =\n | CreateCustomerRequestedAction\n | CreateCustomerSucceededAction\n | CreateCustomerFailedAction\n | SpamProtectionAction\n | LoadCheckoutAction;\n\nexport type CreateCustomerAddressAction =\n | CreateCustomerAddressRequestedAction\n | CreateCustomerAddressSucceededAction\n | CreateCustomerAddressFailedAction\n | LoadCheckoutAction;\n\nexport type SignInCustomerAction =\n | SignInCustomerRequestedAction\n | SignInCustomerSucceededAction\n | SignInCustomerFailedAction\n | LoadCheckoutAction;\n\nexport type SignOutCustomerAction =\n | SignOutCustomerRequestedAction\n | SignOutCustomerSucceededAction\n | SignOutCustomerFailedAction\n | LoadCheckoutAction;\n\nexport interface SignInCustomerRequestedAction extends Action {\n type: CustomerActionType.SignInCustomerRequested;\n}\n\nexport interface StripeLinkAuthenticatedAction extends Action {\n type: CustomerActionType.StripeLinkAuthenticated;\n}\n\nexport interface SignInCustomerSucceededAction extends Action {\n type: CustomerActionType.SignInCustomerSucceeded;\n}\n\nexport interface SignInCustomerFailedAction extends Action {\n type: CustomerActionType.SignInCustomerFailed;\n}\n\nexport interface SignOutCustomerRequestedAction extends Action {\n type: CustomerActionType.SignOutCustomerRequested;\n}\n\nexport interface SignOutCustomerSucceededAction extends Action {\n type: CustomerActionType.SignOutCustomerSucceeded;\n}\n\nexport interface SignOutCustomerFailedAction extends Action {\n type: CustomerActionType.SignOutCustomerFailed;\n}\n\nexport interface CreateCustomerRequestedAction extends Action {\n type: CustomerActionType.CreateCustomerRequested;\n}\n\nexport interface CreateCustomerSucceededAction extends Action {\n type: CustomerActionType.CreateCustomerSucceeded;\n}\n\nexport interface CreateCustomerFailedAction extends Action {\n type: CustomerActionType.CreateCustomerFailed;\n}\n\nexport interface CreateCustomerAddressRequestedAction extends Action {\n type: CustomerActionType.CreateCustomerAddressRequested;\n}\n\nexport interface CreateCustomerAddressSucceededAction extends Action {\n type: CustomerActionType.CreateCustomerAddressSucceeded;\n}\n\nexport interface CreateCustomerAddressFailedAction extends Action {\n type: CustomerActionType.CreateCustomerAddressFailed;\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, from, Observable, of } from 'rxjs';\nimport { catchError, switchMap } from 'rxjs/operators';\n\nimport { CheckoutActionCreator, InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\nimport {\n isSpamProtectionExecuteSucceededAction,\n SpamProtectionActionCreator,\n} from '../spam-protection';\n\nimport CustomerAccountRequestBody, { CustomerAddressRequestBody } from './customer-account';\nimport {\n CreateCustomerAction,\n CreateCustomerAddressAction,\n CustomerActionType,\n SignInCustomerAction,\n SignOutCustomerAction,\n} from './customer-actions';\nimport CustomerCredentials from './customer-credentials';\nimport CustomerRequestSender from './customer-request-sender';\n\nexport default class CustomerActionCreator {\n constructor(\n private _customerRequestSender: CustomerRequestSender,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _spamProtectionActionCreator: SpamProtectionActionCreator,\n ) {}\n\n createCustomer(\n customerAccount: CustomerAccountRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const state = store.getState();\n const config = state.config.getStoreConfigOrThrow();\n const { isStorefrontSpamProtectionEnabled } = config.checkoutSettings;\n\n const createCustomer = (token?: string) =>\n from(\n this._customerRequestSender.createAccount(\n { ...customerAccount, token },\n options,\n ),\n ).pipe(\n switchMap(() =>\n concat(\n this._checkoutActionCreator.loadCurrentCheckout(options)(store),\n of(createAction(CustomerActionType.CreateCustomerSucceeded)),\n ),\n ),\n );\n\n return concat(\n of(createAction(CustomerActionType.CreateCustomerRequested)),\n isStorefrontSpamProtectionEnabled\n ? from(this._spamProtectionActionCreator.execute()(store)).pipe(\n switchMap((action) =>\n isSpamProtectionExecuteSucceededAction(action)\n ? concat(of(action), createCustomer(action.payload?.token))\n : of(action),\n ),\n )\n : createCustomer(),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CustomerActionType.CreateCustomerFailed, error),\n ),\n );\n };\n }\n\n createAddress(\n customerAddress: CustomerAddressRequestBody,\n options?: RequestOptions,\n ): Observable {\n return concat(\n of(createAction(CustomerActionType.CreateCustomerAddressRequested)),\n defer(async () => {\n const { body } = await this._customerRequestSender.createAddress(\n customerAddress,\n options,\n );\n\n return createAction(CustomerActionType.CreateCustomerAddressSucceeded, body);\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CustomerActionType.CreateCustomerAddressFailed, error),\n ),\n );\n }\n\n signInCustomer(\n credentials: CustomerCredentials,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(CustomerActionType.SignInCustomerRequested)),\n from(this._customerRequestSender.signInCustomer(credentials, options)).pipe(\n switchMap(({ body }) =>\n concat(\n this._checkoutActionCreator.loadCurrentCheckout(options)(store),\n of(createAction(CustomerActionType.SignInCustomerSucceeded, body.data)),\n ),\n ),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CustomerActionType.SignInCustomerFailed, error),\n ),\n );\n }\n\n signOutCustomer(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(CustomerActionType.SignOutCustomerRequested)),\n from(this._customerRequestSender.signOutCustomer(options)).pipe(\n switchMap(({ body }) =>\n concat(\n this._checkoutActionCreator.loadCurrentCheckout(options)(store),\n of(\n createAction(\n CustomerActionType.SignOutCustomerSucceeded,\n body.data,\n ),\n ),\n ),\n ),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CustomerActionType.SignOutCustomerFailed, error),\n ),\n );\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nimport Customer from './customer';\nimport { CustomerAccountInternalRequestBody, CustomerAddressRequestBody } from './customer-account';\nimport CustomerCredentials from './customer-credentials';\nimport { InternalCustomerResponseBody } from './internal-customer-responses';\n\nexport default class CustomerRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n createAccount(\n customerAccount: CustomerAccountInternalRequestBody,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = '/api/storefront/customer';\n\n return this._requestSender.post(url, {\n timeout,\n headers: SDK_VERSION_HEADERS,\n body: customerAccount,\n });\n }\n\n createAddress(\n customerAddress: CustomerAddressRequestBody,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/customer-address`;\n\n return this._requestSender.post(url, {\n timeout,\n headers: SDK_VERSION_HEADERS,\n body: customerAddress,\n });\n }\n\n signInCustomer(\n credentials: CustomerCredentials,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = '/internalapi/v1/checkout/customer';\n\n return this._requestSender.post(url, {\n timeout,\n headers: SDK_VERSION_HEADERS,\n body: credentials,\n });\n }\n\n signOutCustomer({ timeout }: RequestOptions = {}): Promise<\n Response\n > {\n const url = '/internalapi/v1/checkout/customer';\n\n return this._requestSender.delete(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nexport enum CustomerStrategyActionType {\n SignInFailed = 'CUSTOMER_STRATEGY_SIGN_IN_FAILED',\n SignInRequested = 'CUSTOMER_STRATEGY_SIGN_IN_REQUESTED',\n SignInSucceeded = 'CUSTOMER_STRATEGY_SIGN_IN_SUCCEEDED',\n SignOutFailed = 'CUSTOMER_STRATEGY_SIGN_OUT_FAILED',\n SignOutRequested = 'CUSTOMER_STRATEGY_SIGN_OUT_REQUESTED',\n SignOutSucceeded = 'CUSTOMER_STRATEGY_SIGN_OUT_SUCCEEDED',\n ExecutePaymentMethodCheckoutFailed = 'CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_FAILED',\n ExecutePaymentMethodCheckoutRequested = 'CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_REQUESTED',\n ExecutePaymentMethodCheckoutSucceeded = 'CUSTOMER_STRATEGY_EXECUTE_PAYMENT_METHOD_CHECKOUT_SUCCEEDED',\n InitializeFailed = 'CUSTOMER_STRATEGY_INITIALIZE_FAILED',\n InitializeRequested = 'CUSTOMER_STRATEGY_INITIALIZE_REQUESTED',\n InitializeSucceeded = 'CUSTOMER_STRATEGY_INITIALIZE_SUCCEEDED',\n DeinitializeFailed = 'CUSTOMER_STRATEGY_DEINITIALIZE_FAILED',\n DeinitializeRequested = 'CUSTOMER_STRATEGY_DEINITIALIZE_REQUESTED',\n DeinitializeSucceeded = 'CUSTOMER_STRATEGY_DEINITIALIZE_SUCCEEDED',\n WidgetInteractionStarted = 'CUSTOMER_STRATEGY_WIDGET_INTERACTION_STARTED',\n WidgetInteractionFinished = 'CUSTOMER_STRATEGY_WIDGET_INTERACTION_FINISHED',\n WidgetInteractionFailed = 'CUSTOMER_STRATEGY_WIDGET_INTERACTION_FAILED',\n}\n\nexport type CustomerStrategyAction =\n | CustomerStrategySignInAction\n | CustomerStrategySignOutAction\n | CustomerStrategyExecutePaymentMethodCheckoutAction\n | CustomerStrategyInitializeAction\n | CustomerStrategyDeinitializeAction\n | CustomerStrategyWidgetAction;\n\nexport type CustomerStrategySignInAction =\n | SignInRequestedAction\n | SignInSucceededAction\n | SignInFailedAction;\n\nexport type CustomerStrategySignOutAction =\n | SignOutRequestedAction\n | SignOutSucceededAction\n | SignOutFailedAction;\n\nexport type CustomerStrategyExecutePaymentMethodCheckoutAction =\n | ExecutePaymentMethodCheckoutRequestedAction\n | ExecutePaymentMethodCheckoutSucceededAction\n | ExecutePaymentMethodCheckoutFailedAction;\n\nexport type CustomerStrategyInitializeAction =\n | InitializeRequestedAction\n | InitializeSucceededAction\n | InitializeFailedAction;\n\nexport type CustomerStrategyDeinitializeAction =\n | DeinitializeRequestedAction\n | DeinitializeSucceededAction\n | DeinitializeFailedAction;\n\nexport type CustomerStrategyWidgetAction =\n | WidgetInteractionStartedAction\n | WidgetInteractionFinishedAction\n | WidgetInteractionFailedAction;\n\nexport interface SignInRequestedAction extends Action {\n type: CustomerStrategyActionType.SignInRequested;\n}\n\nexport interface SignInSucceededAction extends Action {\n type: CustomerStrategyActionType.SignInSucceeded;\n}\n\nexport interface SignInFailedAction extends Action {\n type: CustomerStrategyActionType.SignInFailed;\n}\n\nexport interface SignOutRequestedAction extends Action {\n type: CustomerStrategyActionType.SignOutRequested;\n}\n\nexport interface SignOutSucceededAction extends Action {\n type: CustomerStrategyActionType.SignOutSucceeded;\n}\n\nexport interface SignOutFailedAction extends Action {\n type: CustomerStrategyActionType.SignOutFailed;\n}\n\nexport interface ExecutePaymentMethodCheckoutRequestedAction extends Action {\n type: CustomerStrategyActionType.ExecutePaymentMethodCheckoutRequested;\n}\n\nexport interface ExecutePaymentMethodCheckoutSucceededAction extends Action {\n type: CustomerStrategyActionType.ExecutePaymentMethodCheckoutSucceeded;\n}\n\nexport interface ExecutePaymentMethodCheckoutFailedAction extends Action {\n type: CustomerStrategyActionType.ExecutePaymentMethodCheckoutFailed;\n}\n\nexport interface InitializeRequestedAction extends Action {\n type: CustomerStrategyActionType.InitializeRequested;\n}\n\nexport interface InitializeSucceededAction extends Action {\n type: CustomerStrategyActionType.InitializeSucceeded;\n}\n\nexport interface InitializeFailedAction extends Action {\n type: CustomerStrategyActionType.InitializeFailed;\n}\n\nexport interface DeinitializeRequestedAction extends Action {\n type: CustomerStrategyActionType.DeinitializeRequested;\n}\n\nexport interface DeinitializeSucceededAction extends Action {\n type: CustomerStrategyActionType.DeinitializeSucceeded;\n}\n\nexport interface DeinitializeFailedAction extends Action {\n type: CustomerStrategyActionType.DeinitializeFailed;\n}\n\nexport interface WidgetInteractionStartedAction extends Action {\n type: CustomerStrategyActionType.WidgetInteractionStarted;\n}\n\nexport interface WidgetInteractionFinishedAction extends Action {\n type: CustomerStrategyActionType.WidgetInteractionFinished;\n}\n\nexport interface WidgetInteractionFailedAction extends Action {\n type: CustomerStrategyActionType.WidgetInteractionFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { CustomerStrategy as CustomerStrategyV2 } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { Registry } from '../common/registry';\n\nimport CustomerCredentials from './customer-credentials';\nimport {\n CustomerInitializeOptions,\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from './customer-request-options';\nimport {\n CustomerStrategyActionType,\n CustomerStrategyDeinitializeAction,\n CustomerStrategyExecutePaymentMethodCheckoutAction,\n CustomerStrategyInitializeAction,\n CustomerStrategySignInAction,\n CustomerStrategySignOutAction,\n CustomerStrategyWidgetAction,\n} from './customer-strategy-actions';\nimport CustomerStrategyRegistryV2 from './customer-strategy-registry-v2';\nimport { CustomerStrategy } from './strategies';\n\nexport default class CustomerStrategyActionCreator {\n constructor(\n private _strategyRegistry: Registry,\n private _strategyRegistryV2: CustomerStrategyRegistryV2,\n ) {}\n\n signIn(\n credentials: CustomerCredentials,\n options?: CustomerRequestOptions,\n ): Observable {\n return Observable.create((observer: Observer) => {\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n observer.next(\n createAction(CustomerStrategyActionType.SignInRequested, undefined, meta),\n );\n\n const promise: Promise = this._getStrategy(\n methodId,\n ).signIn(credentials, options);\n\n promise\n .then(() => {\n observer.next(\n createAction(CustomerStrategyActionType.SignInSucceeded, undefined, meta),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(CustomerStrategyActionType.SignInFailed, error, meta),\n );\n });\n });\n }\n\n signOut(options?: CustomerRequestOptions): Observable {\n return Observable.create((observer: Observer) => {\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n observer.next(\n createAction(CustomerStrategyActionType.SignOutRequested, undefined, meta),\n );\n\n const promise: Promise =\n this._getStrategy(methodId).signOut(options);\n\n promise\n .then(() => {\n observer.next(\n createAction(CustomerStrategyActionType.SignOutSucceeded, undefined, meta),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(CustomerStrategyActionType.SignOutFailed, error, meta),\n );\n });\n });\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Observable {\n return Observable.create(\n (observer: Observer) => {\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n observer.next(\n createAction(\n CustomerStrategyActionType.ExecutePaymentMethodCheckoutRequested,\n undefined,\n meta,\n ),\n );\n\n const promise: Promise =\n this._getStrategy(methodId).executePaymentMethodCheckout(options);\n\n promise\n .then(() => {\n observer.next(\n createAction(\n CustomerStrategyActionType.ExecutePaymentMethodCheckoutSucceeded,\n undefined,\n meta,\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n CustomerStrategyActionType.ExecutePaymentMethodCheckoutFailed,\n error,\n meta,\n ),\n );\n });\n },\n );\n }\n\n initialize(\n options?: CustomerInitializeOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n if (methodId && state.customerStrategies.isInitialized(methodId)) {\n return observer.complete();\n }\n\n observer.next(\n createAction(CustomerStrategyActionType.InitializeRequested, undefined, meta),\n );\n\n const promise: Promise =\n this._getStrategy(methodId).initialize(options);\n\n promise\n .then(() => {\n observer.next(\n createAction(\n CustomerStrategyActionType.InitializeSucceeded,\n undefined,\n meta,\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n CustomerStrategyActionType.InitializeFailed,\n error,\n meta,\n ),\n );\n });\n });\n }\n\n deinitialize(\n options?: CustomerRequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n if (methodId && !state.customerStrategies.isInitialized(methodId)) {\n return observer.complete();\n }\n\n observer.next(\n createAction(CustomerStrategyActionType.DeinitializeRequested, undefined, meta),\n );\n\n const promise: Promise =\n this._getStrategy(methodId).deinitialize(options);\n\n promise\n .then(() => {\n observer.next(\n createAction(\n CustomerStrategyActionType.DeinitializeSucceeded,\n undefined,\n meta,\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n CustomerStrategyActionType.DeinitializeFailed,\n error,\n meta,\n ),\n );\n });\n });\n }\n\n widgetInteraction(\n method: () => Promise,\n options?: CustomerRequestOptions,\n ): Observable {\n return Observable.create((observer: Observer) => {\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n observer.next(\n createAction(CustomerStrategyActionType.WidgetInteractionStarted, undefined, meta),\n );\n\n method()\n .then(() => {\n observer.next(\n createAction(\n CustomerStrategyActionType.WidgetInteractionFinished,\n undefined,\n meta,\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n CustomerStrategyActionType.WidgetInteractionFailed,\n error,\n meta,\n ),\n );\n });\n });\n }\n\n private _getStrategy(methodId?: string): CustomerStrategy | CustomerStrategyV2 {\n let strategy: CustomerStrategy | CustomerStrategyV2;\n\n try {\n strategy = this._strategyRegistryV2.get({ id: methodId || '' });\n } catch {\n strategy = this._strategyRegistry.get(methodId);\n }\n\n return strategy;\n }\n}\n","import joinIncludes from './join-includes';\nimport mergeIncludes from './merge-includes';\n\n/**\n * Joins or merges a base list of includes with a set of additional includes.\n */\nexport default function joinOrMergeIncludes(\n baseIncludes: T[],\n includeDictionaryOrList: { [key in T]?: boolean } | T[] = [],\n): string {\n return Array.isArray(includeDictionaryOrList)\n ? joinIncludes([...baseIncludes, ...includeDictionaryOrList])\n : mergeIncludes(baseIncludes, includeDictionaryOrList);\n}\n","import { difference, filter, keys, pickBy } from 'lodash';\n\nimport joinIncludes from './join-includes';\n\n/**\n * Merges includes given a list of base includes and a dictionary\n * of includes\n */\nexport default function mergeIncludes(\n baseIncludes: T[],\n includesDictionary?: { [key in T]?: boolean },\n): string {\n const deletions = keys(pickBy(includesDictionary, (on) => !on));\n const additions = keys(filter(includesDictionary));\n\n return joinIncludes([...difference(baseIncludes, deletions), ...additions]);\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n joinOrMergeIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport Checkout, { CheckoutRequestBody } from './checkout';\nimport CHECKOUT_DEFAULT_INCLUDES from './checkout-default-includes';\nimport CheckoutParams from './checkout-params';\nimport { CheckoutNotAvailableError } from './errors';\n\nexport default class CheckoutRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n loadCheckout(\n id: string,\n { params: { include } = {}, timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkout/${id}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender\n .get(url, {\n params: {\n include: joinOrMergeIncludes(CHECKOUT_DEFAULT_INCLUDES, include),\n },\n headers,\n timeout,\n })\n .catch((error) => {\n if (error.status >= 400 && error.status < 500) {\n throw new CheckoutNotAvailableError(error);\n }\n\n throw error;\n });\n }\n\n updateCheckout(\n id: string,\n body: CheckoutRequestBody,\n { params: { include } = {}, timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkout/${id}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.put(url, {\n params: {\n include: joinOrMergeIncludes(CHECKOUT_DEFAULT_INCLUDES, include),\n },\n body,\n headers,\n timeout,\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { LoadConfigAction } from '../config';\nimport { LoadFormFieldsAction } from '../form';\n\nimport Checkout from './checkout';\n\nexport enum CheckoutActionType {\n LoadCheckoutRequested = 'LOAD_CHECKOUT_REQUESTED',\n LoadCheckoutSucceeded = 'LOAD_CHECKOUT_SUCCEEDED',\n LoadCheckoutFailed = 'LOAD_CHECKOUT_FAILED',\n\n UpdateCheckoutRequested = 'UPDATE_CHECKOUT_REQUESTED',\n UpdateCheckoutSucceeded = 'UPDATE_CHECKOUT_SUCCEEDED',\n UpdateCheckoutFailed = 'UPDATE_CHECKOUT_FAILED',\n}\n\nexport type CheckoutAction = LoadCheckoutAction | UpdateCheckoutAction;\n\nexport type LoadCheckoutAction =\n | LoadCheckoutRequestedAction\n | LoadCheckoutSucceededAction\n | LoadCheckoutFailedAction\n | LoadFormFieldsAction\n | LoadConfigAction;\n\nexport type UpdateCheckoutAction =\n | UpdateCheckoutRequestedAction\n | UpdateCheckoutSucceededAction\n | UpdateCheckoutFailedAction;\n\nexport interface LoadCheckoutRequestedAction extends Action {\n type: CheckoutActionType.LoadCheckoutRequested;\n}\n\nexport interface LoadCheckoutSucceededAction extends Action {\n type: CheckoutActionType.LoadCheckoutSucceeded;\n}\n\nexport interface LoadCheckoutFailedAction extends Action {\n type: CheckoutActionType.LoadCheckoutFailed;\n}\n\nexport interface UpdateCheckoutRequestedAction extends Action {\n type: CheckoutActionType.UpdateCheckoutRequested;\n}\n\nexport interface UpdateCheckoutSucceededAction extends Action {\n type: CheckoutActionType.UpdateCheckoutSucceeded;\n}\n\nexport interface UpdateCheckoutFailedAction extends Action {\n type: CheckoutActionType.UpdateCheckoutFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, merge, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\nimport { ConfigActionCreator } from '../config';\nimport { FormFieldsActionCreator } from '../form';\n\nimport { CheckoutRequestBody } from './checkout';\nimport { CheckoutActionType, LoadCheckoutAction, UpdateCheckoutAction } from './checkout-actions';\nimport CheckoutRequestSender from './checkout-request-sender';\nimport InternalCheckoutSelectors from './internal-checkout-selectors';\n\nexport default class CheckoutActionCreator {\n constructor(\n private _checkoutRequestSender: CheckoutRequestSender,\n private _configActionCreator: ConfigActionCreator,\n private _formFieldsActionCreator: FormFieldsActionCreator,\n ) {}\n\n loadCheckout(id: string, options?: RequestOptions): Observable {\n return concat(\n of(createAction(CheckoutActionType.LoadCheckoutRequested)),\n merge(\n this._configActionCreator.loadConfig({\n ...options,\n useCache: true,\n params: { ...options?.params, checkoutId: id },\n }),\n this._formFieldsActionCreator.loadFormFields({ ...options, useCache: true }),\n defer(() =>\n this._checkoutRequestSender\n .loadCheckout(id, options)\n .then(({ body }) =>\n createAction(CheckoutActionType.LoadCheckoutSucceeded, body),\n ),\n ),\n ),\n ).pipe(\n catchError((error) => throwErrorAction(CheckoutActionType.LoadCheckoutFailed, error)),\n );\n }\n\n loadDefaultCheckout(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(CheckoutActionType.LoadCheckoutRequested)),\n merge(\n this._configActionCreator.loadConfig(),\n this._formFieldsActionCreator.loadFormFields({ ...options, useCache: true }),\n ),\n defer(async () => {\n const state = store.getState();\n const context = state.config.getContextConfig();\n\n if (!context || !context.checkoutId) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const { body } = await this._checkoutRequestSender.loadCheckout(\n context.checkoutId,\n options,\n );\n\n return createAction(CheckoutActionType.LoadCheckoutSucceeded, body);\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CheckoutActionType.LoadCheckoutFailed, error),\n ),\n );\n }\n\n updateCheckout(\n body: CheckoutRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n new Observable((observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(createAction(CheckoutActionType.UpdateCheckoutRequested));\n\n this._checkoutRequestSender\n .updateCheckout(checkout.id, body, options)\n .then(({ body }) => {\n observer.next(\n createAction(CheckoutActionType.UpdateCheckoutSucceeded, body),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(CheckoutActionType.UpdateCheckoutFailed, response),\n );\n });\n });\n }\n\n loadCurrentCheckout(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n return this.loadCheckout(checkout.id, options);\n };\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { FormFields } from './form-field';\n\nexport enum FormFieldsActionType {\n LoadFormFieldsRequested = 'LOAD_FORM_FIELDS_REQUESTED',\n LoadFormFieldsSucceeded = 'LOAD_FORM_FIELDS_SUCCEEDED',\n LoadFormFieldsFailed = 'LOAD_FORM_FIELDS_FAILED',\n}\n\nexport type LoadFormFieldsAction =\n | LoadFormFieldsRequestedAction\n | LoadFormFieldsSucceededAction\n | LoadFormFieldsFailedAction;\n\nexport interface LoadFormFieldsRequestedAction extends Action {\n type: FormFieldsActionType.LoadFormFieldsRequested;\n}\n\nexport interface LoadFormFieldsSucceededAction extends Action {\n type: FormFieldsActionType.LoadFormFieldsSucceeded;\n}\n\nexport interface LoadFormFieldsFailedAction extends Action {\n type: FormFieldsActionType.LoadFormFieldsFailed;\n}\n","import { createAction } from '@bigcommerce/data-store';\nimport { concat, defer, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { ActionOptions, cachableAction } from '../common/data-store';\nimport { throwErrorAction } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\n\nimport { FormFieldsActionType, LoadFormFieldsAction } from './form-fields-actions';\nimport FormFieldsRequestSender from './form-fields-request-sender';\n\nexport default class FormFieldsActionCreator {\n constructor(private _formFieldsRequestSender: FormFieldsRequestSender) {}\n\n @cachableAction\n loadFormFields(options?: RequestOptions & ActionOptions): Observable {\n return concat(\n of(createAction(FormFieldsActionType.LoadFormFieldsRequested)),\n defer(async () => {\n const { body } = await this._formFieldsRequestSender.loadFields(options);\n\n return createAction(FormFieldsActionType.LoadFormFieldsSucceeded, body);\n }),\n ).pipe(\n catchError((response) =>\n throwErrorAction(FormFieldsActionType.LoadFormFieldsFailed, response),\n ),\n );\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport { FormFields } from './form-field';\n\nexport default class FormFieldsRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n loadFields({ timeout }: RequestOptions = {}): Promise> {\n const url = '/api/storefront/form-fields';\n\n return this._requestSender.get(url, {\n timeout,\n headers: {\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport PaymentMethod from './payment-method';\nimport PaymentMethodMeta from './payment-method-meta';\n\nexport enum PaymentMethodActionType {\n LoadPaymentMethodRequested = 'LOAD_PAYMENT_METHOD_REQUESTED',\n LoadPaymentMethodSucceeded = 'LOAD_PAYMENT_METHOD_SUCCEEDED',\n LoadPaymentMethodFailed = 'LOAD_PAYMENT_METHOD_FAILED',\n\n LoadPaymentMethodsRequested = 'LOAD_PAYMENT_METHODS_REQUESTED',\n LoadPaymentMethodsSucceeded = 'LOAD_PAYMENT_METHODS_SUCCEEDED',\n LoadPaymentMethodsFailed = 'LOAD_PAYMENT_METHODS_FAILED',\n}\n\nexport type PaymentMethodAction = LoadPaymentMethodAction | LoadPaymentMethodsAction;\n\nexport type LoadPaymentMethodAction =\n | LoadPaymentMethodRequestedAction\n | LoadPaymentMethodSucceededAction\n | LoadPaymentMethodFailedAction;\n\nexport type LoadPaymentMethodsAction =\n | LoadPaymentMethodsRequestedAction\n | LoadPaymentMethodsSucceededAction\n | LoadPaymentMethodsFailedAction;\n\nexport interface LoadPaymentMethodRequestedAction extends Action {\n type: PaymentMethodActionType.LoadPaymentMethodRequested;\n}\n\nexport interface LoadPaymentMethodSucceededAction extends Action {\n type: PaymentMethodActionType.LoadPaymentMethodSucceeded;\n}\n\nexport interface LoadPaymentMethodFailedAction extends Action {\n type: PaymentMethodActionType.LoadPaymentMethodFailed;\n}\n\nexport interface LoadPaymentMethodsRequestedAction extends Action {\n type: PaymentMethodActionType.LoadPaymentMethodsRequested;\n}\n\nexport interface LoadPaymentMethodsSucceededAction\n extends Action {\n type: PaymentMethodActionType.LoadPaymentMethodsSucceeded;\n}\n\nexport interface LoadPaymentMethodsFailedAction extends Action {\n type: PaymentMethodActionType.LoadPaymentMethodsFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { filter } from 'lodash';\nimport { Observable, Observer } from 'rxjs';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { ActionOptions, cachableAction } from '../common/data-store';\nimport { RequestOptions } from '../common/http-request';\n\nimport {\n LoadPaymentMethodAction,\n LoadPaymentMethodsAction,\n PaymentMethodActionType,\n} from './payment-method-actions';\nimport PaymentMethodRequestSender from './payment-method-request-sender';\nimport { isApplePayWindow } from './strategies/apple-pay';\n\nimport { PaymentMethod } from '.';\n\nconst APPLEPAYID = 'applepay';\n\nexport default class PaymentMethodActionCreator {\n constructor(private _requestSender: PaymentMethodRequestSender) {}\n\n loadPaymentMethods(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const cart = state.cart.getCartOrThrow();\n\n observer.next(createAction(PaymentMethodActionType.LoadPaymentMethodsRequested));\n\n this._requestSender\n .loadPaymentMethods({\n ...options,\n params: { ...options?.params, cartId: cart.id },\n })\n .then((response) => {\n const meta = {\n deviceSessionId: response.headers['x-device-session-id'],\n sessionHash: response.headers['x-session-hash'],\n };\n const methods = response.body;\n const filteredMethods = Array.isArray(methods)\n ? this._filterApplePay(methods)\n : methods;\n\n observer.next(\n createAction(\n PaymentMethodActionType.LoadPaymentMethodsSucceeded,\n filteredMethods,\n meta,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n PaymentMethodActionType.LoadPaymentMethodsFailed,\n response,\n ),\n );\n });\n });\n }\n\n @cachableAction\n loadPaymentMethod(\n methodId: string,\n options?: RequestOptions & ActionOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const cartId = state.cart.getCart()?.id;\n const params = cartId ? { ...options?.params, cartId } : { ...options?.params };\n\n observer.next(\n createAction(PaymentMethodActionType.LoadPaymentMethodRequested, undefined, {\n methodId,\n }),\n );\n\n this._requestSender\n .loadPaymentMethod(methodId, { ...options, params })\n .then((response) => {\n observer.next(\n createAction(\n PaymentMethodActionType.LoadPaymentMethodSucceeded,\n response.body,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n PaymentMethodActionType.LoadPaymentMethodFailed,\n response,\n { methodId },\n ),\n );\n });\n });\n }\n\n private _filterApplePay(methods: PaymentMethod[]): PaymentMethod[] {\n return filter(methods, (method) => {\n if (method.id === APPLEPAYID && !isApplePayWindow(window)) {\n return false;\n }\n\n return true;\n });\n }\n}\n","export interface ApplePayWindow extends Window {\n ApplePaySession: ApplePaySession;\n}\n\nexport default function isApplePayWindow(window: Window): window is ApplePayWindow {\n return 'ApplePaySession' in window;\n}\n\nexport function assertApplePayWindow(window: Window): asserts window is ApplePayWindow {\n if (!isApplePayWindow(window)) {\n throw new Error('Apple pay is not supported');\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport PaymentMethod from './payment-method';\n\nexport default class PaymentMethodRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n loadPaymentMethods({ timeout, params }: RequestOptions = {}): Promise<\n Response\n > {\n const url = '/api/storefront/payments';\n\n return this._requestSender.get(url, {\n timeout,\n headers: {\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n params,\n });\n }\n\n loadPaymentMethod(\n methodId: string,\n { timeout, params }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/payments/${methodId}`;\n\n return this._requestSender.get(url, {\n timeout,\n headers: {\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n params,\n });\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { BuyNowCartRequestBody, Cart } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ContentType, RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nexport default class CartRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n createBuyNowCart(\n body: BuyNowCartRequestBody,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = '/api/storefront/carts';\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, { body, headers, timeout });\n }\n}\n","import { isEqual } from 'lodash';\n\nimport { PartialDeep } from '../common/types';\n\nimport Cart from './cart';\n\nexport default class CartComparator {\n isEqual(cartA: Cart, cartB: Cart): boolean {\n return isEqual(this._normalize(cartA), this._normalize(cartB));\n }\n\n private _normalize(cart: Cart): PartialDeep {\n return {\n cartAmount: cart.cartAmount,\n currency: cart.currency,\n id: cart.id,\n lineItems: {\n digitalItems: cart.lineItems.digitalItems\n .slice()\n .sort((itemA, itemB) =>\n `${itemA.productId}${itemA.variantId}`.localeCompare(\n `${itemB.productId}${itemB.variantId}`,\n ),\n )\n .map((item) => ({\n extendedSalePrice: item.extendedSalePrice,\n productId: item.productId,\n quantity: item.quantity,\n variantId: item.variantId,\n })),\n giftCertificates: cart.lineItems.giftCertificates\n .slice()\n .sort((itemA, itemB) => `${itemA.id}`.localeCompare(`${itemB.id}`))\n .map((item) => ({\n amount: item.amount,\n recipient: item.recipient,\n })),\n physicalItems: cart.lineItems.physicalItems\n .slice()\n .sort((itemA, itemB) =>\n `${itemA.productId}${itemA.variantId}`.localeCompare(\n `${itemB.productId}${itemB.variantId}`,\n ),\n )\n .map((item) => ({\n extendedSalePrice: item.extendedSalePrice,\n productId: item.productId,\n quantity: item.quantity,\n variantId: item.variantId,\n giftWrapping: item.giftWrapping,\n })),\n },\n };\n }\n}\n","import { ComparableCheckout } from '../../checkout';\nimport { StandardError } from '../../common/error/errors';\n\nexport default class CartChangedError extends StandardError {\n /**\n * @alpha\n * Please note that this option is currently in an early stage of\n * development. Therefore the API is unstable and not ready for public\n * consumption.\n */\n data: { previous: ComparableCheckout; updated: ComparableCheckout };\n\n constructor(previous: ComparableCheckout, updated: ComparableCheckout) {\n super(\n 'An update to your shopping cart has been detected and your available shipping costs have been updated.',\n );\n\n this.name = 'CartChangedError';\n this.type = 'cart_changed';\n this.data = {\n previous,\n updated,\n };\n }\n}\n","import { isEqual, map } from 'lodash';\n\nimport { Cart, CartComparator } from '../cart';\nimport { CartChangedError } from '../cart/errors';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\nimport { Coupon, GiftCertificate } from '../coupon';\n\nimport Checkout from './checkout';\nimport CheckoutRequestSender from './checkout-request-sender';\n\nexport type ComparableCheckout = Pick<\n Checkout,\n 'outstandingBalance' | 'coupons' | 'giftCertificates'\n> & {\n cart: Partial;\n};\n\nexport default class CheckoutValidator {\n constructor(private _checkoutRequestSender: CheckoutRequestSender) {}\n\n validate(checkout?: Checkout, options?: RequestOptions): Promise {\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n return this._checkoutRequestSender.loadCheckout(checkout.id, options).then((response) => {\n const comparator = new CartComparator();\n\n if (\n checkout.outstandingBalance === response.body.outstandingBalance &&\n this._compareCoupons(checkout.coupons, response.body.coupons) &&\n this._compareGiftCertificates(\n checkout.giftCertificates,\n response.body.giftCertificates,\n ) &&\n comparator.isEqual(checkout.cart, response.body.cart)\n ) {\n return;\n }\n\n throw new CartChangedError(\n this._getComparableCheckout(checkout),\n this._getComparableCheckout(response.body),\n );\n });\n }\n\n private _compareCoupons(couponsA: Coupon[], couponsB: Coupon[]): boolean {\n return isEqual(map(couponsA, 'code'), map(couponsB, 'code'));\n }\n\n private _compareGiftCertificates(\n giftCertificatesA: GiftCertificate[],\n giftCertificatesB: GiftCertificate[],\n ): boolean {\n return isEqual(map(giftCertificatesA, 'code'), map(giftCertificatesB, 'code'));\n }\n\n private _getComparableCheckout(checkout: Checkout): ComparableCheckout {\n const { cart, coupons, giftCertificates, outstandingBalance } = checkout;\n\n return {\n cart: {\n cartAmount: cart.cartAmount,\n currency: cart.currency,\n lineItems: cart.lineItems,\n },\n coupons,\n giftCertificates,\n outstandingBalance,\n };\n }\n}\n","export default class CancellablePromise {\n promise: Promise;\n cancel!: (reason?: any) => void;\n\n constructor(promise: Promise) {\n const cancellable = new Promise((_, reject) => {\n this.cancel = reject;\n });\n\n this.promise = Promise.race([promise, cancellable]);\n }\n}\n","import { StandardError } from '../../error/errors';\n\nexport default class UnexpectedDetachmentError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Unable to proceed because the required element is unexpectedly detached from the page.',\n );\n\n this.name = 'UnexpectedDetachmentError';\n this.type = 'unexpected_detachment';\n }\n}\n","import { CancellablePromise } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { UnexpectedDetachmentError } from './errors';\nimport { MutationObserverFactory } from './mutation-observer';\n\nexport default class DetachmentObserver {\n constructor(private _mutationObserver: MutationObserverFactory) {}\n\n async ensurePresence(targets: Node[], promise: Promise): Promise {\n const cancellable = new CancellablePromise(promise);\n\n const observer = this._mutationObserver.create((mutationsList) => {\n mutationsList.forEach((mutation) => {\n const removedTargets = Array.from(mutation.removedNodes).filter((node) =>\n targets.some((target) => node === target || node.contains(target)),\n );\n\n if (removedTargets.length === 0) {\n return;\n }\n\n cancellable.cancel(new UnexpectedDetachmentError());\n });\n });\n\n observer.observe(document.body, { childList: true, subtree: true });\n\n try {\n const output = await cancellable.promise;\n\n observer.disconnect();\n\n return output;\n } catch (error) {\n observer.disconnect();\n\n throw error;\n }\n }\n}\n","export interface MutationObeserverCreator {\n prototype: MutationObserver;\n new (callback: MutationCallback): MutationObserver;\n}\n\nexport interface MutationObserverWindow extends Window {\n MutationObserver: MutationObeserverCreator;\n}\n\nexport class MutationObserverFactory {\n constructor(private _window: MutationObserverWindow = window as MutationObserverWindow) {}\n\n create(callback: MutationCallback): MutationObserver {\n return new this._window.MutationObserver(callback);\n }\n}\n","import { InvalidArgumentError } from '../error/errors';\n\nimport Url from './url';\n\nexport default function parseUrl(url: string): Url {\n if (!/^(https?:)?\\/\\//.test(url)) {\n throw new InvalidArgumentError('The provided URL must be absolute.');\n }\n\n // new URL() is not supported in IE11, use anchor tag instead\n const anchor = document.createElement('a');\n\n anchor.href = url;\n\n // IE11 returns 80 or 443 for the port number depending on the URL scheme,\n // even if the port number is not specified in the URL.\n const port =\n anchor.port && url.indexOf(`${anchor.hostname}:${anchor.port}`) !== -1 ? anchor.port : '';\n\n return {\n hash: anchor.hash,\n hostname: anchor.hostname,\n href: anchor.href,\n origin: `${anchor.protocol}//${anchor.hostname}${port ? `:${port}` : ''}`,\n pathname: anchor.pathname,\n port,\n protocol: anchor.protocol,\n search: anchor.search,\n };\n}\n","import IframeEvent from './iframe-event';\n\nexport default function isIframeEvent, TType extends string>(\n object: any,\n type: TType,\n): object is TEvent {\n return object.type === type;\n}\n","import { fromEvent } from 'rxjs';\nimport { filter, map, take } from 'rxjs/operators';\n\nimport { parseUrl } from '../url';\n\nimport IframeEvent from './iframe-event';\nimport isIframeEvent from './is-iframe-event';\n\nexport interface IframeEventPostOptions<\n TSuccessEvent extends IframeEvent,\n TErrorEvent extends IframeEvent,\n> {\n errorType?: TErrorEvent['type'];\n successType?: TSuccessEvent['type'];\n}\n\nexport default class IframeEventPoster {\n private _targetOrigin: string;\n\n constructor(targetOrigin: string, private _targetWindow?: Window) {\n this._targetOrigin = targetOrigin === '*' ? '*' : parseUrl(targetOrigin).origin;\n }\n\n post(event: TEvent): void;\n post<\n TSuccessEvent extends IframeEvent = IframeEvent,\n TErrorEvent extends IframeEvent = IframeEvent,\n >(\n event: TEvent,\n options: IframeEventPostOptions,\n ): Promise;\n post<\n TSuccessEvent extends IframeEvent = IframeEvent,\n TErrorEvent extends IframeEvent = IframeEvent,\n >(\n event: TEvent,\n options?: IframeEventPostOptions,\n ): Promise | void {\n const targetWindow = this._targetWindow;\n\n if (window === targetWindow) {\n return;\n }\n\n if (!targetWindow) {\n throw new Error('Unable to post message because target window is not set.');\n }\n\n const result =\n options &&\n fromEvent(window, 'message')\n .pipe(\n filter(\n (event) =>\n event.origin === this._targetOrigin &&\n isIframeEvent(event.data, event.data.type) &&\n [options.successType, options.errorType].indexOf(event.data.type) !==\n -1,\n ),\n map((event) => {\n if (options.errorType === event.data.type) {\n throw event.data;\n }\n\n return event.data;\n }),\n take(1),\n )\n .toPromise();\n\n targetWindow.postMessage(event, this._targetOrigin);\n\n return result;\n }\n\n setTarget(window: Window) {\n this._targetWindow = window;\n }\n}\n","/**\n * Decorates a class or a method by binding all its prototype methods or itself\n * to the calling instance respectively.\n */\nfunction bindDecorator(\n target: object,\n key: string,\n descriptor: TypedPropertyDescriptor,\n): TypedPropertyDescriptor;\nfunction bindDecorator>(target: T): T;\n\nfunction bindDecorator(target: any, key?: any, descriptor?: any): any {\n if (!key || !descriptor) {\n return bindClassDecorator(target);\n }\n\n return bindMethodDecorator(target, key, descriptor);\n}\n\nexport default bindDecorator;\n\n/**\n * Decorates a class by binding all its prototype methods to the calling\n * instance.\n */\nexport function bindClassDecorator>(target: T): T {\n const decoratedTarget = class extends target {};\n\n Object.getOwnPropertyNames(target.prototype).forEach((key) => {\n const descriptor = Object.getOwnPropertyDescriptor(target.prototype, key);\n\n if (!descriptor || key === 'constructor') {\n return;\n }\n\n Object.defineProperty(\n decoratedTarget.prototype,\n key,\n bindMethodDecorator(target.prototype, key, descriptor),\n );\n });\n\n return decoratedTarget;\n}\n\n/**\n * Decorates a method by binding it to the calling instance.\n */\nexport function bindMethodDecorator(\n _: object,\n key: string,\n descriptor: TypedPropertyDescriptor,\n): TypedPropertyDescriptor {\n if (typeof descriptor.value !== 'function') {\n return descriptor;\n }\n\n let method: T = descriptor.value;\n\n return {\n get() {\n const boundMethod = method.bind(this) as T;\n\n Object.defineProperty(this, key, {\n ...descriptor,\n value: boundMethod,\n });\n\n return boundMethod;\n },\n set(value) {\n method = value;\n },\n };\n}\n\nexport type Constructor = new (...args: any[]) => T;\nexport type Method = (...args: any[]) => any;\n","import { appendWww, parseUrl } from '../url';\nimport { bindDecorator as bind } from '../utility';\n\nimport { IframeEventMap } from './iframe-event';\nimport isIframeEvent from './is-iframe-event';\n\nexport default class IframeEventListener> {\n private _isListening: boolean;\n private _listeners: EventListeners;\n private _sourceOrigins: string[];\n\n constructor(sourceOrigin: string) {\n this._sourceOrigins = [\n parseUrl(sourceOrigin).origin,\n appendWww(parseUrl(sourceOrigin)).origin,\n ];\n this._isListening = false;\n this._listeners = {};\n }\n\n listen(): void {\n if (this._isListening) {\n return;\n }\n\n this._isListening = true;\n\n window.addEventListener('message', this._handleMessage);\n }\n\n stopListen(): void {\n if (!this._isListening) {\n return;\n }\n\n this._isListening = false;\n\n window.removeEventListener('message', this._handleMessage);\n }\n\n addListener(\n type: TType,\n listener: (event: TEventMap[TType]) => void,\n ): void {\n let listeners = this._listeners[type];\n\n if (!listeners) {\n this._listeners[type] = listeners = [];\n }\n\n if (listeners.indexOf(listener) === -1) {\n listeners.push(listener);\n }\n }\n\n removeListener(\n type: TType,\n listener: (event: TEventMap[TType]) => void,\n ): void {\n const listeners = this._listeners[type];\n\n if (!listeners) {\n return;\n }\n\n const index = listeners.indexOf(listener);\n\n if (index >= 0) {\n listeners.splice(index, 1);\n }\n }\n\n trigger(event: TEventMap[TType]): void {\n const listeners = this._listeners[event.type];\n\n if (!listeners) {\n return;\n }\n\n listeners.forEach((listener) => listener(event));\n }\n\n @bind\n private _handleMessage(event: MessageEvent): void {\n if (\n this._sourceOrigins.indexOf(event.origin) === -1 ||\n !isIframeEvent(event.data as TEventMap[keyof TEventMap], event.data.type)\n ) {\n return;\n }\n\n this.trigger(event.data);\n }\n}\n\ntype EventListeners = {\n [key in keyof TEventMap]?: Array<(event: TEventMap[key]) => void>;\n};\n","import parseUrl from './parse-url';\nimport Url from './url';\n\nexport default function appendWww(url: Url): Url {\n return parseUrl(\n url.hostname.indexOf('www') === 0\n ? url.href\n : url.href.replace(url.hostname, `www.${url.hostname}`),\n );\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if the shopper chooses not to complete the spam protection\n * challenge (i.e.: they close the reCaptcha window).\n */\nexport default class SpamProtectionChallengeNotCompletedError extends StandardError {\n constructor() {\n super(\"You haven't complete our spam protection challenge. Please try again.\");\n\n this.name = 'SpamProtectionChallengeNotCompletedError';\n this.type = 'spam_protection_challenge_not_completed';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if the shopper chooses not to complete the spam protection\n * challenge (i.e.: they close the reCaptcha window).\n */\nexport default class CardingProtectionChallengeNotCompletedError extends StandardError {\n constructor() {\n super('Please complete our human verification challenge and try again.');\n\n this.name = 'CardingProtectionChallengeNotCompletedError';\n this.type = 'carding_protection_challenge_not_completed';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if we fail to complete the required spam protection\n * verification due to an unknown reason.\n */\nexport default class CardingProtectionFailedError extends StandardError {\n constructor() {\n super('We were not able to verify that you are not a robot. Please try again.');\n\n this.name = 'CardingProtectionFailedError';\n this.type = 'carding_protection_failed';\n }\n}\n","import { switchMap, take } from 'rxjs/operators';\n\nimport { RequestError } from '../common/error/errors';\nimport { PaymentAdditionalAction } from '../payment';\n\nimport {\n CardingProtectionChallengeNotCompletedError,\n CardingProtectionFailedError,\n SpamProtectionChallengeNotCompletedError,\n} from './errors';\nimport GoogleRecaptcha from './google-recaptcha';\n\nexport default class PaymentHumanVerificationHandler {\n constructor(private _googleRecaptcha: GoogleRecaptcha) {}\n\n handle(error: Error): Promise;\n handle(id: string, key: string): Promise;\n async handle(errorOrId: Error | string, key?: string): Promise {\n if (typeof errorOrId === 'string') {\n return this.handleWithRecaptchaSitekey(errorOrId, key);\n }\n\n return this.handleWithPaymentHumanVerificationRequestError(errorOrId);\n }\n\n private async handleWithPaymentHumanVerificationRequestError(\n error: Error,\n ): Promise {\n if (!this._isPaymentHumanVerificationRequest(error)) {\n throw error;\n }\n\n await this._initialize(error.body.additional_action_required.data.key);\n\n return this._performRecaptcha();\n }\n\n private async handleWithRecaptchaSitekey(\n id: string,\n key?: string,\n ): Promise {\n if (id !== 'recaptcha_v2') {\n throw Error('Human verification method is not supported.');\n }\n\n if (!key) {\n throw Error('Recaptcha site key is missing.');\n }\n\n await this._initialize(key);\n\n return this._performRecaptcha();\n }\n\n private _performRecaptcha(): Promise {\n return this._googleRecaptcha\n .execute()\n .pipe(take(1))\n .pipe(\n switchMap(async ({ error, token }) => {\n if (error instanceof SpamProtectionChallengeNotCompletedError) {\n throw new CardingProtectionChallengeNotCompletedError();\n }\n\n if (error || !token) {\n throw new CardingProtectionFailedError();\n }\n\n return {\n type: 'recaptcha_v2_verification',\n data: {\n human_verification_token: token,\n },\n };\n }),\n )\n .toPromise();\n }\n\n private _initialize(recaptchaSitekey: string): Promise {\n const cardingProtectionElementId = 'cardingProtectionContainer';\n\n let cardingProtectionElement = document.getElementById(cardingProtectionElementId);\n\n if (cardingProtectionElement && cardingProtectionElement.parentNode) {\n cardingProtectionElement.parentNode.removeChild(cardingProtectionElement);\n }\n\n cardingProtectionElement = document.createElement('div');\n cardingProtectionElement.setAttribute('id', cardingProtectionElementId);\n document.body.appendChild(cardingProtectionElement);\n\n return this._googleRecaptcha.load(cardingProtectionElementId, recaptchaSitekey);\n }\n\n private _isPaymentHumanVerificationRequest(error: Error): error is RequestError {\n const { additional_action_required, status } = (error as RequestError).body || {};\n\n return (\n status === 'additional_action_required' &&\n additional_action_required &&\n additional_action_required.type === 'recaptcha_v2_verification'\n );\n }\n}\n","import StandardError from './standard-error';\n\nexport enum NotInitializedErrorType {\n CheckoutButtonNotInitialized,\n CustomerNotInitialized,\n PaymentNotInitialized,\n ShippingNotInitialized,\n SpamProtectionNotInitialized,\n}\n\n/**\n * Throw this error if a method requires a certain initialization call to be\n * made first. Some objects can be constructed but they cannot be used until a\n * separate initialization call is made.\n */\nexport default class NotInitializedError extends StandardError {\n constructor(public subtype: NotInitializedErrorType) {\n super(getErrorMessage(subtype));\n\n this.name = 'NotInitializedError';\n this.type = 'not_initialized';\n }\n}\n\nfunction getErrorMessage(type: NotInitializedErrorType): string {\n switch (type) {\n case NotInitializedErrorType.CustomerNotInitialized:\n return 'Unable to proceed because the customer step of checkout has not been initialized.';\n\n case NotInitializedErrorType.PaymentNotInitialized:\n return 'Unable to proceed because the payment step of checkout has not been initialized.';\n\n case NotInitializedErrorType.ShippingNotInitialized:\n return 'Unable to proceed because the shipping step of checkout has not been initialized.';\n\n case NotInitializedErrorType.SpamProtectionNotInitialized:\n return 'Unable to proceed because the checkout spam protection has not been initialized.';\n\n default:\n return 'Unable to proceed because the required component has not been initialized.';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if we fail to complete the required spam protection\n * verification due to an unknown reason.\n */\nexport default class SpamProtectionFailedError extends StandardError {\n constructor() {\n super('We were not able to complete your spam protection verification. Please try again.');\n\n this.name = 'SpamProtectionFailedError';\n this.type = 'spam_protection_failed';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if spam protection is not loaded when trying to\n * complete the required spam protection verification.\n */\nexport default class SpamProtectionNotLoadedError extends StandardError {\n constructor() {\n super('Spam protection is not loaded. Please try again.');\n\n this.name = 'SpamProtectionNotLoadedError';\n this.type = 'spam_protection_failed';\n }\n}\n","import { memoize } from '@bigcommerce/memoize';\nimport { defer, Observable, of, Subject, throwError } from 'rxjs';\nimport { catchError, delay, retryWhen, switchMap } from 'rxjs/operators';\n\nimport { MutationObserverFactory } from '../common/dom';\nimport { NotInitializedError, NotInitializedErrorType } from '../common/error/errors';\n\nimport {\n SpamProtectionChallengeNotCompletedError,\n SpamProtectionFailedError,\n SpamProtectionNotLoadedError,\n} from './errors';\nimport GoogleRecaptchaScriptLoader from './google-recaptcha-script-loader';\n\nconst TIMEOUT = 7000;\nconst RETRY_INTERVAL = 250;\nconst MAX_RETRIES = TIMEOUT / RETRY_INTERVAL;\n\nexport interface RecaptchaResult {\n error?: Error;\n token?: string;\n}\n\nexport default class GoogleRecaptcha {\n private _event$?: Subject;\n private _recaptcha?: ReCaptchaV2.ReCaptcha;\n private _memoized: (\n recaptcha: ReCaptchaV2.ReCaptcha,\n sitekey: string,\n container: HTMLElement | null,\n ) => Subject;\n private _widgetId?: number;\n\n constructor(\n private googleRecaptchaScriptLoader: GoogleRecaptchaScriptLoader,\n private mutationObserverFactory: MutationObserverFactory,\n ) {\n this._memoized = memoize(\n (recaptcha: ReCaptchaV2.ReCaptcha, sitekey: string, container: HTMLElement | null) => {\n const event$ = new Subject();\n\n if (!container) {\n throw new Error();\n }\n\n this._widgetId = recaptcha.render(container.id, {\n sitekey,\n size: 'invisible',\n callback: () => {\n event$.next({\n token: recaptcha.getResponse(this._widgetId),\n });\n recaptcha.reset(this._widgetId);\n },\n 'error-callback': () => {\n event$.next({\n error: new SpamProtectionFailedError(),\n });\n },\n });\n\n return event$;\n },\n { isEqual: (a, b) => a === b },\n );\n }\n\n load(containerId: string, sitekey: string): Promise {\n return this.googleRecaptchaScriptLoader.load().then((recaptcha) => {\n if (recaptcha) {\n this._event$ = this._memoized(\n recaptcha,\n sitekey,\n document.getElementById(containerId),\n );\n this._recaptcha = recaptcha;\n }\n });\n }\n\n execute(): Observable {\n return defer(() => {\n const event$ = this._event$;\n const recaptcha = this._recaptcha;\n\n if (!event$ || !recaptcha) {\n throw new NotInitializedError(NotInitializedErrorType.SpamProtectionNotInitialized);\n }\n\n return defer(() => {\n const element = document.querySelector('iframe[src*=\"bframe\"]');\n\n return element ? of(element) : throwError(new SpamProtectionNotLoadedError());\n }).pipe(\n retryWhen((errors) =>\n errors.pipe(\n delay(RETRY_INTERVAL),\n switchMap((error, index) =>\n index < MAX_RETRIES ? of(error) : throwError(error),\n ),\n ),\n ),\n switchMap((element) => {\n this._watchRecaptchaChallengeWindow(event$, element);\n recaptcha.execute(this._widgetId);\n\n return event$;\n }),\n catchError((error) => of({ error })),\n );\n });\n }\n\n private _watchRecaptchaChallengeWindow(event: Subject, element: Element) {\n const iframeContainer = element.parentElement;\n\n if (!iframeContainer) {\n throw new SpamProtectionNotLoadedError();\n }\n\n const container = iframeContainer.parentElement;\n\n if (!container) {\n throw new SpamProtectionNotLoadedError();\n }\n\n this.mutationObserverFactory\n .create(() => {\n // When customer closes the Google ReCaptcha challenge window, throw SpamProtectionNotCompletedError\n if (container.style.visibility === 'hidden') {\n event.next({\n error: new SpamProtectionChallengeNotCompletedError(),\n });\n }\n })\n .observe(container, { attributes: true, attributeFilter: ['style'] });\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nexport default class GoogleRecaptchaScriptLoader {\n private _loadPromise?: Promise;\n\n constructor(\n private _scriptLoader: ScriptLoader,\n private _window: GoogleRecaptchaWindow = window,\n ) {}\n\n load(): Promise {\n if (!this._loadPromise) {\n this._loadPromise = this._loadScript();\n }\n\n return this._loadPromise;\n }\n\n private _loadScript(): Promise {\n const callbackName = 'initRecaptcha';\n const params = [`onload=${callbackName}`, 'render=explicit'].join('&');\n\n return new Promise((resolve, reject) => {\n this._window[callbackName] = () => resolve(this._window.grecaptcha);\n\n this._scriptLoader\n .loadScript(`//www.google.com/recaptcha/api.js?${params}`)\n .catch((error) => {\n this._loadPromise = undefined;\n reject(error);\n });\n });\n }\n}\n\nexport interface GoogleRecaptchaWindow extends Window {\n grecaptcha?: ReCaptchaV2.ReCaptcha;\n initRecaptcha?(): void;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { MutationObserverFactory } from '../common/dom';\n\nimport GoogleRecaptcha from './google-recaptcha';\nimport GoogleRecaptchaScriptLoader from './google-recaptcha-script-loader';\n\nexport default function createSpamProtection(scriptLoader: ScriptLoader): GoogleRecaptcha {\n return new GoogleRecaptcha(\n new GoogleRecaptchaScriptLoader(scriptLoader),\n new MutationObserverFactory(),\n );\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { PaymentErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport RequestError from './request-error';\n\nexport default function mapFromPaymentErrorResponse(\n response: Response,\n message?: string,\n): RequestError {\n const { body } = response;\n const { errors = [] } = body;\n\n return new RequestError(response, {\n message: joinErrors(errors) || message,\n errors,\n });\n}\n\nfunction joinErrors(errors: Array<{ code: string; message?: string }>): string | undefined {\n if (!Array.isArray(errors)) {\n return;\n }\n\n return errors\n .reduce((result: string[], error) => {\n if (error && error.message) {\n return [...result, error.message];\n }\n\n return result;\n }, [])\n .join(' ');\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport default class InvalidHostedFormConfigError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Unable to proceed due to invalid configuration provided for the hosted payment form.',\n );\n\n this.name = 'InvalidHostedFormConfigError';\n this.type = 'invalid_hosted_form_config';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport default class InvalidHostedFormError extends StandardError {\n constructor(message?: string) {\n super(message || 'Unable to proceed due to an unknown error with the hosted payment form.');\n\n this.name = 'InvalidHostedFormError';\n this.type = 'invalid_hosted_form';\n }\n}\n","import { flatMap, map, values } from 'lodash';\n\nimport { StandardError } from '../../common/error/errors';\nimport { HostedInputValidateErrorDataMap } from '../iframe-content';\n\nexport default class InvalidHostedFormValueError extends StandardError {\n constructor(public errors: HostedInputValidateErrorDataMap) {\n super(\n [\n 'Unable to proceed due to invalid user input values',\n ...flatMap(values(errors), (fieldErrors) =>\n map(fieldErrors, ({ message }) => message),\n ),\n ].join('. '),\n );\n\n this.name = 'InvalidHostedFormValueError';\n this.type = 'invalid_hosted_form_value';\n }\n}\n","import { CardInstrument } from '../payment/instrument';\n\nimport HostedFieldType from './hosted-field-type';\nimport { HostedFieldStylesMap } from './hosted-form-options';\nimport HostedFormOrderData from './hosted-form-order-data';\n\nexport enum HostedFieldEventType {\n AttachRequested = 'HOSTED_FIELD:ATTACH_REQUESTED',\n SubmitRequested = 'HOSTED_FIELD:SUBMITTED_REQUESTED',\n ValidateRequested = 'HOSTED_FIELD:VALIDATE_REQUESTED',\n}\n\nexport interface HostedFieldEventMap {\n [HostedFieldEventType.AttachRequested]: HostedFieldAttachEvent;\n [HostedFieldEventType.SubmitRequested]: HostedFieldSubmitRequestEvent;\n [HostedFieldEventType.ValidateRequested]: HostedFieldValidateRequestEvent;\n}\n\nexport type HostedFieldEvent =\n | HostedFieldAttachEvent\n | HostedFieldSubmitRequestEvent\n | HostedFieldValidateRequestEvent;\n\nexport interface HostedFieldAttachEvent {\n type: HostedFieldEventType.AttachRequested;\n payload: {\n accessibilityLabel?: string;\n cardInstrument?: CardInstrument;\n fontUrls?: string[];\n placeholder?: string;\n styles?: HostedFieldStylesMap;\n origin?: string;\n type: HostedFieldType;\n };\n}\n\nexport interface HostedFieldSubmitRequestEvent {\n type: HostedFieldEventType.SubmitRequested;\n payload: {\n data: HostedFormOrderData;\n fields: HostedFieldType[];\n };\n}\n\nexport interface HostedFieldValidateRequestEvent {\n type: HostedFieldEventType.ValidateRequested;\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport {\n PaymentErrorData,\n PaymentErrorResponseBody,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport HostedFieldType from '../hosted-field-type';\nimport { HostedFormErrorsData } from '../hosted-form-options';\n\nimport HostedInputInitializeErrorData from './hosted-input-initialize-error-data';\nimport HostedInputValidateResults from './hosted-input-validate-results';\n\n// Event types\nexport enum HostedInputEventType {\n AttachSucceeded = 'HOSTED_INPUT:ATTACH_SUCCEEDED',\n AttachFailed = 'HOSTED_INPUT:ATTACH_FAILED',\n BinChanged = 'HOSTED_INPUT:BIN_CHANGED',\n Blurred = 'HOSTED_INPUT:BLURRED',\n Changed = 'HOSTED_INPUT:CHANGED',\n CardTypeChanged = 'HOSTED_INPUT:CARD_TYPE_CHANGED',\n Entered = 'HOSTED_INPUT:ENTERED',\n Focused = 'HOSTED_INPUT:FOCUSED',\n SubmitSucceeded = 'HOSTED_INPUT:SUBMIT_SUCCEEDED',\n SubmitFailed = 'HOSTED_INPUT:SUBMIT_FAILED',\n Validated = 'HOSTED_INPUT:VALIDATED',\n}\n\n// Event mapping\nexport interface HostedInputEventMap {\n [HostedInputEventType.AttachSucceeded]: HostedInputAttachSuccessEvent;\n [HostedInputEventType.AttachFailed]: HostedInputAttachErrorEvent;\n [HostedInputEventType.BinChanged]: HostedInputBinChangeEvent;\n [HostedInputEventType.Blurred]: HostedInputBlurEvent;\n [HostedInputEventType.Changed]: HostedInputChangeEvent;\n [HostedInputEventType.CardTypeChanged]: HostedInputCardTypeChangeEvent;\n [HostedInputEventType.Entered]: HostedInputEnterEvent;\n [HostedInputEventType.Focused]: HostedInputFocusEvent;\n [HostedInputEventType.SubmitSucceeded]: HostedInputSubmitSuccessEvent;\n [HostedInputEventType.SubmitFailed]: HostedInputSubmitErrorEvent;\n [HostedInputEventType.Validated]: HostedInputValidateEvent;\n}\n\n// Events\nexport type HostedInputEvent =\n | HostedInputAttachSuccessEvent\n | HostedInputAttachErrorEvent\n | HostedInputBinChangeEvent\n | HostedInputBlurEvent\n | HostedInputChangeEvent\n | HostedInputCardTypeChangeEvent\n | HostedInputEnterEvent\n | HostedInputFocusEvent\n | HostedInputSubmitSuccessEvent\n | HostedInputSubmitErrorEvent\n | HostedInputValidateEvent;\n\nexport interface HostedInputAttachSuccessEvent {\n type: HostedInputEventType.AttachSucceeded;\n}\n\nexport interface HostedInputAttachErrorEvent {\n type: HostedInputEventType.AttachFailed;\n payload: {\n error: HostedInputInitializeErrorData;\n };\n}\n\nexport interface HostedInputBinChangeEvent {\n type: HostedInputEventType.BinChanged;\n payload: {\n bin?: string;\n };\n}\n\nexport interface HostedInputBlurEvent {\n type: HostedInputEventType.Blurred;\n payload: {\n fieldType: HostedFieldType;\n errors?: HostedFormErrorsData;\n };\n}\n\nexport interface HostedInputChangeEvent {\n type: HostedInputEventType.Changed;\n payload: {\n fieldType: HostedFieldType;\n };\n}\n\nexport interface HostedInputCardTypeChangeEvent {\n type: HostedInputEventType.CardTypeChanged;\n payload: {\n cardType?: string;\n };\n}\n\nexport interface HostedInputFocusEvent {\n type: HostedInputEventType.Focused;\n payload: {\n fieldType: HostedFieldType;\n };\n}\n\nexport interface HostedInputEnterEvent {\n type: HostedInputEventType.Entered;\n payload: {\n fieldType: HostedFieldType;\n };\n}\n\nexport interface HostedInputSubmitSuccessEvent {\n type: HostedInputEventType.SubmitSucceeded;\n payload: {\n response: Response;\n };\n}\n\nexport interface HostedInputSubmitErrorEvent {\n type: HostedInputEventType.SubmitFailed;\n payload: {\n error: PaymentErrorData;\n response?: Response;\n };\n}\n\nexport interface HostedInputValidateEvent {\n type: HostedInputEventType.Validated;\n payload: HostedInputValidateResults;\n}\n","import { values } from 'lodash';\nimport { fromEvent } from 'rxjs';\nimport { switchMap, take } from 'rxjs/operators';\n\nimport { DetachmentObserver } from '../common/dom';\nimport { mapFromPaymentErrorResponse } from '../common/error/errors';\nimport { IframeEventListener, IframeEventPoster } from '../common/iframe';\nimport { parseUrl } from '../common/url';\nimport { CardInstrument } from '../payment/instrument';\n\nimport {\n InvalidHostedFormConfigError,\n InvalidHostedFormError,\n InvalidHostedFormValueError,\n} from './errors';\nimport { HostedFieldEvent, HostedFieldEventType } from './hosted-field-events';\nimport HostedFieldType from './hosted-field-type';\nimport { HostedFieldStylesMap } from './hosted-form-options';\nimport HostedFormOrderData from './hosted-form-order-data';\nimport {\n HostedInputEventMap,\n HostedInputEventType,\n HostedInputSubmitErrorEvent,\n HostedInputSubmitSuccessEvent,\n HostedInputValidateEvent,\n} from './iframe-content';\n\nexport const RETRY_INTERVAL = 60 * 1000;\nexport const LAST_RETRY_KEY = 'lastRetry';\n\nexport default class HostedField {\n private _iframe: HTMLIFrameElement;\n\n constructor(\n private _type: HostedFieldType,\n private _containerId: string,\n private _placeholder: string,\n private _accessibilityLabel: string,\n private _styles: HostedFieldStylesMap,\n private _eventPoster: IframeEventPoster,\n private _eventListener: IframeEventListener,\n private _detachmentObserver: DetachmentObserver,\n private _cardInstrument?: CardInstrument,\n ) {\n this._iframe = document.createElement('iframe');\n\n this._iframe.src = `/checkout/payment/hosted-field?version=${LIBRARY_VERSION}`;\n this._iframe.style.border = 'none';\n this._iframe.style.height = '100%';\n this._iframe.style.overflow = 'hidden';\n this._iframe.style.width = '100%';\n }\n\n getType(): HostedFieldType {\n return this._type;\n }\n\n async attach(): Promise {\n const container = document.getElementById(this._containerId);\n\n if (!container) {\n throw new InvalidHostedFormConfigError(\n 'Unable to proceed because the provided container ID is not valid.',\n );\n }\n\n container.appendChild(this._iframe);\n this._eventListener.listen();\n\n const promise = fromEvent(this._iframe, 'load')\n .pipe(\n switchMap(async ({ target }) => {\n const contentWindow = target && (target as HTMLIFrameElement).contentWindow;\n\n if (!contentWindow) {\n throw new Error('The content window of the iframe cannot be accessed.');\n }\n\n this._eventPoster.setTarget(contentWindow);\n\n await this._eventPoster.post(\n {\n type: HostedFieldEventType.AttachRequested,\n payload: {\n accessibilityLabel: this._accessibilityLabel,\n cardInstrument: this._cardInstrument,\n fontUrls: this._getFontUrls(),\n placeholder: this._placeholder,\n styles: this._styles,\n origin: document.location.origin,\n type: this._type,\n },\n },\n {\n successType: HostedInputEventType.AttachSucceeded,\n errorType: HostedInputEventType.AttachFailed,\n },\n );\n }),\n take(1),\n )\n .toPromise();\n\n await this._detachmentObserver.ensurePresence([this._iframe], promise);\n }\n\n detach(): void {\n if (!this._iframe.parentElement) {\n return;\n }\n\n this._iframe.parentElement.removeChild(this._iframe);\n this._eventListener.stopListen();\n }\n\n async submitForm(\n fields: HostedFieldType[],\n data: HostedFormOrderData,\n ): Promise {\n try {\n const promise = this._eventPoster.post(\n {\n type: HostedFieldEventType.SubmitRequested,\n payload: { fields, data },\n },\n {\n successType: HostedInputEventType.SubmitSucceeded,\n errorType: HostedInputEventType.SubmitFailed,\n },\n );\n\n return await this._detachmentObserver.ensurePresence([this._iframe], promise);\n } catch (event) {\n if (this._isSubmitErrorEvent(event)) {\n if (event.payload.error.code === 'hosted_form_error') {\n throw new InvalidHostedFormError(event.payload.error.message);\n }\n\n if (event.payload.response) {\n throw mapFromPaymentErrorResponse(event.payload.response);\n }\n\n throw new Error(event.payload.error.message);\n }\n\n throw event;\n }\n }\n\n async validateForm(): Promise {\n const promise = this._eventPoster.post(\n {\n type: HostedFieldEventType.ValidateRequested,\n },\n {\n successType: HostedInputEventType.Validated,\n },\n );\n\n const { payload } = await this._detachmentObserver.ensurePresence([this._iframe], promise);\n\n if (!payload.isValid) {\n throw new InvalidHostedFormValueError(payload.errors);\n }\n }\n\n private _getFontUrls(): string[] {\n const hostname = 'fonts.googleapis.com';\n const links = document.querySelectorAll(`link[href*='${hostname}'][rel='stylesheet']`);\n\n return Array.prototype.slice\n .call(links)\n .filter((link) => parseUrl(link.href).hostname === hostname)\n .filter((link) =>\n values(this._styles)\n .map((style) => style && style.fontFamily)\n .filter((family): family is string => typeof family === 'string')\n .some((family) =>\n family\n .split(/,\\s/)\n .some((name) => link.href.indexOf(name.replace(' ', '+')) !== -1),\n ),\n )\n .map((link) => link.href);\n }\n\n private _isSubmitErrorEvent(event: any): event is HostedInputSubmitErrorEvent {\n return event.type === HostedInputEventType.SubmitFailed;\n }\n}\n","import { noop, without } from 'lodash';\n\nimport { HostedForm as HostedFormInterface } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { IframeEventListener } from '../common/iframe';\nimport { OrderPaymentRequestBody } from '../order';\nimport { PaymentAdditionalAction } from '../payment';\nimport { PaymentHumanVerificationHandler } from '../spam-protection';\n\nimport { InvalidHostedFormConfigError } from './errors';\nimport HostedField from './hosted-field';\nimport HostedFormOptions from './hosted-form-options';\nimport HostedFormOrderDataTransformer from './hosted-form-order-data-transformer';\nimport {\n HostedInputEnterEvent,\n HostedInputEventMap,\n HostedInputEventType,\n HostedInputSubmitSuccessEvent,\n} from './iframe-content';\n\ntype HostedFormEventCallbacks = Pick<\n HostedFormOptions,\n 'onBlur' | 'onCardTypeChange' | 'onFocus' | 'onEnter' | 'onValidate'\n>;\n\nexport default class HostedForm implements HostedFormInterface {\n private _bin?: string;\n private _cardType?: string;\n\n constructor(\n private _fields: HostedField[],\n private _eventListener: IframeEventListener,\n private _payloadTransformer: HostedFormOrderDataTransformer,\n private _eventCallbacks: HostedFormEventCallbacks,\n private _paymentHumanVerificationHandler: PaymentHumanVerificationHandler,\n ) {\n const {\n onBlur = noop,\n onCardTypeChange = noop,\n onFocus = noop,\n onValidate = noop,\n } = this._eventCallbacks;\n\n this._eventListener.addListener(HostedInputEventType.Blurred, ({ payload }) =>\n onBlur(payload),\n );\n this._eventListener.addListener(HostedInputEventType.CardTypeChanged, ({ payload }) =>\n onCardTypeChange(payload),\n );\n this._eventListener.addListener(HostedInputEventType.Focused, ({ payload }) =>\n onFocus(payload),\n );\n this._eventListener.addListener(HostedInputEventType.Validated, ({ payload }) =>\n onValidate(payload),\n );\n this._eventListener.addListener(HostedInputEventType.Entered, this._handleEnter);\n\n this._eventListener.addListener(\n HostedInputEventType.CardTypeChanged,\n ({ payload }) => (this._cardType = payload.cardType),\n );\n this._eventListener.addListener(\n HostedInputEventType.BinChanged,\n ({ payload }) => (this._bin = payload.bin),\n );\n }\n\n getBin(): string | undefined {\n return this._bin;\n }\n\n getCardType(): string | undefined {\n return this._cardType;\n }\n\n async attach(): Promise {\n this._eventListener.listen();\n\n const field = this._getFirstField();\n const otherFields = without(this._fields, field);\n\n await field.attach();\n await Promise.all(otherFields.map((otherField) => otherField.attach()));\n }\n\n detach(): void {\n this._eventListener.stopListen();\n\n this._fields.forEach((field) => {\n field.detach();\n });\n }\n\n async submit(\n payload: OrderPaymentRequestBody,\n additionalActionData?: PaymentAdditionalAction,\n ): Promise {\n try {\n return await this._getFirstField().submitForm(\n this._fields.map((field) => field.getType()),\n this._payloadTransformer.transform(payload, additionalActionData),\n );\n } catch (error) {\n const additionalAction = await this._paymentHumanVerificationHandler.handle(error);\n\n return await this._getFirstField().submitForm(\n this._fields.map((field) => field.getType()),\n this._payloadTransformer.transform(payload, additionalAction),\n );\n }\n }\n\n async validate(): Promise {\n return this._getFirstField().validateForm();\n }\n\n private _getFirstField(): HostedField {\n const field = this._fields[0];\n\n if (!field) {\n throw new InvalidHostedFormConfigError(\n 'Unable to proceed because the payment form has no field defined.',\n );\n }\n\n return field;\n }\n\n private _handleEnter: (event: HostedInputEnterEvent) => Promise = async ({ payload }) => {\n try {\n await this.validate();\n } catch (error) {\n // Catch form validation error because we want to trigger `onEnter`\n // irrespective of the validation result.\n if (error.name !== 'InvalidHostedFormValueError') {\n throw error;\n }\n }\n\n const { onEnter = noop } = this._eventCallbacks;\n\n onEnter(payload);\n };\n}\n","import {\n FormattedPayload,\n FormattedVaultedInstrument,\n HostedVaultedInstrument,\n PaymentInstrument,\n VaultedInstrument,\n} from './payment';\n\nexport default function isVaultedInstrument(\n instrument: PaymentInstrument,\n): instrument is VaultedInstrument {\n return Boolean((instrument as VaultedInstrument).instrumentId);\n}\n\nexport function isHostedVaultedInstrument(\n instrument: PaymentInstrument,\n): instrument is HostedVaultedInstrument {\n return (\n Boolean((instrument as HostedVaultedInstrument).instrumentId) &&\n !Object.prototype.hasOwnProperty.call(instrument, 'ccNumber') &&\n !Object.prototype.hasOwnProperty.call(instrument, 'ccCvv')\n );\n}\n\nexport function isFormattedVaultedInstrument(\n instrument: PaymentInstrument,\n): instrument is FormattedPayload {\n const formattedInstrument = (instrument as FormattedPayload)\n .formattedPayload;\n\n if (!formattedInstrument) {\n return false;\n }\n\n return (\n typeof formattedInstrument.bigpay_token === 'string' ||\n Boolean(formattedInstrument.bigpay_token && formattedInstrument.bigpay_token.token)\n );\n}\n","import { omit } from 'lodash';\n\nimport { ReadableCheckoutStore } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { OrderPaymentRequestBody } from '../order';\nimport {\n HostedCreditCardInstrument,\n isVaultedInstrument,\n PaymentAdditionalAction,\n} from '../payment';\n\nimport HostedFormOrderData from './hosted-form-order-data';\n\nexport default class HostedFormOrderDataTransformer {\n constructor(private _store: ReadableCheckoutStore) {}\n\n transform(\n payload: OrderPaymentRequestBody,\n additionalAction?: PaymentAdditionalAction,\n ): HostedFormOrderData {\n const state = this._store.getState();\n const checkout = state.checkout.getCheckout();\n const config = state.config.getConfig();\n const instrumentMeta = state.instruments.getInstrumentsMeta();\n const order = state.order.getOrder();\n const orderMeta = state.order.getOrderMeta();\n const payment = omit(\n payload.paymentData,\n 'ccExpiry',\n 'ccName',\n 'ccNumber',\n 'ccCvv',\n ) as HostedCreditCardInstrument;\n const paymentMethod = state.paymentMethods.getPaymentMethod(\n payload.methodId,\n payload.gatewayId,\n );\n const paymentMethodMeta = state.paymentMethods.getPaymentMethodsMeta();\n const authToken =\n instrumentMeta && payment && isVaultedInstrument(payment)\n ? `${state.payment.getPaymentToken()}, ${instrumentMeta.vaultAccessToken}`\n : state.payment.getPaymentToken();\n\n if (!authToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n return {\n additionalAction,\n authToken,\n checkout,\n config,\n order,\n orderMeta,\n payment,\n paymentMethod,\n paymentMethodMeta,\n };\n }\n}\n","import { createScriptLoader } from '@bigcommerce/script-loader';\nimport { pick } from 'lodash';\n\nimport { ReadableCheckoutStore } from '../checkout';\nimport { DetachmentObserver, MutationObserverFactory } from '../common/dom';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { IframeEventListener, IframeEventPoster } from '../common/iframe';\nimport { CardInstrument } from '../payment/instrument';\nimport { createSpamProtection, PaymentHumanVerificationHandler } from '../spam-protection';\n\nimport HostedField from './hosted-field';\nimport HostedFieldType from './hosted-field-type';\nimport HostedForm from './hosted-form';\nimport HostedFormOptions, {\n HostedCardFieldOptionsMap,\n HostedStoredCardFieldOptionsMap,\n} from './hosted-form-options';\nimport HostedFormOrderDataTransformer from './hosted-form-order-data-transformer';\n\nexport default class HostedFormFactory {\n constructor(private _store: ReadableCheckoutStore) {}\n\n create(host: string, options: HostedFormOptions): HostedForm {\n const fieldTypes = Object.keys(options.fields) as HostedFieldType[];\n const fields = fieldTypes.reduce((result, type) => {\n const fields = options.fields as HostedStoredCardFieldOptionsMap &\n HostedCardFieldOptionsMap;\n const fieldOptions = fields[type];\n\n if (!fieldOptions) {\n return result;\n }\n\n return [\n ...result,\n new HostedField(\n type,\n fieldOptions.containerId,\n fieldOptions.placeholder || '',\n fieldOptions.accessibilityLabel || '',\n options.styles || {},\n new IframeEventPoster(host),\n new IframeEventListener(host),\n new DetachmentObserver(new MutationObserverFactory()),\n 'instrumentId' in fieldOptions\n ? this._getCardInstrument(fieldOptions.instrumentId)\n : undefined,\n ),\n ];\n }, []);\n\n return new HostedForm(\n fields,\n new IframeEventListener(host),\n new HostedFormOrderDataTransformer(this._store),\n pick(options, 'onBlur', 'onEnter', 'onFocus', 'onCardTypeChange', 'onValidate'),\n new PaymentHumanVerificationHandler(createSpamProtection(createScriptLoader())),\n );\n }\n\n private _getCardInstrument(instrumentId: string): CardInstrument {\n const {\n instruments: { getCardInstrument },\n } = this._store.getState();\n const instrument = getCardInstrument(instrumentId);\n\n if (!instrument) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentInstrument);\n }\n\n return instrument;\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if the shopper chooses not to complete the spam check.\n */\nexport default class SpamProtectionNotCompletedError extends StandardError {\n constructor() {\n super(\"You haven't complete our spam check. Please try again.\");\n\n this.name = 'SpamProtectionNotCompletedError';\n this.type = 'spam_protection_not_completed';\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { InternalOrderResponseData } from './internal-order-responses';\nimport Order from './order';\n\nexport enum OrderActionType {\n LoadOrderRequested = 'LOAD_ORDER_REQUESTED',\n LoadOrderSucceeded = 'LOAD_ORDER_SUCCEEDED',\n LoadOrderFailed = 'LOAD_ORDER_FAILED',\n\n LoadOrderPaymentsRequested = 'LOAD_ORDER_PAYMENTS_REQUESTED',\n LoadOrderPaymentsSucceeded = 'LOAD_ORDER_PAYMENTS_SUCCEEDED',\n LoadOrderPaymentsFailed = 'LOAD_ORDER_PAYMENTS_FAILED',\n\n SubmitOrderRequested = 'SUBMIT_ORDER_REQUESTED',\n SubmitOrderSucceeded = 'SUBMIT_ORDER_SUCCEEDED',\n SubmitOrderFailed = 'SUBMIT_ORDER_FAILED',\n\n FinalizeOrderRequested = 'FINALIZE_ORDER_REQUESTED',\n FinalizeOrderSucceeded = 'FINALIZE_ORDER_SUCCEEDED',\n FinalizeOrderFailed = 'FINALIZE_ORDER_FAILED',\n}\n\nexport type OrderAction =\n | LoadOrderAction\n | LoadOrderPaymentsAction\n | SubmitOrderAction\n | FinalizeOrderAction;\n\nexport type LoadOrderPaymentsAction =\n | LoadOrderPaymentsRequestedAction\n | LoadOrderPaymentsSucceededAction\n | LoadOrderPaymentsFailedAction;\n\nexport type LoadOrderAction =\n | LoadOrderRequestedAction\n | LoadOrderSucceededAction\n | LoadOrderFailedAction;\n\nexport type SubmitOrderAction =\n | SubmitOrderRequestedAction\n | SubmitOrderSucceededAction\n | SubmitOrderFailedAction\n | LoadOrderAction;\n\nexport type FinalizeOrderAction =\n | FinalizeOrderRequestedAction\n | FinalizeOrderSucceededAction\n | FinalizeOrderFailedAction\n | LoadOrderAction;\n\nexport interface LoadOrderRequestedAction extends Action {\n type: OrderActionType.LoadOrderRequested;\n}\n\nexport interface LoadOrderSucceededAction extends Action {\n type: OrderActionType.LoadOrderSucceeded;\n}\n\nexport interface LoadOrderFailedAction extends Action {\n type: OrderActionType.LoadOrderFailed;\n}\n\nexport interface LoadOrderPaymentsRequestedAction extends Action {\n type: OrderActionType.LoadOrderPaymentsRequested;\n}\n\nexport interface LoadOrderPaymentsSucceededAction extends Action {\n type: OrderActionType.LoadOrderPaymentsSucceeded;\n}\n\nexport interface LoadOrderPaymentsFailedAction extends Action {\n type: OrderActionType.LoadOrderPaymentsFailed;\n}\n\nexport interface SubmitOrderRequestedAction extends Action {\n type: OrderActionType.SubmitOrderRequested;\n}\n\nexport interface SubmitOrderSucceededAction extends Action {\n type: OrderActionType.SubmitOrderSucceeded;\n}\n\nexport interface SubmitOrderFailedAction extends Action {\n type: OrderActionType.SubmitOrderFailed;\n}\n\nexport interface FinalizeOrderRequestedAction extends Action {\n type: OrderActionType.FinalizeOrderRequested;\n}\n\nexport interface FinalizeOrderSucceededAction extends Action {\n type: OrderActionType.FinalizeOrderSucceeded;\n}\n\nexport interface FinalizeOrderFailedAction extends Action {\n type: OrderActionType.FinalizeOrderFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, from, Observable, Observer, of } from 'rxjs';\nimport { catchError, switchMap } from 'rxjs/operators';\n\nimport { CheckoutValidator, InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\nimport { SpamProtectionNotCompletedError } from '../spam-protection/errors';\n\nimport InternalOrderRequestBody from './internal-order-request-body';\nimport {\n FinalizeOrderAction,\n LoadOrderAction,\n LoadOrderPaymentsAction,\n OrderActionType,\n SubmitOrderAction,\n} from './order-actions';\nimport OrderRequestBody from './order-request-body';\nimport OrderRequestSender from './order-request-sender';\n\nexport default class OrderActionCreator {\n constructor(\n private _orderRequestSender: OrderRequestSender,\n private _checkoutValidator: CheckoutValidator,\n ) {}\n\n loadOrder(orderId: number, options?: RequestOptions): Observable {\n return new Observable((observer: Observer) => {\n observer.next(createAction(OrderActionType.LoadOrderRequested));\n\n this._orderRequestSender\n .loadOrder(orderId, options)\n .then((response) => {\n observer.next(createAction(OrderActionType.LoadOrderSucceeded, response.body));\n observer.complete();\n })\n .catch((response) => {\n observer.error(createErrorAction(OrderActionType.LoadOrderFailed, response));\n });\n });\n }\n\n // TODO: Remove when checkout does not contain unrelated order data.\n loadOrderPayments(\n orderId: number,\n options?: RequestOptions,\n ): Observable {\n return new Observable((observer: Observer) => {\n observer.next(createAction(OrderActionType.LoadOrderPaymentsRequested));\n\n this._orderRequestSender\n .loadOrder(orderId, options)\n .then((response) => {\n observer.next(\n createAction(OrderActionType.LoadOrderPaymentsSucceeded, response.body),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(OrderActionType.LoadOrderPaymentsFailed, response),\n );\n });\n });\n }\n\n loadCurrentOrder(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n defer(() => {\n const orderId = this._getCurrentOrderId(store.getState());\n\n if (!orderId) {\n throw new MissingDataError(MissingDataErrorType.MissingOrderId);\n }\n\n return this.loadOrder(orderId, options);\n });\n }\n\n submitOrder(\n payload?: OrderRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(OrderActionType.SubmitOrderRequested)),\n defer(() => {\n const state = store.getState();\n const externalSource = state.config.getExternalSource();\n const variantIdentificationToken = state.config.getVariantIdentificationToken();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (checkout.shouldExecuteSpamCheck) {\n throw new SpamProtectionNotCompletedError();\n }\n\n return from(\n this._checkoutValidator.validate(checkout, options).then(() =>\n this._orderRequestSender.submitOrder(\n this._mapToOrderRequestBody(\n payload ?? {},\n checkout.id,\n checkout.customerMessage,\n externalSource,\n ),\n {\n ...options,\n headers: {\n checkoutVariant: variantIdentificationToken,\n },\n },\n ),\n ),\n ).pipe(\n switchMap((response) =>\n concat(\n // TODO: Remove once we can submit orders using storefront API\n this.loadOrder(response.body.data.order.orderId, options),\n of(\n createAction(\n OrderActionType.SubmitOrderSucceeded,\n response.body.data,\n { ...response.body.meta, token: response.headers.token },\n ),\n ),\n ),\n ),\n );\n }).pipe(\n catchError((error) =>\n throwErrorAction(OrderActionType.SubmitOrderFailed, error),\n ),\n ),\n );\n }\n\n finalizeOrder(\n orderId: number,\n options?: RequestOptions,\n ): Observable {\n return concat(\n of(createAction(OrderActionType.FinalizeOrderRequested)),\n from(this._orderRequestSender.finalizeOrder(orderId, options)).pipe(\n switchMap((response) =>\n concat(\n this.loadOrder(orderId, options),\n of(\n createAction(\n OrderActionType.FinalizeOrderSucceeded,\n response.body.data,\n ),\n ),\n ),\n ),\n ),\n ).pipe(catchError((error) => throwErrorAction(OrderActionType.FinalizeOrderFailed, error)));\n }\n\n private _getCurrentOrderId(state: InternalCheckoutSelectors): number | undefined {\n const order = state.order.getOrder();\n const checkout = state.checkout.getCheckout();\n\n return (order && order.orderId) || (checkout && checkout.orderId);\n }\n\n private _mapToOrderRequestBody(\n payload: OrderRequestBody,\n cartId: string,\n customerMessage: string,\n externalSource?: string,\n ): InternalOrderRequestBody {\n const { payment, ...order } = payload;\n\n if (!payment) {\n return {\n ...order,\n cartId,\n customerMessage,\n externalSource,\n };\n }\n\n return {\n ...order,\n cartId,\n customerMessage,\n externalSource,\n payment: {\n paymentData: payment.paymentData,\n name: payment.methodId,\n gateway: payment.gatewayId,\n },\n };\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error is thrown when the server detects inconsistency in cart data since it is last requested,\n * for example, product prices or eligible discounts have changed.\n */\nexport default class CartConsistencyError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Your checkout could not be processed because some details have changed. Please review your order and try again.',\n );\n\n this.name = 'CartConsistencyError';\n this.type = 'cart_consistency';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Checkout prevents consumers from placing their orders when a merchant wishes\n * to be able to block transactions if the automated tax provider cannot be reached.\n */\nexport default class OrderTaxProviderUnavailableError extends StandardError {\n constructor(message?: string) {\n super(message || 'The tax provider is unavailable.');\n\n this.name = 'OrderTaxProviderUnavailableError';\n this.type = 'tax_provider_unavailable';\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\nimport { isNil, omitBy } from 'lodash';\n\nimport { CartConsistencyError } from '../cart/errors';\nimport {\n ContentType,\n joinIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport { OrderTaxProviderUnavailableError } from './errors';\nimport InternalOrderRequestBody from './internal-order-request-body';\nimport { InternalOrderResponseBody } from './internal-order-responses';\nimport Order from './order';\n\nexport interface SubmitOrderRequestOptions extends RequestOptions {\n headers?: {\n checkoutVariant?: string;\n };\n}\n\nexport default class OrderRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n loadOrder(orderId: number, { timeout }: RequestOptions = {}): Promise> {\n const url = `/api/storefront/orders/${orderId}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n const include = [\n 'payments',\n 'lineItems.physicalItems.socialMedia',\n 'lineItems.physicalItems.options',\n 'lineItems.physicalItems.categories',\n 'lineItems.digitalItems.socialMedia',\n 'lineItems.digitalItems.options',\n 'lineItems.digitalItems.categories',\n ];\n\n return this._requestSender.get(url, {\n params: {\n include: joinIncludes(include),\n },\n headers,\n timeout,\n });\n }\n\n submitOrder(\n body?: InternalOrderRequestBody,\n { headers, timeout }: SubmitOrderRequestOptions = {},\n ): Promise> {\n const url = '/internalapi/v1/checkout/order';\n\n return this._requestSender\n .post(url, {\n body,\n headers: omitBy(\n {\n 'X-Checkout-Variant': headers && headers.checkoutVariant,\n ...SDK_VERSION_HEADERS,\n },\n isNil,\n ),\n timeout,\n })\n .catch((error) => {\n if (error.body.type === 'tax_provider_unavailable') {\n throw new OrderTaxProviderUnavailableError();\n }\n\n if (error.body.type === 'cart_has_changed') {\n throw new CartConsistencyError();\n }\n\n throw error;\n });\n }\n\n finalizeOrder(\n orderId: number,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/internalapi/v1/checkout/order/${orderId}`;\n\n return this._requestSender.post(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { LoadOrderAction } from '../order';\n\nimport PaymentResponseBody from './payment-response-body';\n\nexport enum PaymentActionType {\n SubmitPaymentRequested = 'SUBMIT_PAYMENT_REQUESTED',\n SubmitPaymentSucceeded = 'SUBMIT_PAYMENT_SUCCEEDED',\n SubmitPaymentFailed = 'SUBMIT_PAYMENT_FAILED',\n\n InitializeOffsitePaymentRequested = 'INITIALIZE_OFFSITE_PAYMENT_REQUESTED',\n InitializeOffsitePaymentSucceeded = 'INITIALIZE_OFFSITE_PAYMENT_SUCCEEDED',\n InitializeOffsitePaymentFailed = 'INITIALIZE_OFFSITE_PAYMENT_FAILED',\n}\n\nexport type PaymentAction = SubmitPaymentAction | InitializeOffsitePaymentAction;\n\nexport type SubmitPaymentAction =\n | SubmitPaymentRequestedAction\n | SubmitPaymentSucceededAction\n | SubmitPaymentFailedAction\n | LoadOrderAction;\n\nexport type InitializeOffsitePaymentAction =\n | InitializeOffsitePaymentRequestedAction\n | InitializeOffsitePaymentSucceededAction\n | InitializeOffsitePaymentFailedAction;\n\nexport interface SubmitPaymentRequestedAction extends Action {\n type: PaymentActionType.SubmitPaymentRequested;\n}\n\nexport interface SubmitPaymentSucceededAction extends Action {\n type: PaymentActionType.SubmitPaymentSucceeded;\n}\n\nexport interface SubmitPaymentFailedAction extends Action {\n type: PaymentActionType.SubmitPaymentFailed;\n}\n\nexport interface InitializeOffsitePaymentRequestedAction extends Action {\n type: PaymentActionType.InitializeOffsitePaymentRequested;\n}\n\nexport interface InitializeOffsitePaymentSucceededAction extends Action {\n type: PaymentActionType.InitializeOffsitePaymentSucceeded;\n}\n\nexport interface InitializeOffsitePaymentFailedAction extends Action {\n type: PaymentActionType.InitializeOffsitePaymentFailed;\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, of } from 'rxjs';\nimport { catchError, switchMap } from 'rxjs/operators';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { OrderActionCreator } from '../order';\nimport { PaymentHumanVerificationHandler } from '../spam-protection';\n\nimport Payment, {\n FormattedHostedInstrument,\n FormattedPayload,\n FormattedVaultedInstrument,\n} from './payment';\nimport {\n InitializeOffsitePaymentAction,\n PaymentActionType,\n SubmitPaymentAction,\n} from './payment-actions';\nimport PaymentRequestSender from './payment-request-sender';\nimport PaymentRequestTransformer from './payment-request-transformer';\n\ninterface InitializeOffsitePaymentSettings {\n methodId: string;\n gatewayId?: string;\n instrumentId?: string;\n target?: string;\n promise?: Promise;\n shouldSaveInstrument?: boolean;\n shouldSetAsDefaultInstrument?: boolean;\n}\n\ntype InitializeOffsitePayment = (\n settings: InitializeOffsitePaymentSettings,\n) => ThunkAction;\n\nexport default class PaymentActionCreator {\n constructor(\n private _paymentRequestSender: PaymentRequestSender,\n private _orderActionCreator: OrderActionCreator,\n private _paymentRequestTransformer: PaymentRequestTransformer,\n private _paymentHumanVerificationHandler: PaymentHumanVerificationHandler,\n ) {}\n\n submitPayment(payment: Payment): ThunkAction {\n return (store) =>\n concat(\n of(createAction(PaymentActionType.SubmitPaymentRequested)),\n defer(async () => {\n try {\n return await this._paymentRequestSender.submitPayment(\n this._paymentRequestTransformer.transform(payment, store.getState()),\n );\n } catch (error) {\n const additionalAction = await this._paymentHumanVerificationHandler.handle(\n error,\n );\n\n return await this._paymentRequestSender.submitPayment(\n this._paymentRequestTransformer.transform(\n { ...payment, additionalAction },\n store.getState(),\n ),\n );\n }\n }).pipe(\n switchMap(({ body }) =>\n concat(\n this._orderActionCreator.loadCurrentOrder()(store),\n of(createAction(PaymentActionType.SubmitPaymentSucceeded, body)),\n ),\n ),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(PaymentActionType.SubmitPaymentFailed, error),\n ),\n );\n }\n\n initializeOffsitePayment: InitializeOffsitePayment = ({\n methodId,\n gatewayId,\n instrumentId,\n target,\n promise,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n }) => {\n return (store) => {\n let paymentData:\n | FormattedPayload\n | undefined;\n\n if (instrumentId) {\n paymentData = { formattedPayload: { bigpay_token: instrumentId } };\n } else if (shouldSaveInstrument) {\n paymentData = {\n formattedPayload: {\n vault_payment_instrument: shouldSaveInstrument,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n },\n };\n }\n\n const payload = this._paymentRequestTransformer.transform(\n { gatewayId, methodId, paymentData },\n store.getState(),\n );\n\n return concat(\n of(createAction(PaymentActionType.InitializeOffsitePaymentRequested)),\n Promise.race(\n [\n this._paymentRequestSender.initializeOffsitePayment(payload, target),\n promise,\n ].filter(Boolean),\n ).then(() => createAction(PaymentActionType.InitializeOffsitePaymentSucceeded)),\n ).pipe(\n catchError((error) =>\n throwErrorAction(PaymentActionType.InitializeOffsitePaymentFailed, error),\n ),\n );\n };\n };\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport PaymentRequestBody from './payment-request-body';\n\n/**\n * @todo Convert this file into TypeScript properly\n */\nexport default class PaymentRequestSender {\n /**\n * @class\n * @param {BigpayClient} client\n */\n constructor(private _client: any) {}\n\n submitPayment(payload: PaymentRequestBody): Promise> {\n return new Promise((resolve, reject) => {\n this._client.submitPayment(payload, (error: any, response: any) => {\n if (error) {\n reject(this._transformResponse(error));\n } else {\n resolve(this._transformResponse(response));\n }\n });\n });\n }\n\n initializeOffsitePayment(payload: PaymentRequestBody, target?: string): Promise {\n return new Promise(() => {\n this._client.initializeOffsitePayment(payload, null, target);\n });\n }\n\n private _transformResponse(response: any): Response {\n return {\n headers: response.headers,\n body: response.data,\n status: response.status,\n statusText: response.statusText,\n };\n }\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@bigcommerce/bigpay-client\");","// / \nimport { createClient as createBigpayClient } from '@bigcommerce/bigpay-client';\n\nimport { CheckoutStore } from '../checkout';\n\nexport default function createPaymentClient(store: CheckoutStore) {\n const paymentClient = createBigpayClient();\n\n store.subscribe(\n (state) => {\n const config = state.config.getStoreConfig();\n\n if (config) {\n paymentClient.setHost(config.paymentSettings.bigpayBaseUrl);\n }\n },\n (state) => state.config.getStoreConfig(),\n );\n\n return paymentClient;\n}\n","import { Address } from '../address';\n\nimport BillingAddress from './billing-address';\n\nexport default function isBillingAddressLike(address: Address): address is BillingAddress {\n const billingAddress = address as BillingAddress;\n\n return typeof billingAddress.id !== 'undefined';\n}\n","import { BillingAddress, isBillingAddressLike } from '../billing';\nimport { Consignment } from '../shipping';\n\nimport Address from './address';\nimport InternalAddress from './internal-address';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalAddress(\n address: Address | BillingAddress,\n consignments?: Consignment[],\n): InternalAddress {\n let addressId;\n\n if (isBillingAddressLike(address)) {\n addressId = address.id;\n } else if (consignments && consignments.length) {\n addressId = consignments[0].id;\n }\n\n return {\n id: addressId,\n firstName: address.firstName,\n lastName: address.lastName,\n company: address.company,\n addressLine1: address.address1,\n addressLine2: address.address2,\n city: address.city,\n province: address.stateOrProvince,\n provinceCode: address.stateOrProvinceCode,\n postCode: address.postalCode,\n country: address.country,\n countryCode: address.countryCode,\n phone: address.phone,\n customFields: address.customFields,\n };\n}\n","export default class AmountTransformer {\n constructor(private _decimalPlaces: number) {}\n\n toInteger(amount: number): number {\n return Math.round(amount * Math.pow(10, this._decimalPlaces));\n }\n}\n","import Coupon from './coupon';\nimport InternalCoupon from './internal-coupon';\n\nconst couponTypes = [\n 'per_item_discount',\n 'percentage_discount',\n 'per_total_discount',\n 'shipping_discount',\n 'free_shipping',\n];\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalCoupon(coupon: Coupon): InternalCoupon {\n return {\n code: coupon.code,\n discount: coupon.displayName,\n discountType: couponTypes.indexOf(coupon.couponType),\n };\n}\n","enum CheckoutButtonMethodType {\n APPLEPAY = \"applepay\",\n AMAZON_PAY_V2 = \"amazonpay\",\n BRAINTREE_PAYPAL = \"braintreepaypal\",\n BRAINTREE_VENMO = \"braintreevenmo\",\n BRAINTREE_PAYPAL_CREDIT = \"braintreepaypalcredit\",\n GOOGLEPAY_ADYENV2 = \"googlepayadyenv2\",\n GOOGLEPAY_ADYENV3 = \"googlepayadyenv3\",\n GOOGLEPAY_AUTHORIZENET = \"googlepayauthorizenet\",\n GOOGLEPAY_BNZ = \"googlepaybnz\",\n GOOGLEPAY_BRAINTREE = \"googlepaybraintree\",\n GOOGLEPAY_CHECKOUTCOM = \"googlepaycheckoutcom\",\n GOOGLEPAY_CYBERSOURCEV2 = \"googlepaycybersourcev2\",\n GOOGLEPAY_ORBITAL = \"googlepayorbital\",\n GOOGLEPAY_STRIPE = \"googlepaystripe\",\n GOOGLEPAY_STRIPEUPE = \"googlepaystripeupe\",\n GOOGLEPAY_WORLDPAYACCESS = \"googlepayworldpayaccess\",\n MASTERPASS = \"masterpass\",\n PAYPALEXPRESS = \"paypalexpress\"\n}\nexport default CheckoutButtonMethodType;\n\n","import GiftCertificate from './gift-certificate';\nimport InternalGiftCertificate from './internal-gift-certificate';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalGiftCertificate(\n giftCertificate: GiftCertificate,\n): InternalGiftCertificate {\n return {\n code: giftCertificate.code,\n discountedAmount: giftCertificate.used,\n remainingBalance: giftCertificate.remaining,\n giftCertificate: {\n balance: giftCertificate.balance,\n code: giftCertificate.code,\n purchaseDate: giftCertificate.purchaseDate,\n },\n };\n}\n","import InternalLineItem from './internal-line-item';\nimport { LineItem } from './line-item';\nimport LineItemMap from './line-item-map';\nimport mapGiftCertificateToInternalLineItem from './map-gift-certificate-to-internal-line-item';\nimport mapToInternalLineItem from './map-to-internal-line-item';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalLineItems(\n itemMap: LineItemMap,\n decimalPlaces: number,\n idKey: keyof LineItem = 'id',\n): InternalLineItem[] {\n return (Object.keys(itemMap) as Array).reduce(\n (result, key) => [\n ...result,\n ...(itemMap[key] as LineItem[]).map((item: any) => {\n if (key === 'giftCertificates') {\n return mapGiftCertificateToInternalLineItem(item, decimalPlaces);\n }\n\n return mapToInternalLineItem(\n item,\n mapToInternalLineItemType(key),\n decimalPlaces,\n idKey,\n );\n }),\n ],\n [] as InternalLineItem[],\n );\n}\n\nfunction mapToInternalLineItemType(type: string): string {\n switch (type) {\n case 'physicalItems':\n return 'ItemPhysicalEntity';\n\n case 'digitalItems':\n return 'ItemDigitalEntity';\n\n case 'giftCertificates':\n return 'ItemGiftCertificateEntity';\n\n default:\n return '';\n }\n}\n","import { AmountTransformer } from '../common/utility';\n\nimport InternalLineItem from './internal-line-item';\nimport { GiftCertificateItem } from './line-item';\n\nexport default function mapGiftCertificateToInternalLineItem(\n item: GiftCertificateItem,\n decimalPlaces: number,\n): InternalLineItem {\n const amountTransformer = new AmountTransformer(decimalPlaces);\n\n return {\n id: item.id,\n imageUrl: '',\n name: item.name,\n amount: item.amount,\n amountAfterDiscount: item.amount,\n discount: 0,\n integerAmount: amountTransformer.toInteger(item.amount),\n integerAmountAfterDiscount: amountTransformer.toInteger(item.amount),\n integerUnitPrice: amountTransformer.toInteger(item.amount),\n integerUnitPriceAfterDiscount: amountTransformer.toInteger(item.amount),\n integerDiscount: 0,\n quantity: 1,\n sender: item.sender,\n recipient: item.recipient,\n type: 'ItemGiftCertificateEntity',\n attributes: [],\n variantId: null,\n };\n}\n","import { AmountTransformer } from '../common/utility';\n\nimport InternalLineItem from './internal-line-item';\nimport { DigitalItem, LineItem } from './line-item';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalLineItem(\n item: LineItem,\n type: string,\n decimalPlaces: number,\n idKey: keyof LineItem = 'id',\n): InternalLineItem {\n const amountTransformer = new AmountTransformer(decimalPlaces);\n\n return {\n id: item[idKey] as string | number,\n imageUrl: item.imageUrl,\n amount: item.extendedListPrice,\n amountAfterDiscount: item.extendedSalePrice,\n discount: item.discountAmount,\n integerAmount: amountTransformer.toInteger(item.extendedListPrice),\n integerAmountAfterDiscount: amountTransformer.toInteger(item.extendedSalePrice),\n integerDiscount: amountTransformer.toInteger(item.discountAmount),\n integerUnitPrice: amountTransformer.toInteger(item.listPrice),\n integerUnitPriceAfterDiscount: amountTransformer.toInteger(item.salePrice),\n downloadsPageUrl: (item as DigitalItem).downloadPageUrl,\n name: item.name,\n quantity: item.quantity,\n brand: item.brand,\n sku: item.sku,\n categoryNames: item.categoryNames,\n variantId: item.variantId,\n productId: item.productId,\n attributes: (item.options || []).map((option) => ({\n name: option.name,\n value: option.value,\n })),\n addedByPromotion: item.addedByPromotion,\n type,\n };\n}\n","import { keyBy, reduce, some } from 'lodash';\n\nimport { Checkout } from '../checkout';\nimport { AmountTransformer } from '../common/utility';\nimport { mapToInternalCoupon, mapToInternalGiftCertificate } from '../coupon';\nimport { mapToDiscountNotifications } from '../promotion';\n\nimport InternalCart from './internal-cart';\nimport mapToInternalLineItems from './map-to-internal-line-items';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalCart(checkout: Checkout): InternalCart {\n const decimalPlaces = checkout.cart.currency.decimalPlaces;\n const amountTransformer = new AmountTransformer(decimalPlaces);\n\n return {\n id: checkout.cart.id,\n items: mapToInternalLineItems(checkout.cart.lineItems, decimalPlaces),\n currency: checkout.cart.currency.code,\n coupon: {\n discountedAmount: reduce(\n checkout.cart.coupons,\n (sum, coupon) => {\n return sum + coupon.discountedAmount;\n },\n 0,\n ),\n coupons: checkout.cart.coupons.map(mapToInternalCoupon),\n },\n discount: {\n amount: checkout.cart.discountAmount,\n integerAmount: amountTransformer.toInteger(checkout.cart.discountAmount),\n },\n discountNotifications: mapToDiscountNotifications(checkout.promotions),\n giftCertificate: {\n totalDiscountedAmount: reduce(\n checkout.giftCertificates,\n (sum, certificate) => {\n return sum + certificate.used;\n },\n 0,\n ),\n appliedGiftCertificates: keyBy(\n checkout.giftCertificates.map(mapToInternalGiftCertificate),\n 'code',\n ),\n },\n shipping: {\n amount: checkout.shippingCostTotal,\n integerAmount: amountTransformer.toInteger(checkout.shippingCostTotal),\n amountBeforeDiscount: checkout.shippingCostBeforeDiscount,\n integerAmountBeforeDiscount: amountTransformer.toInteger(\n checkout.shippingCostBeforeDiscount,\n ),\n required: some(\n checkout.cart.lineItems.physicalItems,\n (lineItem) => lineItem.isShippingRequired,\n ),\n },\n subtotal: {\n amount: checkout.subtotal,\n integerAmount: amountTransformer.toInteger(checkout.subtotal),\n },\n storeCredit: {\n amount: checkout.customer ? checkout.customer.storeCredit : 0,\n },\n taxSubtotal: {\n amount: checkout.taxTotal,\n integerAmount: amountTransformer.toInteger(checkout.taxTotal),\n },\n taxes: checkout.taxes,\n taxTotal: {\n amount: checkout.taxTotal,\n integerAmount: amountTransformer.toInteger(checkout.taxTotal),\n },\n handling: {\n amount: checkout.handlingCostTotal,\n integerAmount: amountTransformer.toInteger(checkout.handlingCostTotal),\n },\n grandTotal: {\n amount: checkout.grandTotal,\n integerAmount: amountTransformer.toInteger(checkout.grandTotal),\n },\n };\n}\n","import { DiscountNotification } from '../discount';\n\nimport { Promotion } from '.';\n\nexport default function mapToDiscountNotifications(\n promotions?: Promotion[],\n): DiscountNotification[] {\n const notifications: DiscountNotification[] = [];\n\n (promotions || []).forEach((promotion) => {\n (promotion.banners || []).forEach((banner) => {\n notifications.push({\n placeholders: [],\n discountType: null,\n message: '',\n messageHtml: banner.text,\n });\n });\n });\n\n return notifications;\n}\n","import { mapToInternalAddress } from '../address';\nimport { OrderBillingAddress } from '../order-billing-address/order-billing-address-state';\n\nimport InternalCustomer from './internal-customer';\n\nimport { Customer } from '.';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalCustomer(\n customer: Customer,\n billingAddress: OrderBillingAddress,\n): InternalCustomer {\n const firstName = customer.firstName || billingAddress.firstName || '';\n const lastName = customer.lastName || billingAddress.lastName || '';\n\n return {\n addresses: (customer.addresses || []).map((address) => mapToInternalAddress(address)),\n customerId: customer.id,\n isGuest: customer.isGuest,\n storeCredit: customer.storeCredit,\n email: customer.email || billingAddress.email || '',\n firstName,\n lastName,\n name: customer.fullName || [firstName, lastName].join(' '),\n customerGroupName: customer.customerGroup && customer.customerGroup.name,\n };\n}\n","import CardExpiryDate from './card-expiry-date';\n\nconst NUMBER_SEPARATOR = '/';\n\nexport default class CardExpiryFormatter {\n format(value: string): string {\n const [month = '', year = ''] = value.split(new RegExp(`\\\\s*${NUMBER_SEPARATOR}\\\\s*`));\n const trimmedMonth = month.slice(0, 2);\n const trimmedYear =\n year.length === 4 ? year.slice(-2) : year ? year.slice(0, 2) : month.slice(2);\n\n // i.e.: '1'\n if (value.length < 2) {\n return month;\n }\n\n // ie.: '10 /' (without trailing space)\n if (value.length > 3 && !trimmedYear) {\n return trimmedMonth;\n }\n\n return `${trimmedMonth} ${NUMBER_SEPARATOR} ${trimmedYear}`;\n }\n\n toObject(value: string): CardExpiryDate {\n const [month = '', year = ''] = value.split(new RegExp(`\\\\s*${NUMBER_SEPARATOR}\\\\s*`));\n\n if (!/^\\d+$/.test(month) || !/^\\d+$/.test(year)) {\n return { month: '', year: '' };\n }\n\n return {\n month: month.length === 1 ? `0${month}` : month.slice(0, 2),\n year: year.length === 2 ? `20${year}` : year.slice(0, 4),\n };\n }\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"card-validator\");","import { creditCardType, number } from 'card-validator';\nimport { max } from 'lodash';\n\nconst NUMBER_SEPARATOR = ' ';\n\nexport default class CardNumberFormatter {\n format(value: string): string {\n const { card } = number(value);\n\n if (!card) {\n return value;\n }\n\n const maxLength = max(creditCardType(value).map((info) => max(info.lengths)));\n const unformattedValue = this.unformat(value).slice(0, maxLength);\n\n return card.gaps\n .filter((gapIndex) => unformattedValue.length > gapIndex)\n .reduce(\n (output, gapIndex, index) =>\n [output.slice(0, gapIndex + index), output.slice(gapIndex + index)].join(\n NUMBER_SEPARATOR,\n ),\n unformattedValue,\n );\n }\n\n unformat(value: string): string {\n const { card } = number(value);\n\n if (!card) {\n return value;\n }\n\n return value.replace(new RegExp(NUMBER_SEPARATOR, 'g'), '');\n }\n}\n","import { filter, find, keyBy, reduce } from 'lodash';\n\nimport { LineItem, mapToInternalLineItems } from '../cart';\nimport { Checkout } from '../checkout';\nimport { AmountTransformer } from '../common/utility';\nimport { mapToInternalCoupon } from '../coupon';\nimport { HOSTED } from '../payment';\n\nimport InternalOrder, {\n InternalGiftCertificateList,\n InternalIncompleteOrder,\n InternalOrderPayment,\n InternalSocialDataList,\n} from './internal-order';\nimport Order, {\n GatewayOrderPayment,\n GiftCertificateOrderPayment,\n OrderPayment,\n OrderPayments,\n} from './order';\nimport { OrderMetaState } from './order-state';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalOrder(\n order: Order,\n orderMeta: OrderMetaState = {},\n): InternalOrder {\n const decimalPlaces = order.currency.decimalPlaces;\n const amountTransformer = new AmountTransformer(decimalPlaces);\n\n return {\n id: order.orderId,\n items: mapToInternalLineItems(order.lineItems, order.currency.decimalPlaces, 'productId'),\n orderId: order.orderId,\n currency: order.currency.code,\n customerCanBeCreated: order.customerCanBeCreated,\n payment: mapToInternalOrderPayment(order.payments, orderMeta.payment),\n subtotal: {\n amount: order.baseAmount,\n integerAmount: amountTransformer.toInteger(order.baseAmount),\n },\n coupon: {\n discountedAmount: reduce(\n order.coupons,\n (sum, coupon) => {\n return sum + coupon.discountedAmount;\n },\n 0,\n ),\n coupons: order.coupons.map(mapToInternalCoupon),\n },\n discount: {\n amount: order.discountAmount,\n integerAmount: amountTransformer.toInteger(order.discountAmount),\n },\n token: orderMeta.orderToken,\n callbackUrl: orderMeta.callbackUrl,\n discountNotifications: [],\n giftCertificate: mapToGiftCertificates(order.payments),\n socialData: mapToInternalSocialDataList(order),\n status: order.status,\n hasDigitalItems: order.hasDigitalItems,\n isDownloadable: order.isDownloadable,\n isComplete: order.isComplete,\n shipping: {\n amount: order.shippingCostTotal,\n integerAmount: amountTransformer.toInteger(order.shippingCostTotal),\n amountBeforeDiscount: order.shippingCostBeforeDiscount,\n integerAmountBeforeDiscount: amountTransformer.toInteger(\n order.shippingCostBeforeDiscount,\n ),\n },\n storeCredit: {\n amount: mapToStoreCredit(order.payments),\n },\n taxes: order.taxes,\n taxTotal: {\n amount: order.taxTotal,\n integerAmount: amountTransformer.toInteger(order.taxTotal),\n },\n handling: {\n amount: order.handlingCostTotal,\n integerAmount: amountTransformer.toInteger(order.handlingCostTotal),\n },\n grandTotal: {\n amount: order.orderAmount,\n integerAmount: order.orderAmountAsInteger,\n },\n };\n}\n\nexport function mapToInternalIncompleteOrder(checkout: Checkout): InternalIncompleteOrder {\n const payment = find(checkout.payments, { providerType: HOSTED });\n\n return {\n orderId: null,\n isComplete: false,\n payment: !payment\n ? {}\n : {\n id: payment.providerId,\n gateway: payment.gatewayId,\n status: mapToInternalPaymentStatus(payment.detail.step),\n },\n };\n}\n\nfunction mapToInternalPaymentStatus(status: string): string {\n return `PAYMENT_STATUS_${status}`;\n}\n\nfunction mapToStoreCredit(payments?: OrderPayments): number {\n const item = find(payments, { providerId: 'storecredit' });\n\n return item ? item.amount : 0;\n}\n\nfunction mapToGiftCertificates(payments?: OrderPayments): InternalGiftCertificateList {\n const items = filter(payments, {\n providerId: 'giftcertificate',\n }) as GiftCertificateOrderPayment[];\n\n return {\n totalDiscountedAmount: reduce(items, (sum, item) => item.amount + sum, 0),\n appliedGiftCertificates: keyBy(\n items.map((item) => ({\n code: item.detail.code,\n discountedAmount: item.amount,\n remainingBalance: item.detail.remaining,\n giftCertificate: {\n balance: item.amount + item.detail.remaining,\n code: item.detail.code,\n purchaseDate: '',\n },\n })),\n 'code',\n ),\n };\n}\n\nfunction mapToInternalOrderPayment(\n payments?: OrderPayments,\n payment: InternalOrderPayment = {},\n): InternalOrderPayment {\n const item = find(payments, isDefaultOrderPayment) as GatewayOrderPayment;\n\n if (!item) {\n return {};\n }\n\n return {\n id: item.providerId,\n status: mapToInternalPaymentStatus(item.detail.step),\n helpText: item.detail.instructions,\n returnUrl: payment.returnUrl,\n };\n}\n\nfunction isDefaultOrderPayment(payment: OrderPayment): payment is GatewayOrderPayment {\n return payment.providerId !== 'giftcertificate' && payment.providerId !== 'storecredit';\n}\n\nfunction mapToInternalSocialDataList(\n order: Order,\n): { [itemId: string]: InternalSocialDataList } | undefined {\n const socialDataObject: { [itemId: string]: InternalSocialDataList } = {};\n const items = [...order.lineItems.physicalItems, ...order.lineItems.digitalItems];\n\n items.forEach((item) => {\n socialDataObject[item.id] = mapToInternalSocialData(item);\n });\n\n return socialDataObject;\n}\n\nfunction mapToInternalSocialData(lineItem: LineItem): InternalSocialDataList {\n const codes = ['fb', 'tw', 'gp'];\n\n return codes.reduce((socialData, code) => {\n const item =\n lineItem.socialMedia && find(lineItem.socialMedia, (item) => item.code === code);\n\n if (!item) {\n return socialData;\n }\n\n socialData[code] = {\n name: lineItem.name,\n description: lineItem.name,\n image: lineItem.imageUrl,\n url: item.link,\n shareText: item.text,\n sharingLink: item.link,\n channelName: item.channel,\n channelCode: item.code,\n };\n\n return socialData;\n }, {} as InternalSocialDataList);\n}\n","import InternalShippingOption from './internal-shipping-option';\nimport ShippingOption from './shipping-option';\n\n/**\n * @deprecated This mapper is only for internal use only. It is required during\n * the transition period as we are moving to adopt the new storefront API object\n * schema.\n */\nexport default function mapToInternalShippingOption(\n option: ShippingOption,\n isSelected: boolean,\n): InternalShippingOption {\n return {\n description: option.description,\n module: option.type,\n price: option.cost,\n id: option.id,\n selected: isSelected,\n isRecommended: option.isRecommended,\n imageUrl: option.imageUrl,\n transitTime: option.transitTime,\n };\n}\n","import { pick } from 'lodash';\n\nimport { Address, mapToInternalAddress } from '../address';\nimport { mapToInternalCart } from '../cart';\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { CheckoutButtonMethodType } from '../checkout-buttons/strategies';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { mapToInternalCustomer } from '../customer';\nimport { HostedFormOrderData } from '../hosted-form';\nimport {\n CardExpiryFormatter,\n CardNumberFormatter,\n HostedInputValues,\n} from '../hosted-form/iframe-content';\nimport { mapToInternalOrder } from '../order';\nimport { mapToInternalShippingOption } from '../shipping';\n\nimport isVaultedInstrument, { isFormattedVaultedInstrument } from './is-vaulted-instrument';\nimport Payment, {\n HostedCreditCardInstrument,\n HostedVaultedInstrument,\n PaymentInstrument,\n} from './payment';\nimport PaymentMethod from './payment-method';\nimport PaymentRequestBody from './payment-request-body';\n\nexport default class PaymentRequestTransformer {\n private _cardExpiryFormatter = new CardExpiryFormatter();\n private _cardNumberFormatter = new CardNumberFormatter();\n\n transform(payment: Payment, checkoutState: InternalCheckoutSelectors): PaymentRequestBody {\n const billingAddress = checkoutState.billingAddress.getBillingAddress();\n const checkout = checkoutState.checkout.getCheckout();\n const customer = checkoutState.customer.getCustomer();\n const order = checkoutState.order.getOrder();\n const paymentMethod = checkoutState.paymentMethods.getPaymentMethod(\n payment.methodId,\n payment.gatewayId,\n );\n const shippingAddress = this._mapShippingAddress(checkoutState, paymentMethod);\n const consignments = checkoutState.consignments.getConsignments();\n const shippingOption = checkoutState.consignments.getShippingOption();\n const storeConfig = checkoutState.config.getStoreConfig();\n const contextConfig = checkoutState.config.getContextConfig();\n const instrumentMeta = checkoutState.instruments.getInstrumentsMeta();\n const paymentMeta = checkoutState.paymentMethods.getPaymentMethodsMeta();\n const orderMeta = checkoutState.order.getOrderMeta();\n const internalCustomer =\n customer && billingAddress && mapToInternalCustomer(customer, billingAddress);\n\n const authToken =\n instrumentMeta &&\n payment.paymentData &&\n (isVaultedInstrument(payment.paymentData) ||\n isFormattedVaultedInstrument(payment.paymentData))\n ? `${checkoutState.payment.getPaymentToken()}, ${instrumentMeta.vaultAccessToken}`\n : checkoutState.payment.getPaymentToken();\n\n if (!authToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n return {\n additionalAction: payment.additionalAction,\n authToken,\n customer: internalCustomer,\n billingAddress: billingAddress && mapToInternalAddress(billingAddress),\n shippingAddress: shippingAddress && mapToInternalAddress(shippingAddress, consignments),\n shippingOption: shippingOption && mapToInternalShippingOption(shippingOption, true),\n cart: checkout && mapToInternalCart(checkout),\n order: order && mapToInternalOrder(order, orderMeta),\n orderMeta,\n payment: payment.paymentData,\n paymentMethod: paymentMethod && this._transformPaymentMethod(paymentMethod),\n quoteMeta: {\n request: {\n ...paymentMeta,\n geoCountryCode: contextConfig && contextConfig.geoCountryCode,\n },\n },\n source: 'bigcommerce-checkout-js-sdk',\n store: pick(storeConfig && storeConfig.storeProfile, [\n 'storeHash',\n 'storeId',\n 'storeLanguage',\n 'storeName',\n ]),\n };\n }\n\n transformWithHostedFormData(\n values: HostedInputValues,\n data: HostedFormOrderData,\n nonce: string,\n ): PaymentRequestBody {\n const {\n additionalAction,\n authToken,\n checkout,\n config,\n order,\n orderMeta,\n payment = {},\n paymentMethod,\n paymentMethodMeta,\n } = data;\n const consignment = checkout && checkout.consignments[0];\n const shippingAddress = consignment && consignment.shippingAddress;\n const shippingOption = consignment && consignment.selectedShippingOption;\n\n return {\n additionalAction,\n authToken,\n paymentMethod: paymentMethod && this._transformPaymentMethod(paymentMethod),\n customer:\n order &&\n order.billingAddress &&\n checkout &&\n mapToInternalCustomer(checkout.customer, order.billingAddress),\n billingAddress:\n order && order.billingAddress && mapToInternalAddress(order.billingAddress),\n shippingAddress:\n shippingAddress &&\n checkout &&\n mapToInternalAddress(shippingAddress, checkout.consignments),\n shippingOption: shippingOption && mapToInternalShippingOption(shippingOption, true),\n cart: checkout && mapToInternalCart(checkout),\n order: order && mapToInternalOrder(order, orderMeta),\n orderMeta,\n payment: this._transformHostedInputValues(values, payment, nonce),\n quoteMeta: {\n request: {\n ...paymentMethodMeta,\n geoCountryCode: config && config.context.geoCountryCode,\n },\n },\n source: 'bigcommerce-checkout-js-sdk',\n store:\n config &&\n pick(config.storeConfig.storeProfile, [\n 'storeHash',\n 'storeId',\n 'storeLanguage',\n 'storeName',\n ]),\n };\n }\n\n private _transformPaymentMethod(paymentMethod: PaymentMethod): PaymentMethod {\n if (paymentMethod.method === 'multi-option' && !paymentMethod.gateway) {\n return { ...paymentMethod, gateway: paymentMethod.id };\n }\n\n if (paymentMethod.initializationData && paymentMethod.initializationData.gateway) {\n return { ...paymentMethod, id: paymentMethod.initializationData.gateway };\n }\n\n if (paymentMethod.id === CheckoutButtonMethodType.BRAINTREE_VENMO) {\n return { ...paymentMethod, id: CheckoutButtonMethodType.BRAINTREE_PAYPAL };\n }\n\n return paymentMethod;\n }\n\n private _transformHostedInputValues(\n values: HostedInputValues,\n payment: HostedCreditCardInstrument | HostedVaultedInstrument,\n nonce: string,\n ): PaymentInstrument {\n return 'instrumentId' in payment\n ? {\n ...payment,\n ccCvv: values.cardCodeVerification,\n ccNumber:\n values.cardNumberVerification &&\n this._cardNumberFormatter.unformat(values.cardNumberVerification),\n hostedFormNonce: nonce,\n }\n : {\n ...payment,\n ccCvv: values.cardCode,\n ccExpiry: this._cardExpiryFormatter.toObject(values.cardExpiry || ''),\n ccName: values.cardName || '',\n ccNumber: this._cardNumberFormatter.unformat(values.cardNumber || ''),\n hostedFormNonce: nonce,\n };\n }\n\n private _mapShippingAddress(\n checkoutState: InternalCheckoutSelectors,\n paymentMethod?: PaymentMethod,\n ): Address | undefined {\n if (paymentMethod) {\n const isBopisEnabled = paymentMethod.initializationData?.bopis?.enabled;\n const requiredAddress = paymentMethod.initializationData?.bopis?.requiredAddress;\n const consignments = checkoutState.consignments.getConsignments();\n const isPickup = consignments?.every((consignment) => consignment.selectedPickupOption);\n\n if (isBopisEnabled && isPickup && requiredAddress === 'none') {\n return undefined;\n }\n }\n\n return checkoutState.shippingAddress.getShippingAddress();\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Checkout } from '../checkout';\n\nimport { ConsignmentMeta } from './consignment';\n\nexport enum ConsignmentActionType {\n CreateConsignmentsRequested = 'CREATE_CONSIGNMENTS_REQUESTED',\n CreateConsignmentsSucceeded = 'CREATE_CONSIGNMENTS_SUCCEEDED',\n CreateConsignmentsFailed = 'CREATE_CONSIGNMENTS_FAILED',\n\n UpdateConsignmentRequested = 'UPDATE_CONSIGNMENT_REQUESTED',\n UpdateConsignmentSucceeded = 'UPDATE_CONSIGNMENT_SUCCEEDED',\n UpdateConsignmentFailed = 'UPDATE_CONSIGNMENT_FAILED',\n\n DeleteConsignmentRequested = 'DELETE_CONSIGNMENT_REQUESTED',\n DeleteConsignmentSucceeded = 'DELETE_CONSIGNMENT_SUCCEEDED',\n DeleteConsignmentFailed = 'DELETE_CONSIGNMENT_FAILED',\n\n UpdateShippingOptionRequested = 'UPDATE_SHIPPING_OPTION_REQUESTED',\n UpdateShippingOptionSucceeded = 'UPDATE_SHIPPING_OPTION_SUCCEEDED',\n UpdateShippingOptionFailed = 'UPDATE_SHIPPING_OPTION_FAILED',\n\n LoadShippingOptionsRequested = 'LOAD_SHIPPING_OPTIONS_REQUESTED',\n LoadShippingOptionsSucceeded = 'LOAD_SHIPPING_OPTIONS_SUCCEEDED',\n LoadShippingOptionsFailed = 'LOAD_SHIPPING_OPTIONS_FAILED',\n}\n\nexport type ConsignmentAction =\n | CreateConsignmentsAction\n | UpdateConsignmentAction\n | DeleteConsignmentAction\n | UpdateShippingOptionAction\n | LoadShippingOptionsAction;\n\nexport type CreateConsignmentsAction =\n | CreateConsignmentsRequestedAction\n | CreateConsignmentsSucceededAction\n | CreateConsignmentsFailedAction;\n\nexport type UpdateConsignmentAction =\n | UpdateConsignmentRequestedAction\n | UpdateConsignmentSucceededAction\n | UpdateConsignmentFailedAction;\n\nexport type DeleteConsignmentAction =\n | DeleteConsignmentRequestedAction\n | DeleteConsignmentSucceededAction\n | DeleteConsignmentFailedAction;\n\nexport type UpdateShippingOptionAction =\n | UpdateShippingOptionRequestedAction\n | UpdateShippingOptionSucceededAction\n | UpdateShippingOptionFailedAction;\n\nexport type LoadShippingOptionsAction =\n | LoadShippingOptionsRequestedAction\n | LoadShippingOptionsSucceededAction\n | LoadShippingOptionsFailedAction;\n\nexport interface CreateConsignmentsRequestedAction extends Action {\n type: ConsignmentActionType.CreateConsignmentsRequested;\n}\n\nexport interface CreateConsignmentsSucceededAction extends Action {\n type: ConsignmentActionType.CreateConsignmentsSucceeded;\n}\n\nexport interface CreateConsignmentsFailedAction extends Action {\n type: ConsignmentActionType.CreateConsignmentsFailed;\n}\n\nexport interface UpdateConsignmentRequestedAction extends Action {\n type: ConsignmentActionType.UpdateConsignmentRequested;\n}\n\nexport interface UpdateConsignmentSucceededAction extends Action {\n type: ConsignmentActionType.UpdateConsignmentSucceeded;\n}\n\nexport interface UpdateConsignmentFailedAction extends Action {\n type: ConsignmentActionType.UpdateConsignmentFailed;\n}\n\nexport interface DeleteConsignmentRequestedAction extends Action {\n type: ConsignmentActionType.DeleteConsignmentRequested;\n}\n\nexport interface DeleteConsignmentSucceededAction extends Action {\n type: ConsignmentActionType.DeleteConsignmentSucceeded;\n}\n\nexport interface DeleteConsignmentFailedAction extends Action {\n type: ConsignmentActionType.DeleteConsignmentFailed;\n}\n\nexport interface UpdateShippingOptionRequestedAction extends Action {\n type: ConsignmentActionType.UpdateShippingOptionRequested;\n}\n\nexport interface UpdateShippingOptionSucceededAction extends Action {\n type: ConsignmentActionType.UpdateShippingOptionSucceeded;\n}\n\nexport interface UpdateShippingOptionFailedAction extends Action {\n type: ConsignmentActionType.UpdateShippingOptionFailed;\n}\n\nexport interface LoadShippingOptionsRequestedAction extends Action {\n type: ConsignmentActionType.LoadShippingOptionsRequested;\n}\n\nexport interface LoadShippingOptionsSucceededAction extends Action {\n type: ConsignmentActionType.LoadShippingOptionsSucceeded;\n}\n\nexport interface LoadShippingOptionsFailedAction extends Action {\n type: ConsignmentActionType.LoadShippingOptionsFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { find } from 'lodash';\nimport { Observable, Observer } from 'rxjs';\n\nimport { AddressRequestBody } from '../address';\nimport { Cart } from '../cart';\nimport {\n CheckoutIncludes,\n CheckoutParams,\n CheckoutRequestSender,\n InternalCheckoutSelectors,\n ReadableCheckoutStore,\n} from '../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\n\nimport Consignment, {\n ConsignmentAssignmentBaseRequestBodyWithAddress,\n ConsignmentAssignmentBaseRequestBodyWithShippingAddress,\n ConsignmentAssignmentRequestBody,\n ConsignmentCreateRequestBody,\n ConsignmentLineItem,\n ConsignmentRequestBody,\n ConsignmentShippingOptionRequestBody,\n ConsignmentsRequestBody,\n ConsignmentUpdateRequestBody,\n} from './consignment';\nimport {\n ConsignmentActionType,\n CreateConsignmentsAction,\n DeleteConsignmentAction,\n LoadShippingOptionsAction,\n UpdateConsignmentAction,\n UpdateShippingOptionAction,\n} from './consignment-actions';\nimport ConsignmentRequestSender from './consignment-request-sender';\n\nexport default class ConsignmentActionCreator {\n constructor(\n private _consignmentRequestSender: ConsignmentRequestSender,\n private _checkoutRequestSender: CheckoutRequestSender,\n ) {}\n\n unassignItemsByAddress(\n consignment: ConsignmentAssignmentRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const address = this._consignmentHasAddress(consignment)\n ? consignment.address\n : consignment.shippingAddress;\n\n const existingConsignment = state.consignments.getConsignmentByAddress(address);\n\n if (!existingConsignment) {\n throw new InvalidArgumentError('No consignment found for the specified address');\n }\n\n const lineItems = this._removeLineItems(\n consignment.lineItems,\n existingConsignment,\n state.cart.getCart(),\n );\n\n if (!lineItems.length) {\n return this.deleteConsignment(existingConsignment.id, options)(store);\n }\n\n return this.updateConsignment(\n {\n id: existingConsignment.id,\n address,\n lineItems,\n },\n options,\n )(store);\n };\n }\n\n assignItemsByAddress(\n consignment: ConsignmentAssignmentRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const state = store.getState();\n const address = this._consignmentHasAddress(consignment)\n ? consignment.address\n : consignment.shippingAddress;\n const existingConsignment = state.consignments.getConsignmentByAddress(address);\n\n return this._createOrUpdateConsignment(\n {\n id: existingConsignment && existingConsignment.id,\n address,\n lineItems: this._addLineItems(\n consignment.lineItems,\n existingConsignment,\n state.cart.getCart(),\n ),\n },\n options,\n )(store);\n };\n }\n\n selectShippingOption(\n id: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n const consignments = state.consignments.getConsignments();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!consignments || !consignments.length) {\n throw new MissingDataError(MissingDataErrorType.MissingConsignments);\n }\n\n const consignmentUpdateBody = {\n id: consignments[0].id,\n shippingOptionId: id,\n };\n\n const consignmentMeta = {\n id: consignments[0].id,\n };\n\n observer.next(\n createAction(\n ConsignmentActionType.UpdateShippingOptionRequested,\n undefined,\n consignmentMeta,\n ),\n );\n\n this._consignmentRequestSender\n .updateConsignment(checkout.id, consignmentUpdateBody, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n ConsignmentActionType.UpdateShippingOptionSucceeded,\n body,\n consignmentMeta,\n ),\n );\n\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ConsignmentActionType.UpdateShippingOptionFailed,\n response,\n consignmentMeta,\n ),\n );\n });\n });\n }\n\n loadShippingOptions(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const checkout = store.getState().checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(createAction(ConsignmentActionType.LoadShippingOptionsRequested));\n\n this._checkoutRequestSender\n .loadCheckout(checkout.id, {\n ...options,\n params: {\n include: [CheckoutIncludes.AvailableShippingOptions],\n },\n })\n .then(({ body }) => {\n observer.next(\n createAction(ConsignmentActionType.LoadShippingOptionsSucceeded, body),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ConsignmentActionType.LoadShippingOptionsFailed,\n response,\n ),\n );\n });\n });\n }\n\n updateAddress(\n address: AddressRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const consignment = this._getUpdateAddressRequestBody(address, store);\n const consignments = store.getState().consignments.getConsignments();\n\n if (consignments && consignments.length) {\n (consignment as ConsignmentUpdateRequestBody).id = consignments[0].id;\n }\n\n return this._createOrUpdateConsignment(consignment, options)(store);\n };\n }\n\n createConsignments(\n consignments: ConsignmentsRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const checkout = store.getState().checkout.getCheckout();\n\n if (!checkout || !checkout.id) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(createAction(ConsignmentActionType.CreateConsignmentsRequested));\n\n this._consignmentRequestSender\n .createConsignments(checkout.id, consignments, options)\n .then(({ body }) => {\n observer.next(\n createAction(ConsignmentActionType.CreateConsignmentsSucceeded, body),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ConsignmentActionType.CreateConsignmentsFailed,\n response,\n ),\n );\n });\n });\n }\n\n updateConsignment(\n consignment: ConsignmentUpdateRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const checkout = store.getState().checkout.getCheckout();\n\n if (!checkout || !checkout.id) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const consignmentMeta = { id: consignment.id };\n\n observer.next(\n createAction(\n ConsignmentActionType.UpdateConsignmentRequested,\n undefined,\n consignmentMeta,\n ),\n );\n\n this._consignmentRequestSender\n .updateConsignment(checkout.id, consignment, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n ConsignmentActionType.UpdateConsignmentSucceeded,\n body,\n consignmentMeta,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ConsignmentActionType.UpdateConsignmentFailed,\n response,\n consignmentMeta,\n ),\n );\n });\n });\n }\n\n deleteConsignment(\n consignmentId: string,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const checkout = store.getState().checkout.getCheckout();\n const consignmentMeta = { id: consignmentId };\n\n if (!checkout || !checkout.id) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n observer.next(\n createAction(\n ConsignmentActionType.DeleteConsignmentRequested,\n undefined,\n consignmentMeta,\n ),\n );\n\n this._consignmentRequestSender\n .deleteConsignment(checkout.id, consignmentId, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n ConsignmentActionType.DeleteConsignmentSucceeded,\n body,\n consignmentMeta,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ConsignmentActionType.DeleteConsignmentFailed,\n response,\n consignmentMeta,\n ),\n );\n });\n });\n }\n\n updateShippingOption(\n consignment: ConsignmentShippingOptionRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const checkout = store.getState().checkout.getCheckout();\n\n if (!checkout || !checkout.id) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const consignmentMeta = { id: consignment.id };\n\n observer.next(\n createAction(\n ConsignmentActionType.UpdateShippingOptionRequested,\n undefined,\n consignmentMeta,\n ),\n );\n\n this._consignmentRequestSender\n .updateConsignment(checkout.id, consignment, options)\n .then(({ body }) => {\n observer.next(\n createAction(\n ConsignmentActionType.UpdateShippingOptionSucceeded,\n body,\n consignmentMeta,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ConsignmentActionType.UpdateShippingOptionFailed,\n response,\n consignmentMeta,\n ),\n );\n });\n });\n }\n\n private _createOrUpdateConsignment(\n consignment: ConsignmentCreateRequestBody | ConsignmentUpdateRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) => {\n const checkout = store.getState().checkout.getCheckout();\n\n if (!checkout || !checkout.id) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (this._isUpdateConsignmentRequest(consignment)) {\n return this.updateConsignment(consignment, options)(store);\n }\n\n return this.createConsignments([consignment], options)(store);\n };\n }\n\n private _getUpdateAddressRequestBody(\n address: AddressRequestBody,\n store: ReadableCheckoutStore,\n ): ConsignmentRequestBody {\n const state = store.getState();\n const cart = state.cart.getCart();\n\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n const { physicalItems, customItems = [] } = cart.lineItems;\n\n return {\n address,\n lineItems: [...physicalItems, ...customItems].map((item) => ({\n itemId: item.id,\n quantity: item.quantity,\n })),\n };\n }\n\n private _removeLineItems(\n lineItems: ConsignmentLineItem[],\n consignment: Consignment,\n cart?: Cart,\n ): ConsignmentLineItem[] {\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n return this._hydrateLineItems(consignment.lineItemIds, cart)\n .map((existingItem) => {\n const sharedItem = find(\n lineItems,\n (lineItem) => lineItem.itemId === existingItem.itemId,\n );\n\n return {\n ...existingItem,\n quantity: sharedItem\n ? existingItem.quantity - sharedItem.quantity\n : existingItem.quantity,\n };\n })\n .filter((lineItem) => lineItem.quantity > 0);\n }\n\n private _addLineItems(\n lineItems: ConsignmentLineItem[],\n consignment?: Consignment,\n cart?: Cart,\n ): ConsignmentLineItem[] {\n if (!consignment) {\n return lineItems;\n }\n\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n return lineItems\n .concat(this._hydrateLineItems(consignment.lineItemIds, cart))\n .filter((lineItem) => lineItem.quantity > 0);\n }\n\n private _hydrateLineItems(lineItemIds: string[], cart: Cart): ConsignmentLineItem[] {\n return lineItemIds.map((itemId) => {\n const item = find(cart.lineItems.physicalItems, (lineItem) => lineItem.id === itemId);\n\n return {\n itemId,\n quantity: item ? item.quantity : 0,\n };\n });\n }\n\n private _isUpdateConsignmentRequest(\n request: ConsignmentRequestBody,\n ): request is ConsignmentUpdateRequestBody {\n const updateRequest = request as ConsignmentUpdateRequestBody;\n\n return !!updateRequest.id;\n }\n\n private _consignmentHasAddress(\n consignment:\n | ConsignmentAssignmentBaseRequestBodyWithAddress\n | ConsignmentAssignmentBaseRequestBodyWithShippingAddress,\n ): consignment is ConsignmentAssignmentBaseRequestBodyWithAddress {\n return typeof consignment === 'object' && 'address' in consignment;\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Checkout, CheckoutParams } from '../checkout';\nimport {\n ContentType,\n joinIncludes,\n joinOrMergeIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nimport { ConsignmentsRequestBody, ConsignmentUpdateRequestBody } from './consignment';\n\nconst DEFAULT_INCLUDES = [\n 'consignments.availableShippingOptions',\n 'cart.lineItems.physicalItems.options',\n 'cart.lineItems.digitalItems.options',\n 'customer',\n 'promotions.banners',\n];\n\nexport default class ConsignmentRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n createConsignments(\n checkoutId: string,\n consignments: ConsignmentsRequestBody,\n { timeout, params: { include } = {} }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/consignments`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, {\n body: consignments,\n params: {\n include: joinOrMergeIncludes(DEFAULT_INCLUDES, include),\n },\n headers,\n timeout,\n });\n }\n\n updateConsignment(\n checkoutId: string,\n consignment: ConsignmentUpdateRequestBody,\n { timeout, params: { include } = {} }: RequestOptions = {},\n ): Promise> {\n const { id, ...body } = consignment;\n const url = `/api/storefront/checkouts/${checkoutId}/consignments/${id}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.put(url, {\n body,\n params: {\n include: joinOrMergeIncludes(DEFAULT_INCLUDES, include),\n },\n headers,\n timeout,\n });\n }\n\n deleteConsignment(\n checkoutId: string,\n consignmentId: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/consignments/${consignmentId}`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n const include = joinIncludes(DEFAULT_INCLUDES);\n\n return this._requestSender.delete(url, { params: { include }, headers, timeout });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Checkout } from '../checkout';\n\nexport enum SpamProtectionActionType {\n InitializeFailed = 'SPAM_PROTECTION_INITIALIZE_FAILED',\n InitializeSucceeded = 'SPAM_PROTECTION_INITIALIZE_SUCCEEDED',\n InitializeRequested = 'SPAM_PROTECTION_INITIALIZE_REQUESTED',\n VerifyCheckoutRequested = 'SPAM_PROTECTION_CHECKOUT_VERIFY_REQUESTED',\n VerifyCheckoutSucceeded = 'SPAM_PROTECTION_CHECKOUT_VERIFY_SUCCEEDED',\n VerifyCheckoutFailed = 'SPAM_PROTECTION_CHECKOUT_VERIFY_FAILED',\n ExecuteRequested = 'SPAM_PROTECTION_EXECUTE_REQUESTED',\n ExecuteSucceeded = 'SPAM_PROTECTION_EXECUTE_SUCCEEDED',\n ExecuteFailed = 'SPAM_PROTECTION_EXECUTE_FAILED',\n}\n\nexport type SpamProtectionAction =\n | InitializeRequestedAction\n | InitializeSucceededAction\n | InitializeFailedAction\n | ExecuteRequestedAction\n | ExecuteSucceededAction\n | ExecuteFailedAction\n | CheckoutVerifyRequestedAction\n | CheckoutVerifyFailedAction\n | CheckoutVerifySucceededAction;\n\nexport interface InitializeRequestedAction extends Action {\n type: SpamProtectionActionType.InitializeRequested;\n}\n\nexport interface InitializeSucceededAction extends Action {\n type: SpamProtectionActionType.InitializeSucceeded;\n}\n\nexport interface InitializeFailedAction extends Action {\n type: SpamProtectionActionType.InitializeFailed;\n}\n\nexport interface ExecuteRequestedAction extends Action {\n type: SpamProtectionActionType.ExecuteRequested;\n}\n\nexport interface ExecuteSucceededAction extends Action<{ token: string }> {\n type: SpamProtectionActionType.ExecuteSucceeded;\n}\n\nexport interface ExecuteFailedAction extends Action {\n type: SpamProtectionActionType.ExecuteFailed;\n}\n\nexport interface CheckoutVerifyRequestedAction extends Action {\n type: SpamProtectionActionType.VerifyCheckoutRequested;\n}\n\nexport interface CheckoutVerifyFailedAction extends Action {\n type: SpamProtectionActionType.VerifyCheckoutFailed;\n}\n\nexport interface CheckoutVerifySucceededAction extends Action {\n type: SpamProtectionActionType.VerifyCheckoutSucceeded;\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, from, of } from 'rxjs';\nimport { catchError, switchMap, take } from 'rxjs/operators';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\n\nimport { SpamProtectionChallengeNotCompletedError, SpamProtectionFailedError } from './errors';\nimport GoogleRecaptcha from './google-recaptcha';\nimport isSpamProtectionExecuteSucceededAction from './is-spam-protection-succeeded-action';\nimport { SpamProtectionAction, SpamProtectionActionType } from './spam-protection-actions';\nimport { SpamProtectionOptions } from './spam-protection-options';\nimport SpamProtectionRequestSender from './spam-protection-request-sender';\n\nexport default class SpamProtectionActionCreator {\n constructor(\n private _googleRecaptcha: GoogleRecaptcha,\n private _requestSender: SpamProtectionRequestSender,\n ) {}\n\n initialize(\n options?: SpamProtectionOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(SpamProtectionActionType.InitializeRequested, undefined)),\n defer(async () => {\n const spamProtectionElementId = options\n ? options.containerId\n : 'spamProtectionContainer';\n\n if (!options && !document.getElementById(spamProtectionElementId)) {\n const spamProtectionElement = document.createElement('div');\n\n spamProtectionElement.setAttribute('id', spamProtectionElementId);\n document.body.appendChild(spamProtectionElement);\n }\n\n const state = store.getState();\n const storeConfig = state.config.getStoreConfigOrThrow();\n const recaptchaSitekey = storeConfig.checkoutSettings.googleRecaptchaSitekey;\n\n await this._googleRecaptcha.load(spamProtectionElementId, recaptchaSitekey);\n\n return createAction(SpamProtectionActionType.InitializeSucceeded);\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(SpamProtectionActionType.InitializeFailed, error),\n ),\n );\n }\n\n verifyCheckoutSpamProtection(): ThunkAction {\n return (store) =>\n defer(() => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n return concat(\n of(createAction(SpamProtectionActionType.VerifyCheckoutRequested)),\n from(this.execute()(store)).pipe(\n switchMap((action) => {\n if (\n !isSpamProtectionExecuteSucceededAction(action) ||\n !action.payload\n ) {\n return of(action);\n }\n\n return from(\n this._requestSender.validate(checkout.id, action.payload.token),\n ).pipe(\n switchMap(({ body }) =>\n concat(\n of(action),\n of(\n createAction(\n SpamProtectionActionType.VerifyCheckoutSucceeded,\n body,\n ),\n ),\n ),\n ),\n );\n }),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(SpamProtectionActionType.VerifyCheckoutFailed, error),\n ),\n );\n });\n }\n\n execute(): ThunkAction {\n return (store) =>\n concat(\n of(createAction(SpamProtectionActionType.ExecuteRequested)),\n this.initialize()(store),\n this._googleRecaptcha\n .execute()\n .pipe(take(1))\n .pipe(\n switchMap(async ({ error, token }) => {\n if (error instanceof SpamProtectionChallengeNotCompletedError) {\n throw error;\n }\n\n if (error || !token) {\n throw new SpamProtectionFailedError();\n }\n\n return createAction(SpamProtectionActionType.ExecuteSucceeded, {\n token,\n });\n }),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(SpamProtectionActionType.ExecuteFailed, error),\n ),\n );\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Checkout } from '../checkout';\nimport { ContentType, RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nexport default class SpamProtectionRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n validate(\n checkoutId: string,\n token: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/spam-protection`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, { body: { token }, headers, timeout });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Checkout } from '../checkout';\nimport { RequestError } from '../common/error/errors';\n\nexport enum StoreCreditActionType {\n ApplyStoreCreditRequested = 'APPLY_STORE_CREDIT_REQUESTED',\n ApplyStoreCreditSucceeded = 'APPLY_STORE_CREDIT_SUCCEEDED',\n ApplyStoreCreditFailed = 'APPLY_STORE_CREDIT_FAILED',\n}\n\nexport type StoreCreditAction = ApplyStoreCreditAction;\n\nexport type ApplyStoreCreditAction =\n | ApplyStoreCreditRequestedAction\n | ApplyStoreCreditSucceededAction\n | ApplyStoreCreditFailedAction;\n\nexport interface ApplyStoreCreditRequestedAction extends Action {\n type: StoreCreditActionType.ApplyStoreCreditRequested;\n}\n\nexport interface ApplyStoreCreditSucceededAction extends Action {\n type: StoreCreditActionType.ApplyStoreCreditSucceeded;\n}\n\nexport interface ApplyStoreCreditFailedAction\n extends Action> {\n type: StoreCreditActionType.ApplyStoreCreditFailed;\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\n\nimport { StoreCreditAction, StoreCreditActionType } from './store-credit-actions';\nimport StoreCreditRequestSender from './store-credit-request-sender';\n\nexport default class StoreCreditActionCreator {\n constructor(private _storeCreditRequestSender: StoreCreditRequestSender) {}\n\n applyStoreCredit(\n useStoreCredit: boolean,\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(StoreCreditActionType.ApplyStoreCreditRequested)),\n defer(async () => {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const { body } = await (useStoreCredit\n ? this._storeCreditRequestSender.applyStoreCredit(checkout.id, options)\n : this._storeCreditRequestSender.removeStoreCredit(checkout.id, options));\n\n return createAction(StoreCreditActionType.ApplyStoreCreditSucceeded, body);\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(StoreCreditActionType.ApplyStoreCreditFailed, error),\n ),\n );\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Checkout, CHECKOUT_DEFAULT_INCLUDES } from '../checkout';\nimport {\n ContentType,\n joinIncludes,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../common/http-request';\n\nexport default class StoreCreditRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n applyStoreCredit(\n checkoutId: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/store-credit`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n },\n });\n }\n\n removeStoreCredit(\n checkoutId: string,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/checkouts/${checkoutId}/store-credit`;\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.delete(url, {\n headers,\n timeout,\n params: {\n include: joinIncludes(CHECKOUT_DEFAULT_INCLUDES),\n },\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Subscriptions } from './subscriptions';\n\nexport enum SubscriptionsActionType {\n UpdateSubscriptionsRequested = 'UPDATE_SUBSCRIPTIONS_REQUESTED',\n UpdateSubscriptionsSucceeded = 'UPDATE_SUBSCRIPTIONS_SUCCEEDED',\n UpdateSubscriptionsFailed = 'UPDATE_SUBSCRIPTIONS_FAILED',\n}\nexport type UpdateSubscriptionsAction =\n | UpdateSubscriptionsRequestedAction\n | UpdateSubscriptionsSucceededAction\n | UpdateSubscriptionsFailedAction;\n\nexport interface UpdateSubscriptionsRequestedAction extends Action {\n type: SubscriptionsActionType.UpdateSubscriptionsRequested;\n}\n\nexport interface UpdateSubscriptionsSucceededAction extends Action {\n type: SubscriptionsActionType.UpdateSubscriptionsSucceeded;\n}\n\nexport interface UpdateSubscriptionsFailedAction extends Action {\n type: SubscriptionsActionType.UpdateSubscriptionsFailed;\n}\n","import { RequestError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when the subscriptions fails to be updated\n */\nexport default class UpdateSubscriptionsError extends RequestError {\n constructor(response?: Response) {\n super(response);\n\n this.name = 'UpdateSubscriptionsError';\n this.type = 'update_subscriptions';\n }\n}\n","import { createAction } from '@bigcommerce/data-store';\nimport { concat, defer, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { throwErrorAction } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\nimport {\n Subscriptions,\n SubscriptionsActionType,\n SubscriptionsRequestSender,\n UpdateSubscriptionsAction,\n} from '../subscription';\n\nimport { UpdateSubscriptionsError } from './errors';\n\nexport default class SubscriptionsActionCreator {\n constructor(private _subscriptionsRequestSender: SubscriptionsRequestSender) {}\n\n updateSubscriptions(\n subscriptions: Subscriptions,\n options?: RequestOptions,\n ): Observable {\n return concat(\n of(createAction(SubscriptionsActionType.UpdateSubscriptionsRequested)),\n defer(async () => {\n const { body } = await this._subscriptionsRequestSender.updateSubscriptions(\n subscriptions,\n options,\n );\n\n return createAction(SubscriptionsActionType.UpdateSubscriptionsSucceeded, body);\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(\n SubscriptionsActionType.UpdateSubscriptionsFailed,\n new UpdateSubscriptionsError(error),\n ),\n ),\n );\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { ContentType, RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nimport { Subscriptions } from './subscriptions';\n\nexport default class SubscriptionsRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n updateSubscriptions(\n subscriptions: Subscriptions,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = '/api/storefront/subscriptions';\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, { body: subscriptions, headers, timeout });\n }\n}\n","import { isPlainObject as lodashIsPlainObject } from 'lodash';\n\n// We need this wrapper because Lodash's version doesn't act as a type guard\nexport default function isPlainObject(value: any): value is object {\n return lodashIsPlainObject(value);\n}\n","import { memoize } from 'lodash';\n\nimport isPlainObject from './is-plain-object';\n\nconst cloneDeep = memoize((input: T): T => {\n if (Array.isArray(input)) {\n // Fixed in later versions of typescript https://github.com/microsoft/TypeScript/issues/36390\n return (input as any[]).map((value: T[keyof T]) => cloneDeepSafe(value)) as any;\n }\n\n if (isPlainObject(input)) {\n return (Object.keys(input) as Array).reduce(\n (result, key) => ({\n ...result,\n [key]: cloneDeepSafe(input[key]),\n }),\n {},\n ) as T;\n }\n\n return input;\n});\n\n// Use WeakMap as the MapCache, this allows for better garbage collection\n// There's a deprecated `clear` method in the lodash implementation\n// of MapCache, hence the `any`\ncloneDeep.cache = new WeakMap() as any;\n\n/**\n * This is a wrapper function for `cloneDeep`. We need it because `cloneDeep` is\n * a memoized function using an instance of `WeakMap` as its cache. Without this\n * wrapper, the memoized function will throw an error if it is called with a\n * non-object argument.\n */\nconst cloneDeepSafe = (input: T): T => {\n return typeof input === 'object' && input !== null ? cloneDeep(input) : input;\n};\n\n/**\n * Clone the return value of a function. If the result is the same as previous\n * calls, return the previous clone instead of cloning it again.\n */\nexport default function cloneResult(fn: T): T {\n return ((...args: any[]) => cloneDeepSafe(fn(...args))) as T;\n}\n\nexport type Func = (...args: any[]) => any;\n","import { PaymentIntegrationSelectors } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { cloneResult as clone } from '../common/utility';\n\nexport default function createPaymentIntegrationSelectors({\n billingAddress: { getBillingAddress, getBillingAddressOrThrow },\n cart: { getCart, getCartOrThrow },\n checkout: { getCheckout, getCheckoutOrThrow },\n config: { getHost, getLocale, getStoreConfig, getStoreConfigOrThrow },\n consignments: { getConsignments, getConsignmentsOrThrow },\n customer: { getCustomer, getCustomerOrThrow },\n instruments: { getCardInstrument, getCardInstrumentOrThrow },\n order: { getOrder, getOrderOrThrow },\n payment: {\n getPaymentToken,\n getPaymentTokenOrThrow,\n getPaymentId,\n getPaymentIdOrThrow,\n getPaymentStatus,\n getPaymentStatusOrThrow,\n getPaymentRedirectUrl,\n getPaymentRedirectUrlOrThrow,\n isPaymentDataRequired,\n },\n paymentMethods: { getPaymentMethod, getPaymentMethodOrThrow },\n paymentStrategies: { isInitialized: isPaymentMethodInitialized },\n shippingAddress: {\n getShippingAddress,\n getShippingAddressOrThrow,\n getShippingAddresses,\n getShippingAddressesOrThrow,\n },\n}: InternalCheckoutSelectors): PaymentIntegrationSelectors {\n return {\n getHost: clone(getHost),\n getLocale: clone(getLocale),\n getBillingAddress: clone(getBillingAddress),\n getBillingAddressOrThrow: clone(getBillingAddressOrThrow),\n getCart: clone(getCart),\n getCartOrThrow: clone(getCartOrThrow),\n getCheckout: clone(getCheckout),\n getCheckoutOrThrow: clone(getCheckoutOrThrow),\n getStoreConfig: clone(getStoreConfig),\n getStoreConfigOrThrow: clone(getStoreConfigOrThrow),\n getConsignments: clone(getConsignments),\n getConsignmentsOrThrow: clone(getConsignmentsOrThrow),\n getCustomer: clone(getCustomer),\n getCustomerOrThrow: clone(getCustomerOrThrow),\n getCardInstrument: clone(getCardInstrument),\n getCardInstrumentOrThrow: clone(getCardInstrumentOrThrow),\n getOrder: clone(getOrder),\n getOrderOrThrow: clone(getOrderOrThrow),\n getPaymentToken,\n getPaymentTokenOrThrow,\n getPaymentId,\n getPaymentIdOrThrow,\n getPaymentStatus,\n getPaymentStatusOrThrow,\n getPaymentRedirectUrl,\n getPaymentRedirectUrlOrThrow,\n getPaymentMethod: clone(getPaymentMethod),\n getPaymentMethodOrThrow: clone(getPaymentMethodOrThrow),\n getShippingAddress: clone(getShippingAddress),\n getShippingAddressOrThrow: clone(getShippingAddressOrThrow),\n getShippingAddresses: clone(getShippingAddresses),\n getShippingAddressesOrThrow: clone(getShippingAddressesOrThrow),\n isPaymentDataRequired,\n isPaymentMethodInitialized,\n };\n}\n","import {\n BillingAddressRequestBody,\n BuyNowCartRequestBody,\n Cart,\n HostedForm,\n HostedFormOptions,\n InitializeOffsitePaymentConfig,\n OrderRequestBody,\n Payment,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n RequestOptions,\n ShippingAddressRequestBody,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BillingAddressActionCreator } from '../billing';\nimport { CartRequestSender } from '../cart';\nimport { CheckoutActionCreator, CheckoutStore } from '../checkout';\nimport { DataStoreProjection } from '../common/data-store';\nimport { CustomerActionCreator, CustomerCredentials } from '../customer';\nimport { HostedFormFactory } from '../hosted-form';\nimport { OrderActionCreator } from '../order';\nimport PaymentActionCreator from '../payment/payment-action-creator';\nimport PaymentMethodActionCreator from '../payment/payment-method-action-creator';\nimport { ConsignmentActionCreator } from '../shipping';\nimport { SpamProtectionActionCreator } from '../spam-protection';\nimport { StoreCreditActionCreator } from '../store-credit';\n\nimport PaymentIntegrationStoreProjectionFactory from './payment-integration-store-projection-factory';\n\nexport default class DefaultPaymentIntegrationService implements PaymentIntegrationService {\n private _storeProjection: DataStoreProjection;\n\n constructor(\n private _store: CheckoutStore,\n private _storeProjectionFactory: PaymentIntegrationStoreProjectionFactory,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _hostedFormFactory: HostedFormFactory,\n private _orderActionCreator: OrderActionCreator,\n private _billingAddressActionCreator: BillingAddressActionCreator,\n private _consignmentActionCreator: ConsignmentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _customerActionCreator: CustomerActionCreator,\n private _cartRequestSender: CartRequestSender,\n private _storeCreditActionCreator: StoreCreditActionCreator,\n private _spamProtectionActionCreator: SpamProtectionActionCreator,\n ) {\n this._storeProjection = this._storeProjectionFactory.create(this._store);\n }\n\n createHostedForm(host: string, options: HostedFormOptions): HostedForm {\n return this._hostedFormFactory.create(host, options);\n }\n\n subscribe(\n subscriber: (state: PaymentIntegrationSelectors) => void,\n ...filters: Array<(state: PaymentIntegrationSelectors) => unknown>\n ): () => void {\n return this._storeProjection.subscribe(subscriber, ...filters);\n }\n\n getState(): PaymentIntegrationSelectors {\n return this._storeProjection.getState();\n }\n\n async initializeOffsitePayment(\n initializeOffsitePaymentConfig: InitializeOffsitePaymentConfig,\n ): Promise {\n await this._store.dispatch(\n this._paymentActionCreator.initializeOffsitePayment(initializeOffsitePaymentConfig),\n );\n\n return this._storeProjection.getState();\n }\n\n async loadCheckout(id?: string): Promise {\n if (id) {\n await this._store.dispatch(this._checkoutActionCreator.loadCheckout(id));\n } else {\n await this._store.dispatch(this._checkoutActionCreator.loadCurrentCheckout());\n }\n\n return this._storeProjection.getState();\n }\n\n async loadDefaultCheckout(): Promise {\n await this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout());\n\n return this._storeProjection.getState();\n }\n\n async loadPaymentMethod(\n methodId: string,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async submitOrder(\n payload?: OrderRequestBody,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(this._orderActionCreator.submitOrder(payload, options));\n\n return this._storeProjection.getState();\n }\n\n async submitPayment(payment: Payment): Promise {\n await this._store.dispatch(this._paymentActionCreator.submitPayment(payment));\n\n return this._storeProjection.getState();\n }\n\n async finalizeOrder(options?: RequestOptions): Promise {\n const {\n order: { getOrderOrThrow },\n } = this._store.getState();\n\n await this._store.dispatch(\n this._orderActionCreator.finalizeOrder(getOrderOrThrow().orderId, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async updateBillingAddress(\n payload: BillingAddressRequestBody,\n ): Promise {\n await this._store.dispatch(this._billingAddressActionCreator.updateAddress(payload));\n\n return this._storeProjection.getState();\n }\n\n async updateShippingAddress(\n payload: ShippingAddressRequestBody,\n ): Promise {\n await this._store.dispatch(this._consignmentActionCreator.updateAddress(payload));\n\n return this._storeProjection.getState();\n }\n\n async selectShippingOption(\n id: string,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(\n this._consignmentActionCreator.selectShippingOption(id, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async signInCustomer(\n credentials: CustomerCredentials,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(\n this._customerActionCreator.signInCustomer(credentials, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async signOutCustomer(options?: RequestOptions): Promise {\n await this._store.dispatch(this._customerActionCreator.signOutCustomer(options));\n\n return this._storeProjection.getState();\n }\n\n async createBuyNowCart(\n buyNowCartRequestBody: BuyNowCartRequestBody,\n options?: RequestOptions,\n ): Promise {\n const { body: buyNowCart } = await this._cartRequestSender.createBuyNowCart(\n buyNowCartRequestBody,\n options,\n );\n\n return buyNowCart;\n }\n\n async applyStoreCredit(\n useStoreCredit: boolean,\n options?: RequestOptions,\n ): Promise {\n await this._store.dispatch(\n this._storeCreditActionCreator.applyStoreCredit(useStoreCredit, options),\n );\n\n return this._storeProjection.getState();\n }\n\n async verifyCheckoutSpamProtection(): Promise {\n const { checkout } = this._store.getState();\n const { shouldExecuteSpamCheck } = checkout.getCheckoutOrThrow();\n\n if (shouldExecuteSpamCheck) {\n await this._store.dispatch(\n this._spamProtectionActionCreator.verifyCheckoutSpamProtection(),\n );\n }\n\n return this._storeProjection.getState();\n }\n}\n","import { Action, createAction, createDataStore, ReadableDataStore } from '@bigcommerce/data-store';\n\nenum ProjectionActionType {\n Synchronize = 'SYNCHRONIZE',\n}\n\ninterface SynchronizeAction extends Action {\n type: ProjectionActionType.Synchronize;\n payload: TState;\n}\n\nexport interface DataStoreProjection\n extends ReadableDataStore {\n notifyState(): void;\n}\n\nexport default function createDataStoreProjection(\n store: ReadableDataStore,\n stateTransformer: (state: TState) => TTransformedState,\n): DataStoreProjection {\n const projection = createDataStore<\n TState | undefined,\n SynchronizeAction,\n TTransformedState\n >(\n (state, action) =>\n action.type === ProjectionActionType.Synchronize ? action.payload : state,\n store.getState(),\n { stateTransformer },\n );\n\n store.subscribe(\n (state) => {\n projection.dispatch(\n createAction(ProjectionActionType.Synchronize, state) as SynchronizeAction,\n );\n },\n { initial: false },\n );\n\n return projection;\n}\n","import { PaymentIntegrationSelectors } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { InternalCheckoutSelectors, ReadableCheckoutStore } from '../checkout';\nimport { createDataStoreProjection, DataStoreProjection } from '../common/data-store';\n\nexport default class PaymentIntegrationStoreProjectionFactory {\n constructor(\n private _transformSelectors: (\n selectors: InternalCheckoutSelectors,\n ) => PaymentIntegrationSelectors,\n ) {}\n\n create(store: ReadableCheckoutStore): DataStoreProjection {\n return createDataStoreProjection(store, this._transformSelectors);\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { createScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentIntegrationService } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BillingAddressActionCreator, BillingAddressRequestSender } from '../billing';\nimport { CartRequestSender } from '../cart';\nimport {\n CheckoutActionCreator,\n CheckoutRequestSender,\n CheckoutStore,\n CheckoutValidator,\n} from '../checkout';\nimport { ConfigActionCreator, ConfigRequestSender } from '../config';\nimport { CustomerActionCreator, CustomerRequestSender } from '../customer';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport { HostedFormFactory } from '../hosted-form';\nimport { OrderActionCreator, OrderRequestSender } from '../order';\nimport {\n createPaymentClient,\n PaymentActionCreator,\n PaymentMethodActionCreator,\n PaymentMethodRequestSender,\n PaymentRequestSender,\n PaymentRequestTransformer,\n} from '../payment';\nimport { ConsignmentActionCreator, ConsignmentRequestSender } from '../shipping';\nimport {\n createSpamProtection,\n PaymentHumanVerificationHandler,\n SpamProtectionActionCreator,\n SpamProtectionRequestSender,\n} from '../spam-protection';\nimport { StoreCreditActionCreator, StoreCreditRequestSender } from '../store-credit';\nimport { SubscriptionsActionCreator, SubscriptionsRequestSender } from '../subscription';\n\nimport createPaymentIntegrationSelectors from './create-payment-integration-selectors';\nimport DefaultPaymentIntegrationService from './default-payment-integration-service';\nimport PaymentIntegrationStoreProjectionFactory from './payment-integration-store-projection-factory';\n\nexport default function createPaymentIntegrationService(\n store: CheckoutStore,\n): PaymentIntegrationService {\n const {\n config: { getHost },\n } = store.getState();\n\n const requestSender = createRequestSender({ host: getHost() });\n\n const storeProjectionFactory = new PaymentIntegrationStoreProjectionFactory(\n createPaymentIntegrationSelectors,\n );\n\n const checkoutActionCreator = new CheckoutActionCreator(\n new CheckoutRequestSender(requestSender),\n new ConfigActionCreator(new ConfigRequestSender(requestSender)),\n new FormFieldsActionCreator(new FormFieldsRequestSender(requestSender)),\n );\n\n const hostedFormFactory = new HostedFormFactory(store);\n\n const orderActionCreator = new OrderActionCreator(\n new OrderRequestSender(requestSender),\n new CheckoutValidator(new CheckoutRequestSender(requestSender)),\n );\n\n const billingAddressActionCreator = new BillingAddressActionCreator(\n new BillingAddressRequestSender(requestSender),\n new SubscriptionsActionCreator(new SubscriptionsRequestSender(requestSender)),\n );\n\n const consignmentActionCreator = new ConsignmentActionCreator(\n new ConsignmentRequestSender(requestSender),\n new CheckoutRequestSender(requestSender),\n );\n\n const paymentMethodActionCreator = new PaymentMethodActionCreator(\n new PaymentMethodRequestSender(requestSender),\n );\n\n const paymentActionCreator = new PaymentActionCreator(\n new PaymentRequestSender(createPaymentClient(store)),\n orderActionCreator,\n new PaymentRequestTransformer(),\n new PaymentHumanVerificationHandler(createSpamProtection(createScriptLoader())),\n );\n\n const customerActionCreator = new CustomerActionCreator(\n new CustomerRequestSender(requestSender),\n checkoutActionCreator,\n new SpamProtectionActionCreator(\n createSpamProtection(createScriptLoader()),\n new SpamProtectionRequestSender(requestSender),\n ),\n );\n\n const storeCreditActionCreator = new StoreCreditActionCreator(\n new StoreCreditRequestSender(requestSender),\n );\n\n const spamProtection = createSpamProtection(createScriptLoader());\n const spamProtectionRequestSender = new SpamProtectionRequestSender(requestSender);\n const spamProtectionActionCreator = new SpamProtectionActionCreator(\n spamProtection,\n spamProtectionRequestSender,\n );\n\n const cartRequestSender = new CartRequestSender(requestSender);\n\n return new DefaultPaymentIntegrationService(\n store,\n storeProjectionFactory,\n checkoutActionCreator,\n hostedFormFactory,\n orderActionCreator,\n billingAddressActionCreator,\n consignmentActionCreator,\n paymentMethodActionCreator,\n paymentActionCreator,\n customerActionCreator,\n cartRequestSender,\n storeCreditActionCreator,\n spamProtectionActionCreator,\n );\n}\n","import { Cart } from '../cart';\n\nimport getLineItemsCount from './getLineItemsCount';\n\nexport default function getShippableItemsCount(cart: Cart): number {\n return getLineItemsCount(cart.lineItems.physicalItems.filter((item) => !item.addedByPromotion));\n}\n","import { reduce } from 'lodash';\n\nimport { LineItem } from '../cart';\n\nexport default function getLineItemsCount(lineItems: LineItem[]): number {\n return reduce(lineItems, (total, item) => total + item.quantity, 0);\n}\n","export default function guard(value: T, errorFactory?: () => Error): NonNullable {\n if (value === undefined || value === null) {\n throw errorFactory ? errorFactory() : new Error('An unexpected error has occurred.');\n }\n\n return value as NonNullable;\n}\n","import { InternalCheckoutSelectors } from '../../../../../core/src/checkout';\n\nexport type EnvironmentType = 'PRODUCTION' | 'TEST';\n\nexport interface AmazonPayV2Options {\n environment: EnvironmentType;\n}\n\nexport interface AmazonPayV2SDK {\n Pay: AmazonPayV2Client;\n}\n\nexport interface RequestConfig {\n createCheckoutSessionConfig: AmazonPayV2CheckoutSessionConfig;\n estimatedOrderAmount?: AmazonPayV2Price;\n productType?: AmazonPayV2PayOptions;\n}\n\nexport interface AmazonPayV2Button {\n /**\n * Allows you to define custom actions.\n */\n onClick: (callback: () => void) => void;\n\n /**\n * Initiates the Amazon Pay checkout.\n */\n initCheckout(requestConfig: RequestConfig): void;\n}\n\nexport type AmazonPayV2ButtonParameters = AmazonPayV2ButtonParams | AmazonPayV2NewButtonParams;\n\nexport interface AmazonPayV2Client {\n /**\n * Render the Amazon Pay button to a HTML container element.\n *\n * @param containerId - HTML element id.\n * @param params - Button rendering params.\n */\n renderButton(containerId: string, params: AmazonPayV2ButtonParameters): AmazonPayV2Button;\n\n /**\n * Bind click events to HTML elements, so that when the element is clicked, the buyer can select a different shipping address or payment method.\n *\n * @param buttonId - HTML element id.\n * @param options - Element binding options.\n */\n bindChangeAction(buttonId: string, options: AmazonPayV2ChangeActionOptions): void;\n\n /**\n * Allow buyers to sign out from their Amazon account.\n */\n signout(): void;\n}\n\nexport interface AmazonPayV2HostWindow extends Window {\n amazon?: AmazonPayV2SDK;\n}\n\nexport interface AmazonPayV2ButtonConfig {\n /**\n * Amazon Pay merchant account identifier.\n */\n merchantId: string;\n\n /**\n * Placement of the Amazon Pay button on your website.\n */\n placement: AmazonPayV2Placement;\n\n /**\n * Ledger currency provided during registration for the given merchant identifier.\n */\n ledgerCurrency: AmazonPayV2LedgerCurrency;\n\n /**\n * Product type selected for checkout. Default is 'PayAndShip'.\n */\n productType?: AmazonPayV2PayOptions;\n\n /**\n * Color of the Amazon Pay button.\n */\n buttonColor?: AmazonPayV2ButtonColor;\n\n /**\n * Language used to render the button and text on Amazon Pay hosted pages.\n */\n checkoutLanguage?: AmazonPayV2CheckoutLanguage;\n\n /**\n * Sets button to Sandbox environment. You do not have to set this parameter\n * if your `publicKeyId` has an environment prefix. Default is false.\n */\n sandbox?: boolean;\n\n /**\n * Sets Amazon Pay button design.\n */\n design?: AmazonPayV2ButtonDesign;\n}\n\nexport interface AmazonPayV2ButtonParams extends AmazonPayV2ButtonConfig {\n /**\n * Configuration for calling the endpoint to Create Checkout Session.\n */\n createCheckoutSession: AmazonPayV2CheckoutSession;\n}\n\nexport interface AmazonPayV2NewButtonParams extends AmazonPayV2ButtonConfig {\n /**\n * Credential provided by Amazon Pay. You must also set the `sandbox`\n * parameter if your `publicKeyId` does not have an environment prefix.\n */\n publicKeyId?: string;\n\n /**\n * It does not have to match the final order amount if the buyer updates\n * their order after starting checkout. Amazon Pay will use this value to\n * assess transaction risk and prevent buyers from selecting payment methods\n * that can't be used to process the order.\n */\n estimatedOrderAmount?: AmazonPayV2Price;\n\n /**\n * Create Checkout Session configuration.\n */\n createCheckoutSessionConfig?: AmazonPayV2CheckoutSessionConfig;\n}\n\nexport interface AmazonPayV2CheckoutSession {\n /**\n * Endpoint URL to Create Checkout Session.\n */\n url: string;\n\n /**\n * HTTP request method. Default is 'POST'.\n */\n method?: 'GET' | 'POST';\n\n /**\n * Checkout Session ID parameter in the response. Default is 'checkoutSessionId'.\n */\n extractAmazonCheckoutSessionId?: string;\n}\n\nexport interface AmazonPayV2CheckoutSessionConfig {\n /**\n * A payload that Amazon Pay will use to create a Checkout Session object.\n */\n payloadJSON: string;\n\n /**\n * Payload's signature.\n */\n signature: string;\n\n /**\n * Credential provided by Amazon Pay. You do not have to set this parameter\n * if your `publicKeyId` has an environment prefix.\n */\n publicKeyId?: string;\n}\n\nexport interface AmazonPayV2Price {\n /**\n * Transaction amount.\n */\n amount: string;\n\n /**\n * Transaction currency code in ISO 4217 format. Example: USD.\n */\n currencyCode: string;\n}\n\nexport type AmazonPayV2ChangeActionType = 'changeAddress' | 'changePayment';\n\nexport interface AmazonPayV2ChangeActionOptions {\n /**\n * Amazon Pay Checkout Session identifier.\n */\n amazonCheckoutSessionId: string;\n\n /**\n * Update requested by the buyer.\n */\n changeAction: AmazonPayV2ChangeActionType;\n}\n\nexport enum AmazonPayV2Regions {\n de = 'eu',\n jp = 'fe',\n uk = 'eu',\n us = 'na',\n}\n\nexport enum AmazonPayV2CheckoutLanguage {\n en_US = 'en_US',\n en_GB = 'en_GB',\n de_DE = 'de_DE',\n fr_FR = 'fr_FR',\n it_IT = 'it_IT',\n es_ES = 'es_ES',\n ja_JP = 'ja_JP',\n}\n\nexport enum AmazonPayV2Placement {\n /** Initial or main page. */\n Home = 'Home',\n\n /** Product details page. */\n Product = 'Product',\n\n /** Cart review page before buyer starts checkout. */\n Cart = 'Cart',\n\n /** Any page after buyer starts checkout. */\n Checkout = 'Checkout',\n\n /** Any page that doesn't fit the previous descriptions. */\n Other = 'Other',\n}\n\nexport enum AmazonPayV2LedgerCurrency {\n USD = 'USD',\n EUR = 'EUR',\n GBP = 'GBP',\n JPY = 'JPY',\n}\n\nexport enum AmazonPayV2PayOptions {\n /** Select this product type if you need the buyer's shipping details. */\n PayAndShip = 'PayAndShip',\n\n /** Select this product type if you do not need the buyer's shipping details. */\n PayOnly = 'PayOnly',\n}\n\nexport enum AmazonPayV2ButtonColor {\n Gold = 'Gold',\n LightGray = 'LightGray',\n DarkGray = 'DarkGray',\n}\n\nexport enum AmazonPayV2ButtonDesign {\n C0001 = 'C0001',\n}\n\nexport interface AmazonPayV2ButtonRenderingOptions {\n checkoutState: InternalCheckoutSelectors;\n containerId: string;\n decoupleCheckoutInitiation?: boolean;\n methodId: string;\n buttonColor?: AmazonPayV2ButtonColor;\n options?: AmazonPayV2ButtonParameters;\n placement: AmazonPayV2Placement;\n}\n","import { PaymentMethod } from '../..';\nimport { InternalCheckoutSelectors } from '../../../../../core/src/checkout';\nimport { getShippableItemsCount } from '../../../../../core/src/shipping';\nimport { guard } from '../../../../src/common/utility';\nimport { StoreProfile } from '../../../../src/config';\nimport { CheckoutSettings } from '../../../../src/config/config';\nimport BuyNowCartRequestBody from '../../../cart/buy-now-cart-request-body';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\n\nimport {\n AmazonPayV2Button,\n AmazonPayV2ButtonColor,\n AmazonPayV2ButtonConfig,\n AmazonPayV2ButtonDesign,\n AmazonPayV2ButtonParameters,\n AmazonPayV2ButtonRenderingOptions,\n AmazonPayV2ChangeActionType,\n AmazonPayV2CheckoutSessionConfig,\n AmazonPayV2NewButtonParams,\n AmazonPayV2PayOptions,\n AmazonPayV2Placement,\n AmazonPayV2Price,\n AmazonPayV2SDK,\n RequestConfig,\n} from './amazon-pay-v2';\nimport AmazonPayV2ScriptLoader from './amazon-pay-v2-script-loader';\n\nexport default class AmazonPayV2PaymentProcessor {\n private _amazonPayV2SDK?: AmazonPayV2SDK;\n private _buttonParentContainer?: HTMLDivElement;\n private _amazonPayV2Button?: AmazonPayV2Button;\n private _buyNowCartRequestBody?: BuyNowCartRequestBody;\n\n constructor(private _amazonPayV2ScriptLoader: AmazonPayV2ScriptLoader) {}\n\n async initialize(paymentMethod: PaymentMethod): Promise {\n this._amazonPayV2SDK = await this._amazonPayV2ScriptLoader.load(paymentMethod);\n this._buttonParentContainer =\n this._buttonParentContainer || this._createAmazonPayButtonParentContainer();\n }\n\n deinitialize(): Promise {\n this._amazonPayV2Button = undefined;\n this._buttonParentContainer?.remove();\n this._buttonParentContainer = undefined;\n this._amazonPayV2SDK = undefined;\n\n return Promise.resolve();\n }\n\n bindButton(\n buttonId: string,\n sessionId: string,\n changeAction: AmazonPayV2ChangeActionType,\n ): void {\n this._getAmazonPayV2SDK().Pay.bindChangeAction(`#${buttonId}`, {\n amazonCheckoutSessionId: sessionId,\n changeAction,\n });\n }\n\n createButton(containerId: string, options: AmazonPayV2ButtonParameters): void {\n this._amazonPayV2Button = this._getAmazonPayV2SDK().Pay.renderButton(\n `#${containerId}`,\n options,\n );\n }\n\n prepareCheckout(createCheckoutSessionConfig: Required) {\n const requestConfig = this._prepareRequestConfig(createCheckoutSessionConfig);\n\n this._getAmazonPayV2Button().onClick(() => {\n this._getAmazonPayV2Button().initCheckout(requestConfig);\n });\n }\n\n prepareCheckoutWithCreationRequestConfig(\n createCheckoutConfig: () => Promise<{\n createCheckoutSessionConfig: Required;\n estimatedOrderAmount: AmazonPayV2Price;\n productType: AmazonPayV2PayOptions;\n }>,\n ) {\n this._getAmazonPayV2Button().onClick(async () => {\n const config = await createCheckoutConfig();\n const requestConfig = this._prepareRequestConfig(\n config.createCheckoutSessionConfig,\n config.estimatedOrderAmount,\n config.productType,\n );\n\n this._getAmazonPayV2Button().initCheckout(requestConfig);\n });\n }\n\n async signout(): Promise {\n if (this._amazonPayV2SDK) {\n this._amazonPayV2SDK.Pay.signout();\n }\n\n return Promise.resolve();\n }\n\n renderAmazonPayButton({\n buttonColor,\n checkoutState,\n containerId,\n decoupleCheckoutInitiation = false,\n methodId,\n options,\n placement,\n }: AmazonPayV2ButtonRenderingOptions): HTMLDivElement {\n const container = document.querySelector(`#${containerId}`);\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to render the Amazon Pay button to an invalid HTML container element.',\n );\n }\n\n const { id: parentContainerId } = container.appendChild(this._getButtonParentContainer());\n\n if (options) {\n options.design = AmazonPayV2ButtonDesign.C0001;\n }\n\n const amazonPayV2ButtonOptions =\n options ??\n this._getAmazonPayV2ButtonOptions(\n checkoutState,\n methodId,\n placement,\n decoupleCheckoutInitiation,\n buttonColor,\n );\n\n this.createButton(parentContainerId, amazonPayV2ButtonOptions);\n\n return this._getButtonParentContainer();\n }\n\n setCartRequestBody(buyNowCartRequestBody: BuyNowCartRequestBody) {\n this._buyNowCartRequestBody = buyNowCartRequestBody;\n }\n\n /**\n * @internal\n */\n isPh4Enabled(\n features: CheckoutSettings['features'],\n storeCountryCode: StoreProfile['storeCountryCode'],\n ): boolean {\n const isPh4Enabled = !!features['PROJECT-3483.amazon_pay_ph4'];\n const isPh4UsOnly = !!features['INT-6885.amazon_pay_ph4_us_only'];\n\n if (isPh4Enabled && isPh4UsOnly) {\n return storeCountryCode === 'US';\n }\n\n return isPh4Enabled;\n }\n\n private _prepareRequestConfig(\n createCheckoutSessionConfig: Required,\n estimatedOrderAmount?: AmazonPayV2Price,\n productType?: AmazonPayV2PayOptions,\n ): RequestConfig {\n const { publicKeyId, ...signedPayload } = createCheckoutSessionConfig;\n\n return {\n createCheckoutSessionConfig: this._isEnvironmentSpecific(publicKeyId)\n ? signedPayload\n : createCheckoutSessionConfig,\n ...(estimatedOrderAmount && { estimatedOrderAmount }),\n ...(productType && { productType }),\n };\n }\n\n private _createAmazonPayButtonParentContainer(): HTMLDivElement {\n const uid = Math.random().toString(16).substr(-4);\n const parentContainer = document.createElement('div');\n\n parentContainer.id = `amazonpay_button_parent_container_${uid}`;\n\n return parentContainer;\n }\n\n private _getAmazonPayV2ButtonOptions(\n {\n cart: { getCart },\n checkout: { getCheckout },\n config: { getStoreConfigOrThrow },\n paymentMethods: { getPaymentMethodOrThrow },\n }: InternalCheckoutSelectors,\n methodId: string,\n placement: AmazonPayV2Placement,\n decoupleCheckoutInitiation = false,\n buttonColor = AmazonPayV2ButtonColor.Gold,\n ): AmazonPayV2ButtonParameters {\n const {\n config: { merchantId, testMode },\n initializationData: {\n checkoutLanguage,\n checkoutSessionMethod,\n createCheckoutSessionConfig,\n extractAmazonCheckoutSessionId,\n ledgerCurrency,\n publicKeyId,\n },\n } = getPaymentMethodOrThrow(methodId);\n\n if (!merchantId || !ledgerCurrency) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const buttonBaseConfig: AmazonPayV2ButtonConfig = {\n merchantId,\n ledgerCurrency,\n checkoutLanguage,\n placement,\n buttonColor,\n design: AmazonPayV2ButtonDesign.C0001,\n };\n\n if (this._buyNowCartRequestBody) {\n return {\n ...buttonBaseConfig,\n sandbox: !!testMode,\n };\n }\n\n const cart = getCart();\n\n buttonBaseConfig.productType =\n cart && getShippableItemsCount(cart) === 0\n ? AmazonPayV2PayOptions.PayOnly\n : AmazonPayV2PayOptions.PayAndShip;\n\n const {\n checkoutSettings: { features },\n storeProfile: { shopPath, storeCountryCode },\n } = getStoreConfigOrThrow();\n\n if (this.isPh4Enabled(features, storeCountryCode)) {\n const amount = getCheckout()?.outstandingBalance.toString();\n const currencyCode = cart?.currency.code;\n const buttonOptions: AmazonPayV2NewButtonParams = { ...buttonBaseConfig };\n let tmpConfig: AmazonPayV2CheckoutSessionConfig;\n\n if (this._isEnvironmentSpecific(publicKeyId)) {\n buttonOptions.publicKeyId = publicKeyId;\n tmpConfig = createCheckoutSessionConfig;\n } else {\n buttonOptions.sandbox = !!testMode;\n tmpConfig = { ...createCheckoutSessionConfig, publicKeyId };\n }\n\n if (!decoupleCheckoutInitiation) {\n buttonOptions.createCheckoutSessionConfig = tmpConfig;\n }\n\n if (amount && currencyCode) {\n buttonOptions.estimatedOrderAmount = { amount, currencyCode };\n }\n\n return buttonOptions;\n }\n\n const createCheckoutSession = {\n method: checkoutSessionMethod,\n url: features['INT-5826.amazon_relative_url']\n ? `/remote-checkout/${methodId}/payment-session`\n : `${shopPath}/remote-checkout/${methodId}/payment-session`,\n extractAmazonCheckoutSessionId,\n };\n\n return {\n ...buttonBaseConfig,\n createCheckoutSession,\n sandbox: !!testMode,\n };\n }\n\n private _isEnvironmentSpecific(publicKeyId: string): boolean {\n return /^(SANDBOX|LIVE)/.test(publicKeyId);\n }\n\n private _getAmazonPayV2SDK(): AmazonPayV2SDK {\n return this._getOrThrow(this._amazonPayV2SDK);\n }\n\n private _getButtonParentContainer(): HTMLDivElement {\n return this._getOrThrow(this._buttonParentContainer);\n }\n\n private _getAmazonPayV2Button(): AmazonPayV2Button {\n return this._getOrThrow(this._amazonPayV2Button);\n }\n\n private _getOrThrow(value?: T): T {\n return guard(\n value,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when the client library of a payment method fails\n * to load, or for some reason, it is inaccessible.\n */\nexport default class PaymentMethodClientUnavailableError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'Unable to proceed because the client library of a payment method is not loaded or ready to be used.',\n );\n\n this.name = 'PaymentMethodClientUnavailableError';\n this.type = 'payment_method_client_unavailable';\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\nimport PaymentMethod from '../../payment-method';\n\nimport { AmazonPayV2HostWindow, AmazonPayV2Regions, AmazonPayV2SDK } from './amazon-pay-v2';\n\nexport default class AmazonPayV2ScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _window: AmazonPayV2HostWindow = window,\n ) {}\n\n async load(method: PaymentMethod): Promise {\n const { initializationData: { region = 'us' } = {} } = method;\n\n const amazonPayV2Region = (AmazonPayV2Regions as any)[region];\n\n await this._scriptLoader.loadScript(\n `https://static-${amazonPayV2Region}.payments-amazon.com/checkout.js`,\n );\n\n if (!this._window.amazon) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.amazon;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport AmazonPayV2PaymentProcessor from './amazon-pay-v2-payment-processor';\nimport AmazonPayV2ScriptLoader from './amazon-pay-v2-script-loader';\n\nexport default function createAmazonPayV2PaymentProcessor(): AmazonPayV2PaymentProcessor {\n return new AmazonPayV2PaymentProcessor(new AmazonPayV2ScriptLoader(getScriptLoader()));\n}\n","import StandardError from './standard-error';\n\n/**\n * Throw this error if the shopper is using a browser version that is not\n * supported by us or any third party provider we use.\n */\nexport default class UnsupportedBrowserError extends StandardError {\n constructor(message?: string) {\n super(message || 'Unsupported browser error');\n\n this.name = 'UnsupportedBrowserError';\n this.type = 'unsupported_browser';\n }\n}\n","import { Omit } from '../../../common/types';\nimport {\n GooglePayBraintreeDataRequest,\n GooglePayBraintreePaymentDataRequestV1,\n GooglePayCreator,\n GooglePaymentData,\n TokenizePayload,\n} from '../googlepay';\nimport { PaypalAuthorizeData, PaypalButtonOptions, PaypalButtonRender, PaypalSDK } from '../paypal';\n\nimport {\n VisaCheckoutInitOptions,\n VisaCheckoutPaymentSuccessPayload,\n VisaCheckoutTokenizedPayload,\n} from './visacheckout';\n\n/**\n *\n * Constants\n *\n */\nexport const PAYPAL_COMPONENTS = ['buttons', 'messages'];\n\n/**\n *\n * Common\n *\n */\nexport interface BraintreeModuleCreator<\n TInstance,\n TOptions = BraintreeModuleCreatorConfig,\n TError = BraintreeError,\n> {\n create(\n config: TOptions,\n callback?: (error: TError, instance: TInstance) => void,\n ): Promise;\n}\n\nexport interface BraintreeModuleCreatorConfig {\n client?: BraintreeClient;\n authorization?: string;\n}\n\nexport interface BraintreeModule {\n teardown(): Promise;\n}\n\nexport interface BraintreeSDK {\n client?: BraintreeClientCreator;\n dataCollector?: BraintreeDataCollectorCreator;\n googlePayment?: GooglePayCreator;\n hostedFields?: BraintreeHostedFieldsCreator;\n paypal?: BraintreePaypalCreator;\n paypalCheckout?: BraintreePaypalCheckoutCreator;\n threeDSecure?: BraintreeThreeDSecureCreator;\n venmo?: BraintreeVenmoCheckoutCreator;\n visaCheckout?: BraintreeVisaCheckoutCreator;\n}\n\nexport interface BraintreePaypalRequest {\n amount: string | number;\n billingAgreementDescription?: string;\n currency?: string;\n displayName?: string;\n enableShippingAddress: true;\n flow: 'checkout' | 'vault';\n intent?: 'authorize' | 'order' | 'sale';\n landingPageType?: 'login' | 'billing';\n locale?: string;\n offerCredit?: boolean;\n shippingAddressEditable?: boolean;\n shippingAddressOverride?: BraintreeShippingAddressOverride;\n useraction?: 'commit';\n}\n\nexport interface BraintreeShippingAddressOverride {\n line1: string;\n line2?: string;\n city: string;\n state: string;\n postalCode: string;\n countryCode: string;\n phone?: string;\n recipientName?: string;\n}\n\nexport interface BraintreeTokenizePayload {\n nonce: string;\n type: 'PaypalAccount' | 'VenmoAccount';\n details: BraintreeDetails;\n creditFinancingOffered?: {\n totalCost: {\n value: string;\n currency: string;\n };\n term: number;\n monthlyPayment: {\n value: string;\n currency: string;\n };\n totalInsterest: {\n value: string;\n currency: string;\n };\n payerAcceptance: boolean;\n cartAmountImmutable: boolean;\n };\n}\n\nexport interface BraintreeDetails {\n username?: string;\n email?: string;\n payerId?: string;\n firstName?: string;\n lastName?: string;\n countryCode?: string;\n phone?: string;\n shippingAddress?: BraintreeShippingAddress;\n billingAddress?: BraintreeAddress;\n}\n\nexport interface BraintreeAddress {\n line1: string;\n line2: string;\n city: string;\n state: string;\n postalCode: string;\n countryCode: string;\n}\n\nexport interface BraintreeShippingAddress extends BraintreeAddress {\n recipientName: string;\n}\n\nexport interface BraintreeVerifyPayload {\n nonce: string;\n details: {\n cardType: string;\n lastFour: string;\n lastTwo: string;\n };\n description: string;\n liabilityShiftPossible: boolean;\n liabilityShifted: boolean;\n}\n\nexport interface BraintreeError extends Error {\n type: 'CUSTOMER' | 'MERCHANT' | 'NETWORK' | 'INTERNAL' | 'UNKNOWN';\n code: string;\n details?: unknown;\n}\n\n/**\n *\n * Braintree Client\n *\n */\nexport type BraintreeClientCreator = BraintreeModuleCreator;\n\nexport interface BraintreeClient {\n request(payload: BraintreeRequestData): Promise;\n getVersion(): string | void;\n}\n\nexport interface BraintreeRequestData {\n data: {\n creditCard: {\n billingAddress?: {\n countryCodeAlpha2: string;\n locality: string;\n countryName: string;\n postalCode: string;\n streetAddress: string;\n };\n cardholderName: string;\n cvv?: string;\n expirationDate: string;\n number: string;\n options: {\n validate: boolean;\n };\n };\n };\n endpoint: string;\n method: string;\n}\n\nexport interface BraintreeTokenizeResponse {\n creditCards: Array<{ nonce: string }>;\n}\n\n/**\n *\n * Braintree Data Collector\n *\n */\nexport type BraintreeDataCollectorCreator = BraintreeModuleCreator<\n BraintreeDataCollector,\n BraintreeDataCollectorCreatorConfig\n>;\n\nexport interface BraintreeDataCollectorCreatorConfig extends BraintreeModuleCreatorConfig {\n kount?: boolean;\n paypal?: boolean;\n}\n\nexport interface BraintreeDataCollector extends BraintreeModule {\n deviceData?: string;\n}\n\n/**\n *\n * Braintree Google Pay\n *\n */\nexport interface BraintreeGooglePayThreeDSecure {\n verifyCard(options: BraintreeGooglePayThreeDSecureOptions): Promise;\n}\n\nexport interface BraintreeGooglePayThreeDSecureOptions {\n nonce: string;\n amount: number;\n showLoader?: boolean;\n onLookupComplete(data: BraintreeThreeDSecureVerificationData, next: () => void): void;\n}\n\nexport interface GooglePayBraintreeSDK extends BraintreeModule {\n createPaymentDataRequest(\n request?: GooglePayBraintreeDataRequest,\n ): GooglePayBraintreePaymentDataRequestV1;\n parseResponse(paymentData: GooglePaymentData): Promise;\n}\n\n/**\n *\n * Braintree Hosted Fields\n *\n */\nexport type BraintreeHostedFieldsCreator = BraintreeModuleCreator<\n BraintreeHostedFields,\n BraintreeHostedFieldsCreatorConfig\n>;\n\nexport interface BraintreeHostedFields {\n teardown(): Promise;\n tokenize(\n options?: BraintreeHostedFieldsTokenizeOptions,\n ): Promise;\n on(eventName: string, callback: (event: BraintreeHostedFieldsState) => void): void;\n}\n\nexport interface BraintreeHostedFieldsCreatorConfig extends BraintreeModuleCreatorConfig {\n fields: {\n number?: BraintreeHostedFieldOption;\n expirationDate?: BraintreeHostedFieldOption;\n expirationMonth?: BraintreeHostedFieldOption;\n expirationYear?: BraintreeHostedFieldOption;\n cvv?: BraintreeHostedFieldOption;\n postalCode?: BraintreeHostedFieldOption;\n };\n styles?: {\n input?: { [key: string]: string };\n '.invalid'?: { [key: string]: string };\n '.valid'?: { [key: string]: string };\n ':focus'?: { [key: string]: string };\n };\n}\n\nexport interface BraintreeHostedFieldOption {\n container: string | HTMLElement;\n placeholder?: string;\n type?: string;\n formatInput?: boolean;\n maskInput?: boolean | { character?: string; showLastFour?: string };\n select?: boolean | { options?: string[] };\n maxCardLength?: number;\n maxlength?: number;\n minlength?: number;\n prefill?: string;\n rejectUnsupportedCards?: boolean;\n supportedCardBrands?: { [key: string]: boolean };\n internalLabel?: string;\n}\n\nexport interface BraintreeHostedFieldsState {\n cards: BraintreeHostedFieldsCard[];\n emittedBy: string;\n fields: {\n number?: BraintreeHostedFieldsFieldData;\n expirationDate?: BraintreeHostedFieldsFieldData;\n expirationMonth?: BraintreeHostedFieldsFieldData;\n expirationYear?: BraintreeHostedFieldsFieldData;\n cvv?: BraintreeHostedFieldsFieldData;\n postalCode?: BraintreeHostedFieldsFieldData;\n };\n}\n\nexport interface BraintreeHostedFieldsCard {\n type: string;\n niceType: string;\n code: { name: string; size: number };\n}\n\nexport interface BraintreeFormFieldState {\n isFocused: boolean;\n isEmpty: boolean;\n isPotentiallyValid: boolean;\n isValid: boolean;\n}\n\nexport interface BraintreeHostedFieldsFieldData extends BraintreeFormFieldState {\n container: HTMLElement;\n}\n\nexport type BraintreeFormErrorData = Omit;\n\nexport type BraintreeFormErrorDataKeys =\n | 'number'\n | 'expirationDate'\n | 'expirationMonth'\n | 'expirationYear'\n | 'cvv'\n | 'postalCode';\n\nexport type BraintreeFormErrorsData = Partial<\n Record\n>;\n\nexport interface BraintreeHostedFieldsTokenizeOptions {\n vault?: boolean;\n fieldsToTokenize?: string[];\n cardholderName?: string;\n billingAddress?: BraintreeBillingAddressRequestData;\n}\n\nexport interface BraintreeHostedFieldsTokenizePayload {\n nonce: string;\n details: {\n bin: string;\n cardType: string;\n expirationMonth: string;\n expirationYear: string;\n lastFour: string;\n lastTwo: string;\n };\n description: string;\n type: string;\n binData: {\n commercial: string;\n countryOfIssuance: string;\n debit: string;\n durbinRegulated: string;\n healthcare: string;\n issuingBank: string;\n payroll: string;\n prepaid: string;\n productId: string;\n };\n}\n\nexport interface BraintreeBillingAddressRequestData {\n postalCode?: string;\n firstName?: string;\n lastName?: string;\n company?: string;\n streetAddress?: string;\n extendedAddress?: string;\n locality?: string;\n region?: string;\n countryCodeNumeric?: string;\n countryCodeAlpha2?: string;\n countryCodeAlpha3?: string;\n countryName?: string;\n}\n\nexport interface BraintreeHostedFormError extends BraintreeError {\n details?: {\n invalidFieldKeys?: string[];\n };\n}\n\n/**\n *\n * Braintree 3D Secure\n *\n */\nexport type BraintreeThreeDSecureCreator = BraintreeModuleCreator<\n BraintreeThreeDSecure,\n BraintreeThreeDSecureCreatorConfig\n>;\n\nexport interface BraintreeThreeDSecure extends BraintreeModule {\n verifyCard(options: BraintreeThreeDSecureOptions): Promise;\n cancelVerifyCard(): Promise;\n}\n\nexport interface BraintreeThreeDSecureCreatorConfig extends BraintreeModuleCreatorConfig {\n version?: number;\n}\n\nexport interface BraintreeThreeDSecureOptions {\n nonce: string;\n amount: number;\n challengeRequested: boolean;\n showLoader?: boolean;\n addFrame(error: Error | undefined, iframe: HTMLIFrameElement): void;\n removeFrame(): void;\n onLookupComplete(data: BraintreeThreeDSecureVerificationData, next: () => void): void;\n}\n\ninterface BraintreeThreeDSecureVerificationData {\n lookup: {\n threeDSecureVersion: string;\n };\n paymentMethod: BraintreeVerifyPayload;\n requiresUserAuthentication: boolean;\n threeDSecureInfo: {\n liabilityShiftPossible: boolean;\n liabilityShifted: boolean;\n };\n}\n\n/**\n *\n * Braintree PayPal\n *\n */\nexport type BraintreePaypalCreator = BraintreeModuleCreator;\n\nexport interface BraintreePaypal {\n closeWindow(): void;\n focusWindow(): void;\n tokenize(options: BraintreePaypalRequest): Promise;\n Buttons?(options: PaypalButtonOptions): PaypalButtonRender;\n}\n\n/**\n *\n * Braintree PayPal Checkout\n *\n */\nexport type BraintreePaypalCheckoutCreator = BraintreeModuleCreator;\n\nexport interface BraintreePaypalCheckout {\n loadPayPalSDK(\n config: BraintreePaypalSdkCreatorConfig,\n callback: (instance: BraintreePaypalCheckout) => void,\n ): void;\n createPayment(options: BraintreePaypalRequest): Promise;\n teardown(): Promise;\n tokenizePayment(options: PaypalAuthorizeData): Promise;\n}\n\nexport interface BraintreePaypalSdkCreatorConfig {\n components?: string;\n currency?: string;\n intent?: string;\n isCreditEnabled?: boolean;\n}\n\n/**\n *\n * Braintree Venmo\n *\n */\nexport type BraintreeVenmoCheckoutCreator = BraintreeModuleCreator<\n BraintreeVenmoCheckout,\n BraintreeVenmoCreatorConfig\n>;\n\nexport interface BraintreeVenmoCheckout extends BraintreeModule {\n tokenize(callback: (error: BraintreeError, payload: BraintreeTokenizePayload) => void): void;\n isBrowserSupported(): boolean;\n}\n\nexport interface BraintreeVenmoCreatorConfig extends BraintreeModuleCreatorConfig {\n allowDesktop: boolean;\n paymentMethodUsage: string;\n}\n\n/**\n *\n * Braintree Visa Checkout\n *\n */\nexport type BraintreeVisaCheckoutCreator = BraintreeModuleCreator;\n\nexport interface BraintreeVisaCheckout extends BraintreeModule {\n tokenize(payment: VisaCheckoutPaymentSuccessPayload): Promise;\n createInitOptions(options: Partial): VisaCheckoutInitOptions;\n}\n\n/**\n *\n * Other\n *\n */\nexport interface BraintreeHostWindow extends Window {\n braintree?: BraintreeSDK;\n paypal?: PaypalSDK;\n}\n","import {\n NotInitializedError,\n NotInitializedErrorType,\n UnsupportedBrowserError,\n} from '../../../common/error/errors';\nimport { PaypalHostWindow } from '../paypal';\n\nimport {\n BraintreeClient,\n BraintreeDataCollector,\n BraintreeError,\n BraintreeHostedFields,\n BraintreeHostedFieldsCreatorConfig,\n BraintreeModule,\n BraintreePaypal,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeThreeDSecure,\n BraintreeVenmoCheckout,\n BraintreeVisaCheckout,\n GooglePayBraintreeSDK,\n PAYPAL_COMPONENTS,\n} from './braintree';\nimport BraintreeScriptLoader from './braintree-script-loader';\n\nexport default class BraintreeSDKCreator {\n private _client?: Promise;\n private _3ds?: Promise;\n private _paypal?: Promise;\n private _paypalCheckout?: Promise;\n private _clientToken?: string;\n private _visaCheckout?: Promise;\n private _venmoCheckout?: Promise;\n private _dataCollectors: {\n default?: Promise;\n paypal?: Promise;\n } = {};\n private _googlePay?: Promise;\n private _window: PaypalHostWindow;\n\n constructor(private _braintreeScriptLoader: BraintreeScriptLoader) {\n this._window = window;\n }\n\n initialize(clientToken: string) {\n this._clientToken = clientToken;\n }\n\n getClient(): Promise {\n if (!this._clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!this._client) {\n this._client = this._braintreeScriptLoader\n .loadClient()\n .then((client) => client.create({ authorization: this._clientToken }));\n }\n\n return this._client;\n }\n\n getPaypal(): Promise {\n if (!this._paypal) {\n this._paypal = Promise.all([\n this.getClient(),\n this._braintreeScriptLoader.loadPaypal(),\n ]).then(([client, paypal]) => paypal.create({ client }));\n }\n\n return this._paypal;\n }\n\n async getPaypalCheckout(\n config: Partial,\n onSuccess: (instance: BraintreePaypalCheckout) => void,\n onError: (error: BraintreeError) => void,\n ): Promise {\n const client = await this.getClient();\n const paypalCheckout = await this._braintreeScriptLoader.loadPaypalCheckout();\n\n const paypalCheckoutConfig = { client };\n const paypalCheckoutCallback = (\n error: BraintreeError,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n if (error) {\n return onError(error);\n }\n\n const paypalSdkLoadCallback = () => onSuccess(braintreePaypalCheckout);\n const paypalSdkLoadConfig = {\n currency: config.currency,\n ...(config.isCreditEnabled && { 'enable-funding': 'paylater' }),\n components: PAYPAL_COMPONENTS.toString(),\n intent: config.intent,\n };\n\n if (!this._window.paypal) {\n braintreePaypalCheckout.loadPayPalSDK(paypalSdkLoadConfig, paypalSdkLoadCallback);\n } else {\n onSuccess(braintreePaypalCheckout);\n }\n };\n\n this._paypalCheckout = paypalCheckout.create(paypalCheckoutConfig, paypalCheckoutCallback);\n\n return this._paypalCheckout;\n }\n\n async getVenmoCheckout(\n onSuccess: (braintreeVenmoCheckout: BraintreeVenmoCheckout) => void,\n onError: (error: BraintreeError | UnsupportedBrowserError) => void,\n ): Promise {\n if (!this._venmoCheckout) {\n const client = await this.getClient();\n\n const venmoCheckout = await this._braintreeScriptLoader.loadVenmoCheckout();\n\n const venmoCheckoutConfig = {\n client,\n allowDesktop: true,\n paymentMethodUsage: 'multi_use',\n };\n\n const venmoCheckoutCallback = (\n error: BraintreeError,\n braintreeVenmoCheckout: BraintreeVenmoCheckout,\n ): void => {\n if (error) {\n return onError(error);\n }\n\n if (!braintreeVenmoCheckout.isBrowserSupported()) {\n return onError(new UnsupportedBrowserError());\n }\n\n onSuccess(braintreeVenmoCheckout);\n };\n\n this._venmoCheckout = venmoCheckout.create(venmoCheckoutConfig, venmoCheckoutCallback);\n }\n\n return this._venmoCheckout;\n }\n\n get3DS(): Promise {\n if (!this._3ds) {\n this._3ds = Promise.all([this.getClient(), this._braintreeScriptLoader.load3DS()]).then(\n ([client, threeDSecure]) => threeDSecure.create({ client, version: 2 }),\n );\n }\n\n return this._3ds;\n }\n\n getDataCollector(options?: { paypal: boolean }): Promise {\n const cacheKey = options && options.paypal ? 'paypal' : 'default';\n let cached = this._dataCollectors[cacheKey];\n\n if (!cached) {\n cached = Promise.all([\n this.getClient(),\n this._braintreeScriptLoader.loadDataCollector(),\n ])\n .then(([client, dataCollector]) =>\n dataCollector.create({ client, kount: true, ...options }),\n )\n .catch((error) => {\n if (error && error.code === 'DATA_COLLECTOR_KOUNT_NOT_ENABLED') {\n return { deviceData: undefined, teardown: () => Promise.resolve() };\n }\n\n throw error;\n });\n\n this._dataCollectors[cacheKey] = cached;\n }\n\n return cached;\n }\n\n getVisaCheckout(): Promise {\n if (!this._visaCheckout) {\n this._visaCheckout = Promise.all([\n this.getClient(),\n this._braintreeScriptLoader.loadVisaCheckout(),\n ]).then(([client, visaCheckout]) => visaCheckout.create({ client }));\n }\n\n return this._visaCheckout;\n }\n\n getGooglePaymentComponent(): Promise {\n if (!this._googlePay) {\n this._googlePay = Promise.all([\n this.getClient(),\n this._braintreeScriptLoader.loadGooglePayment(),\n ]).then(([client, googlePay]) => googlePay.create({ client }));\n }\n\n return this._googlePay;\n }\n\n async createHostedFields(\n options: Pick,\n ): Promise {\n const [client, hostedFields] = await Promise.all([\n this.getClient(),\n this._braintreeScriptLoader.loadHostedFields(),\n ]);\n\n return hostedFields.create({ ...options, client });\n }\n\n teardown(): Promise {\n return Promise.all([\n this._teardown(this._3ds),\n this._teardown(this._dataCollectors.default),\n this._teardown(this._dataCollectors.paypal),\n this._teardown(this._googlePay),\n this._teardown(this._paypalCheckout),\n this._teardown(this._venmoCheckout),\n this._teardown(this._visaCheckout),\n ]).then(() => {\n this._3ds = undefined;\n this._dataCollectors = {};\n this._googlePay = undefined;\n this._paypalCheckout = undefined;\n this._venmoCheckout = undefined;\n this._visaCheckout = undefined;\n });\n }\n\n private _teardown(module?: Promise) {\n return module\n ? module\n .then((mod) => mod.teardown())\n .catch((error) => {\n if (error.code !== 'METHOD_CALLED_AFTER_TEARDOWN') {\n throw error;\n }\n })\n : Promise.resolve();\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\nimport { GooglePayCreator } from '../googlepay';\n\nimport {\n BraintreeClientCreator,\n BraintreeDataCollectorCreator,\n BraintreeHostedFieldsCreator,\n BraintreeHostWindow,\n BraintreePaypalCheckoutCreator,\n BraintreePaypalCreator,\n BraintreeThreeDSecureCreator,\n BraintreeVenmoCheckoutCreator,\n BraintreeVisaCheckoutCreator,\n} from './braintree';\n\nconst version = '3.81.0';\n\nexport default class BraintreeScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _window: BraintreeHostWindow = window,\n ) {}\n\n loadClient(): Promise {\n return this._scriptLoader\n .loadScript(`//js.braintreegateway.com/web/${version}/js/client.min.js`)\n .then(() => {\n if (!this._window.braintree || !this._window.braintree.client) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.braintree.client;\n });\n }\n\n load3DS(): Promise {\n return this._scriptLoader\n .loadScript(`//js.braintreegateway.com/web/${version}/js/three-d-secure.min.js`)\n .then(() => {\n if (!this._window.braintree || !this._window.braintree.threeDSecure) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.braintree.threeDSecure;\n });\n }\n\n loadDataCollector(): Promise {\n return this._scriptLoader\n .loadScript(`//js.braintreegateway.com/web/${version}/js/data-collector.min.js`)\n .then(() => {\n if (!this._window.braintree || !this._window.braintree.dataCollector) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.braintree.dataCollector;\n });\n }\n\n loadPaypal(): Promise {\n return this._scriptLoader\n .loadScript(`//js.braintreegateway.com/web/${version}/js/paypal.min.js`)\n .then(() => {\n if (!this._window.braintree || !this._window.braintree.paypal) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.braintree.paypal;\n });\n }\n\n loadPaypalCheckout(): Promise {\n return this._scriptLoader\n .loadScript(`//js.braintreegateway.com/web/${version}/js/paypal-checkout.min.js`)\n .then(() => {\n if (!this._window.braintree || !this._window.braintree.paypalCheckout) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.braintree.paypalCheckout;\n });\n }\n\n loadVisaCheckout(): Promise {\n return this._scriptLoader\n .loadScript(`//js.braintreegateway.com/web/${version}/js/visa-checkout.min.js`)\n .then(() => {\n if (!this._window.braintree || !this._window.braintree.visaCheckout) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.braintree.visaCheckout;\n });\n }\n\n loadVenmoCheckout(): Promise {\n return this._scriptLoader\n .loadScript(`//js.braintreegateway.com/web/${version}/js/venmo.min.js`)\n .then(() => {\n if (!this._window.braintree?.venmo) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.braintree.venmo;\n });\n }\n\n loadGooglePayment(): Promise {\n return this._scriptLoader\n .loadScript(`//js.braintreegateway.com/web/${version}/js/google-payment.min.js`)\n .then(() => {\n if (!this._window.braintree || !this._window.braintree.googlePayment) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.braintree.googlePayment;\n });\n }\n\n async loadHostedFields(): Promise {\n await this._scriptLoader.loadScript(\n `//js.braintreegateway.com/web/${version}/js/hosted-fields.min.js`,\n );\n\n if (!this._window.braintree || !this._window.braintree.hostedFields) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.braintree.hostedFields;\n }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { Address, LegacyAddress } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { SDK_VERSION_HEADERS } from '../../../common/http-request';\n\nimport { BraintreeDataCollector } from './braintree';\nimport BraintreeSDKCreator from './braintree-sdk-creator';\nimport {\n VisaCheckoutAddress,\n VisaCheckoutInitOptions,\n VisaCheckoutPaymentSuccessPayload,\n VisaCheckoutTokenizedPayload,\n} from './visacheckout';\n\nexport default class BraintreeVisaCheckoutPaymentProcessor {\n constructor(\n private _braintreeSDKCreator: BraintreeSDKCreator,\n private _requestSender: RequestSender,\n ) {}\n\n initialize(\n clientToken: string,\n options: VisaCheckoutInitializeOptions,\n ): Promise {\n this._braintreeSDKCreator.initialize(clientToken);\n\n return this._braintreeSDKCreator.getVisaCheckout().then((visaCheckout) =>\n visaCheckout.createInitOptions({\n settings: {\n locale: options.locale,\n shipping: {\n collectShipping: options.collectShipping,\n },\n },\n paymentRequest: {\n currencyCode: options.currencyCode,\n subtotal: String(options.subtotal),\n },\n }),\n );\n }\n\n deinitialize(): Promise {\n return this._braintreeSDKCreator.teardown();\n }\n\n handleSuccess(\n payment: VisaCheckoutPaymentSuccessPayload,\n shipping?: Address,\n billing?: Address,\n ): Promise {\n return this._braintreeSDKCreator.getVisaCheckout().then((braintreeVisaCheckout) =>\n Promise.all([\n braintreeVisaCheckout.tokenize(payment),\n this._braintreeSDKCreator.getDataCollector(),\n ]).then(([tokenizedPayload, dataCollector]) => {\n const {\n shippingAddress = this._toVisaCheckoutAddress(shipping),\n billingAddress = this._toVisaCheckoutAddress(billing),\n } = tokenizedPayload;\n\n return this._postForm(\n {\n ...tokenizedPayload,\n shippingAddress,\n billingAddress,\n },\n dataCollector,\n );\n }),\n );\n }\n\n private _postForm(\n paymentData: VisaCheckoutTokenizedPayload,\n dataCollector: BraintreeDataCollector,\n ) {\n const { userData, billingAddress, shippingAddress, details: cardInformation } = paymentData;\n const { userEmail } = userData;\n const { deviceData } = dataCollector;\n\n return this._requestSender.post('/checkout.php', {\n headers: {\n Accept: 'text/html',\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...SDK_VERSION_HEADERS,\n },\n body: {\n payment_type: paymentData.type,\n nonce: paymentData.nonce,\n provider: 'braintreevisacheckout',\n action: 'set_external_checkout',\n device_data: deviceData,\n card_information: this._getCardInformation(cardInformation),\n billing_address: this._getAddress(userEmail, billingAddress),\n shipping_address: this._getAddress(userEmail, shippingAddress),\n },\n });\n }\n\n private _toVisaCheckoutAddress(address?: Address): VisaCheckoutAddress {\n if (!address) {\n return {};\n }\n\n return {\n firstName: address.firstName,\n lastName: address.lastName,\n phoneNumber: address.phone,\n streetAddress: address.address1,\n extendedAddress: address.address2,\n locality: address.city,\n region: address.stateOrProvinceCode,\n countryCode: address.countryCode,\n postalCode: address.postalCode,\n };\n }\n\n private _getAddress(email: string, address: VisaCheckoutAddress = {}): Partial {\n return {\n email,\n first_name: address.firstName,\n last_name: address.lastName,\n phone_number: address.phoneNumber,\n address_line_1: address.streetAddress,\n address_line_2: address.extendedAddress,\n city: address.locality,\n state: address.region,\n country_code: address.countryCode,\n postal_code: address.postalCode,\n };\n }\n\n private _getCardInformation(cardInformation: { cardType: string; lastTwo: string }) {\n return {\n type: cardInformation.cardType,\n number: cardInformation.lastTwo,\n };\n }\n}\n\nexport interface VisaCheckoutInitializeOptions {\n locale?: string;\n collectShipping?: boolean;\n subtotal?: number;\n currencyCode?: string;\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\nimport { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport BraintreeScriptLoader from './braintree-script-loader';\nimport BraintreeSDKCreator from './braintree-sdk-creator';\nimport BraintreeVisaCheckoutPaymentProcessor from './braintree-visacheckout-payment-processor';\n\nexport default function createBraintreeVisaCheckoutPaymentProcessor(\n scriptLoader: ScriptLoader,\n requestSender: RequestSender,\n) {\n const braintreeScriptLoader = new BraintreeScriptLoader(scriptLoader);\n const braintreeSDKCreator = new BraintreeSDKCreator(braintreeScriptLoader);\n\n return new BraintreeVisaCheckoutPaymentProcessor(braintreeSDKCreator, requestSender);\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { VisaCheckoutHostWindow, VisaCheckoutSDK } from './visacheckout';\n\nexport default class VisaCheckoutScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _window: VisaCheckoutHostWindow = window,\n ) {}\n\n load(testMode?: boolean): Promise {\n return this._scriptLoader\n .loadScript(\n `//${\n testMode ? 'sandbox-' : ''\n }assets.secure.checkout.visa.com/checkout-widget/resources/js/integration/v1/sdk.js`,\n )\n .then(() => {\n if (!this._window.V) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.V;\n });\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { ChasePayHostWindow, JPMC } from './chasepay';\n\nexport default class ChasePayScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, public _window: ChasePayHostWindow = window) {}\n\n load(testMode?: boolean): Promise {\n return this._scriptLoader\n .loadScript(\n `//pwc${\n testMode ? 'psb' : ''\n }.chase.com/pwc/checkout/js/v20170521/list.action?type=raw&applId=PWC&channelId=CWC&version=1`,\n )\n .then(() => {\n if (!this._window.JPMC) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.JPMC;\n });\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if we are unable to synchronize the checkout details of a\n * shopper with a hosted / remote checkout provider (i.e.: Amazon).\n */\nexport default class RemoteCheckoutSynchronizationError extends StandardError {\n constructor(public error?: Error) {\n super(\n 'Unable to synchronize your checkout details with a third party provider. Please try again later.',\n );\n\n this.name = 'RemoteCheckoutSynchronizationError';\n this.type = 'remote_checkout_synchronization';\n }\n}\n","import { PaymentInitializeOptions } from '../..';\nimport { Checkout, InternalCheckoutSelectors } from '../../../checkout';\nimport PaymentMethod from '../../payment-method';\nimport {\n BraintreeModuleCreator,\n BraintreeVerifyPayload,\n GooglePayBraintreeSDK,\n} from '../braintree';\n\nexport enum CallbackTriggerType {\n INITIALIZE = 'INITIALIZE',\n SHIPPING_OPTION = 'SHIPPING_OPTION',\n SHIPPING_ADDRESS = 'SHIPPING_ADDRESS',\n OFFER = 'OFFER',\n}\n\nexport enum TotalPriceStatusType {\n ESTIMATED = 'ESTIMATED',\n FINAL = 'FINAL',\n NOT_CURRENTLY_KNOWN = 'NOT_CURRENTLY_KNOWN',\n}\n\nexport enum CallbackIntentsType {\n OFFER = 'OFFER',\n PAYMENT_AUTHORIZATION = 'PAYMENT_AUTHORIZATION',\n SHIPPING_ADDRESS = 'SHIPPING_ADDRESS',\n SHIPPING_OPTION = 'SHIPPING_OPTION',\n}\n\nexport type EnvironmentType = 'PRODUCTION' | 'TEST';\nexport type TokenizeType = 'AndroidPayCard' | 'CreditCard' | 'CARD';\n\nexport interface GooglePayInitializer {\n initialize(\n checkout: Checkout | void,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n publishableKey?: string,\n ): Promise;\n teardown(): Promise;\n parseResponse(paymentData: GooglePaymentData): Promise;\n}\n\nexport interface GooglePayProviderProcessor {\n initialize(options: PaymentInitializeOptions): Promise;\n processAdditionalAction(error: unknown): Promise;\n}\n\nexport type GooglePayCreator = BraintreeModuleCreator;\n\nexport interface GooglePayPaymentOptions {\n environment: EnvironmentType;\n paymentDataCallbacks?: {\n onPaymentDataChanged(\n intermediatePaymentData: IntermediatePaymentData,\n ): Promise;\n };\n}\n\nexport type GooglePayVerifyPayload = BraintreeVerifyPayload | undefined;\n\nexport interface GooglePayIsReadyToPayResponse {\n result: boolean;\n paymentMethodPresend?: boolean;\n}\n\nexport interface GooglePaySDK {\n payments: {\n api: {\n PaymentsClient: new (options: GooglePayPaymentOptions) => GooglePayClient;\n };\n };\n}\n\nexport interface GooglePayClient {\n isReadyToPay(options: object): Promise;\n loadPaymentData(paymentDataRequest: GooglePayPaymentDataRequestV2): Promise;\n createButton(options: { [key: string]: string | object }): HTMLElement;\n}\n\nexport interface GooglePayHostWindow extends Window {\n google?: GooglePaySDK;\n}\n\nexport interface TokenizePayload {\n nonce: string;\n tokenFormat?: string;\n details: {\n cardType: string;\n lastFour: string;\n lastTwo?: string;\n };\n description?: string;\n type: TokenizeType;\n binData?: {\n commercial: string;\n countryOfIssuance: string;\n debit: string;\n durbinRegulated: string;\n healthcare: string;\n issuingBank: string;\n payroll: string;\n prepaid: string;\n productId: string;\n };\n}\n\nexport interface GooglePaymentData {\n apiVersion: number;\n apiVersionMinor: number;\n paymentMethodData: {\n description: string;\n info: {\n cardDetails: string;\n cardNetwork: string;\n billingAddress: GooglePayAddress;\n };\n tokenizationData: {\n token: string;\n type: string;\n };\n type: TokenizeType;\n };\n shippingAddress: GooglePayAddress;\n email: string;\n}\n\nexport interface GooglePayAddress {\n address1: string;\n address2: string;\n address3: string;\n administrativeArea: string;\n companyName: string;\n countryCode: string;\n locality: string;\n name: string;\n postalCode: string;\n sortingCode: string;\n phoneNumber: string;\n}\n\nexport interface GooglePaymentsError {\n statusCode: string;\n statusMessage?: string;\n}\n\nexport interface PaymentMethodData {\n methodId: string;\n paymentData: {\n method: string;\n nonce: string;\n cardInformation: {\n type: string;\n number: string;\n };\n };\n}\n\nexport enum ButtonType {\n Long = 'long',\n Short = 'short',\n}\nexport enum ButtonColor {\n Default = 'default',\n Black = 'black',\n White = 'white',\n}\n\nexport interface TokenizationSpecification {\n type: string;\n parameters: {\n gateway: string;\n gatewayMerchantId?: string;\n 'braintree:apiVersion'?: string;\n 'braintree:clientKey'?: string;\n 'braintree:merchantId'?: string;\n 'braintree:sdkVersion'?: string;\n 'braintree:authorizationFingerprint'?: string;\n 'stripe:version'?: string;\n 'stripe:publishableKey'?: string;\n };\n}\n\nexport enum BillingAddressFormat {\n /*\n * Name, country code, and postal code (default).\n */\n Min = 'MIN',\n /*\n * Name, street address, locality, region, country code, and postal code.\n */\n Full = 'FULL',\n}\n\nexport interface GooglePayPaymentDataRequestV2 {\n apiVersion: number;\n apiVersionMinor: number;\n merchantInfo: {\n authJwt?: string;\n merchantId?: string;\n merchantName?: string;\n };\n allowedPaymentMethods: [\n {\n type: string;\n parameters: {\n allowedAuthMethods: string[];\n allowedCardNetworks: string[];\n allowPrepaidCards?: boolean;\n billingAddressRequired?: boolean;\n billingAddressParameters?: {\n format?: BillingAddressFormat;\n phoneNumberRequired?: boolean;\n };\n };\n tokenizationSpecification?: TokenizationSpecification;\n },\n ];\n transactionInfo: {\n currencyCode: string;\n countryCode?: string;\n totalPriceStatus?: TotalPriceStatusType;\n totalPrice?: string;\n checkoutOption?: string;\n };\n callbackIntents?: CallbackIntentsType[];\n emailRequired?: boolean;\n shippingAddressRequired?: boolean;\n shippingAddressParameters?: {\n allowedCountryCodes?: string[];\n phoneNumberRequired?: boolean;\n };\n}\n\nexport interface UpdatePaymentDataRequestPayload {\n apiVersion?: number;\n apiVersionMinor?: number;\n merchantInfo?: {\n authJwt?: string;\n merchantId?: string;\n merchantName?: string;\n };\n allowedPaymentMethods?: [\n {\n type: string;\n parameters: {\n allowedAuthMethods: string[];\n allowedCardNetworks: string[];\n allowPrepaidCards?: boolean;\n billingAddressRequired?: boolean;\n billingAddressParameters?: {\n format?: BillingAddressFormat;\n phoneNumberRequired?: boolean;\n };\n };\n tokenizationSpecification?: TokenizationSpecification;\n },\n ];\n transactionInfo?: {\n currencyCode: string;\n countryCode?: string;\n totalPriceStatus?: TotalPriceStatusType;\n totalPrice?: string;\n checkoutOption?: string;\n };\n callbackIntents?: CallbackIntentsType[];\n emailRequired?: boolean;\n shippingAddressRequired?: boolean;\n shippingAddressParameters?: {\n allowedCountryCodes?: string[];\n phoneNumberRequired?: boolean;\n };\n}\n\nexport interface NewTransactionInfo {\n newTransactionInfo: {\n currencyCode: string;\n totalPrice: string;\n totalPriceStatus: TotalPriceStatusType;\n };\n}\n\nexport interface IntermediatePaymentData {\n callbackTrigger: CallbackTriggerType;\n}\n\nexport type GooglePayTransactionInfo = Pick;\n","export function getFirstAndLastName(fullName: string): [string, string] {\n const nameParts = fullName.split(' ');\n\n if (nameParts.length === 1) {\n return [fullName, ''];\n }\n\n const firstName = nameParts.slice(0, -1).join(' ');\n const lastName = nameParts[nameParts.length - 1];\n\n return [firstName, lastName];\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { PaymentMethodInvalidError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { AddressRequestBody } from '../../../address';\nimport { BillingAddressActionCreator, BillingAddressUpdateRequestBody } from '../../../billing';\nimport { Checkout, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { SDK_VERSION_HEADERS } from '../../../common/http-request';\nimport { RemoteCheckoutSynchronizationError } from '../../../remote-checkout/errors';\nimport { ConsignmentActionCreator } from '../../../shipping';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\n\nimport {\n ButtonColor,\n ButtonType,\n EnvironmentType,\n GooglePayAddress,\n GooglePayClient,\n GooglePayInitializer,\n GooglePaymentData,\n GooglePayPaymentDataRequestV2,\n GooglePayPaymentOptions,\n GooglePaySDK,\n TokenizePayload,\n UpdatePaymentDataRequestPayload,\n} from './googlepay';\nimport { getFirstAndLastName } from './googlepay-get-first-and-last-name';\nimport GooglePayScriptLoader from './googlepay-script-loader';\n\nexport default class GooglePayPaymentProcessor {\n private _googlePayClient?: GooglePayClient;\n private _methodId?: string;\n private _paymentDataRequest?: GooglePayPaymentDataRequestV2;\n private _isBuyNowFlow = false;\n\n constructor(\n private _store: CheckoutStore,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _googlePayScriptLoader: GooglePayScriptLoader,\n private _googlePayInitializer: GooglePayInitializer,\n private _billingAddressActionCreator: BillingAddressActionCreator,\n private _consignmentActionCreator: ConsignmentActionCreator,\n private _requestSender: RequestSender,\n ) {}\n\n initialize(methodId: string, googlePayClientOptions?: GooglePayPaymentOptions): Promise {\n this._methodId = methodId;\n\n return this._configureWallet(googlePayClientOptions);\n }\n\n deinitialize(): Promise {\n return this._googlePayInitializer.teardown();\n }\n\n createButton(\n onClick: (event: Event) => Promise,\n buttonType: ButtonType = ButtonType.Short,\n buttonColor: ButtonColor = ButtonColor.Default,\n ): HTMLElement {\n if (!this._googlePayClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._googlePayClient.createButton({\n buttonColor,\n buttonType,\n onClick,\n });\n }\n\n updatePaymentDataRequest(paymentDataRequest: UpdatePaymentDataRequestPayload) {\n const existingPaymentDataRequest = this._getPaymentDataRequest();\n\n this._paymentDataRequest = {\n ...existingPaymentDataRequest,\n ...paymentDataRequest,\n merchantInfo: {\n ...(existingPaymentDataRequest.merchantInfo ?? {}),\n ...(paymentDataRequest.merchantInfo ?? {}),\n },\n transactionInfo: {\n ...(existingPaymentDataRequest.transactionInfo ?? {}),\n ...(paymentDataRequest.transactionInfo ?? {}),\n },\n shippingAddressParameters: {\n ...(existingPaymentDataRequest.shippingAddressParameters ?? {}),\n ...(paymentDataRequest.shippingAddressParameters ?? {}),\n },\n };\n }\n\n displayWallet(): Promise {\n if (!this._googlePayClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._googlePayClient.loadPaymentData(this._getPaymentDataRequest());\n }\n\n handleSuccess(paymentData: GooglePaymentData): Promise {\n return this._googlePayInitializer\n .parseResponse(paymentData)\n .then((tokenizePayload) => this._postForm(tokenizePayload))\n .then(() => this._updateBillingAddress(paymentData));\n }\n\n updateShippingAddress(shippingAddress: GooglePayAddress): Promise {\n return this._store.dispatch(\n this._consignmentActionCreator.updateAddress(\n this._mapGooglePayAddressToShippingAddress(shippingAddress),\n ),\n );\n }\n\n updateBuyNowFlowFlag(isBuyNowFlow: boolean): void {\n this._isBuyNowFlow = isBuyNowFlow;\n }\n\n private _configureWallet(\n googlePayClientOptions?: Partial,\n ): Promise {\n const features = this._store.getState().config.getStoreConfig()?.checkoutSettings.features;\n const options =\n features && features['INT-5826.google_hostname_alias']\n ? { params: { origin: window.location.hostname } }\n : undefined;\n const methodId = this._getMethodId();\n\n return this._store\n .dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId, options))\n .then((state) => {\n const checkout = this._getCheckout(state);\n const paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n const hasShippingAddress = !!state.shippingAddress.getShippingAddress();\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { testMode } = paymentMethod.config;\n\n return Promise.all([\n this._googlePayScriptLoader.load(),\n this._googlePayInitializer.initialize(\n checkout,\n paymentMethod,\n hasShippingAddress,\n ),\n ]).then(([googlePay, paymentDataRequest]) => {\n this._googlePayClient = this._getGooglePayClient(\n googlePay,\n testMode,\n googlePayClientOptions,\n );\n this._paymentDataRequest = paymentDataRequest;\n\n return this._googlePayClient\n .isReadyToPay({\n allowedPaymentMethods: [\n {\n type: paymentDataRequest.allowedPaymentMethods[0].type,\n parameters: {\n allowedAuthMethods:\n paymentDataRequest.allowedPaymentMethods[0].parameters\n .allowedAuthMethods,\n allowedCardNetworks:\n paymentDataRequest.allowedPaymentMethods[0].parameters\n .allowedCardNetworks,\n },\n },\n ],\n apiVersion: paymentDataRequest.apiVersion,\n apiVersionMinor: paymentDataRequest.apiVersionMinor,\n })\n .then((response) => {\n if (response.result) {\n return;\n }\n\n throw new PaymentMethodInvalidError();\n });\n });\n });\n }\n\n private _getCardInformation(cardInformation: { cardType: string; lastFour: string }) {\n return {\n type: cardInformation.cardType,\n number: cardInformation.lastFour,\n };\n }\n\n private _getCheckout(state: InternalCheckoutSelectors): Checkout | void {\n if (this._isBuyNowFlow) {\n return;\n }\n\n const checkout = state.checkout.getCheckout();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n return checkout;\n }\n\n private _getPaymentDataRequest(): GooglePayPaymentDataRequestV2 {\n if (!this._paymentDataRequest) {\n throw new RemoteCheckoutSynchronizationError();\n }\n\n return this._paymentDataRequest;\n }\n\n private _getGooglePayClient(\n google: GooglePaySDK,\n testMode?: boolean,\n googlePayClientOptions?: Partial,\n ): GooglePayClient {\n if (testMode === undefined) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const environment: EnvironmentType = testMode ? 'TEST' : 'PRODUCTION';\n\n return new google.payments.api.PaymentsClient({\n environment,\n ...(googlePayClientOptions ?? {}),\n });\n }\n\n private _getMethodId(): string {\n if (!this._methodId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._methodId;\n }\n\n private _mapGooglePayAddressToBillingAddress(\n paymentData: GooglePaymentData,\n id: string,\n customerEmail?: string,\n ): BillingAddressUpdateRequestBody {\n const fullName = paymentData.paymentMethodData.info.billingAddress.name;\n const [firstName, lastName] = getFirstAndLastName(fullName);\n const address1 = paymentData.paymentMethodData.info.billingAddress.address1;\n const city = paymentData.paymentMethodData.info.billingAddress.locality;\n const postalCode = paymentData.paymentMethodData.info.billingAddress.postalCode;\n const countryCode = paymentData.paymentMethodData.info.billingAddress.countryCode;\n\n if (!firstName || !address1 || !city || !postalCode || !countryCode) {\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n\n return {\n id,\n firstName,\n lastName,\n company: paymentData.paymentMethodData.info.billingAddress.companyName,\n address1,\n address2:\n paymentData.paymentMethodData.info.billingAddress.address2 +\n paymentData.paymentMethodData.info.billingAddress.address3,\n city,\n stateOrProvince: paymentData.paymentMethodData.info.billingAddress.administrativeArea,\n stateOrProvinceCode:\n paymentData.paymentMethodData.info.billingAddress.administrativeArea,\n postalCode,\n countryCode,\n phone: paymentData.paymentMethodData.info.billingAddress.phoneNumber,\n customFields: [],\n email: customerEmail || paymentData.email,\n };\n }\n\n private _mapGooglePayAddressToShippingAddress(address: GooglePayAddress): AddressRequestBody {\n const [firstName, lastName] = getFirstAndLastName(address.name);\n\n return {\n firstName,\n lastName,\n company: address.companyName,\n address1: address.address1,\n address2: address.address2 + address.address3,\n city: address.locality,\n stateOrProvince: address.administrativeArea,\n stateOrProvinceCode: address.administrativeArea,\n postalCode: address.postalCode,\n countryCode: address.countryCode,\n phone: address.phoneNumber,\n customFields: [],\n };\n }\n\n private _postForm(postPaymentData: TokenizePayload): Promise> {\n const cardInformation = postPaymentData.details;\n const buyNowCartId = this._isBuyNowFlow\n ? this._store.getState().cart.getCartOrThrow().id\n : undefined;\n\n return this._requestSender.post('/checkout.php', {\n headers: {\n Accept: 'text/html',\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...SDK_VERSION_HEADERS,\n },\n body: {\n payment_type: postPaymentData.type,\n nonce: postPaymentData.nonce,\n tokenFormat: postPaymentData.tokenFormat,\n provider: this._getMethodId(),\n action: 'set_external_checkout',\n card_information: this._getCardInformation(cardInformation),\n ...(buyNowCartId && { cart_id: buyNowCartId }),\n },\n });\n }\n\n private _updateBillingAddress(\n paymentData: GooglePaymentData,\n ): Promise {\n const remoteBillingAddress = this._store.getState().billingAddress.getBillingAddress();\n\n if (!remoteBillingAddress) {\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n\n const googlePayAddressMapped = this._mapGooglePayAddressToBillingAddress(\n paymentData,\n remoteBillingAddress.id,\n remoteBillingAddress.email,\n );\n\n return this._store.dispatch(\n this._billingAddressActionCreator.updateAddress(googlePayAddressMapped),\n );\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { GooglePayHostWindow, GooglePaySDK } from './googlepay';\n\nexport default class GooglePayScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _window: GooglePayHostWindow = window,\n ) {}\n\n load(): Promise {\n return this._scriptLoader.loadScript('https://pay.google.com/gp/p/js/pay.js').then(() => {\n if (!this._window.google) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.google;\n });\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { BillingAddressActionCreator, BillingAddressRequestSender } from '../../../billing';\nimport { CheckoutRequestSender, CheckoutStore } from '../../../checkout';\nimport { ConsignmentActionCreator, ConsignmentRequestSender } from '../../../shipping';\nimport { SubscriptionsActionCreator, SubscriptionsRequestSender } from '../../../subscription';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport PaymentMethodRequestSender from '../../payment-method-request-sender';\n\nimport { GooglePayInitializer } from './googlepay';\nimport GooglePayPaymentProcessor from './googlepay-payment-processor';\nimport GooglePayScriptLoader from './googlepay-script-loader';\n\nexport default function createGooglePayPaymentProcessor(\n store: CheckoutStore,\n initializer: GooglePayInitializer,\n): GooglePayPaymentProcessor {\n const requestSender = createRequestSender();\n const scriptLoader = getScriptLoader();\n\n return new GooglePayPaymentProcessor(\n store,\n new PaymentMethodActionCreator(new PaymentMethodRequestSender(requestSender)),\n new GooglePayScriptLoader(scriptLoader),\n initializer,\n new BillingAddressActionCreator(\n new BillingAddressRequestSender(requestSender),\n new SubscriptionsActionCreator(new SubscriptionsRequestSender(requestSender)),\n ),\n new ConsignmentActionCreator(\n new ConsignmentRequestSender(requestSender),\n new CheckoutRequestSender(requestSender),\n ),\n requestSender,\n );\n}\n","import { round } from 'lodash';\n\nimport { Checkout } from '../../../checkout';\nimport PaymentMethod from '../../payment-method';\n\nimport {\n BillingAddressFormat,\n GooglePayInitializer,\n GooglePaymentData,\n GooglePayPaymentDataRequestV2,\n TokenizePayload,\n TotalPriceStatusType,\n} from './googlepay';\n\nexport default class GooglePayAdyenV2Initializer implements GooglePayInitializer {\n initialize(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): Promise {\n return Promise.resolve(\n this._getGooglePayPaymentDataRequest(checkout, paymentMethod, hasShippingAddress),\n );\n }\n\n teardown(): Promise {\n return Promise.resolve();\n }\n\n parseResponse(paymentData: GooglePaymentData): Promise {\n const {\n paymentMethodData: {\n type,\n tokenizationData: { token },\n info: { cardNetwork: cardType, cardDetails: lastFour },\n },\n } = paymentData;\n\n return Promise.resolve({\n type,\n nonce: token,\n details: {\n cardType,\n lastFour,\n },\n });\n }\n\n private _getGooglePayPaymentDataRequest(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): GooglePayPaymentDataRequestV2 {\n const currencyCode = checkout?.cart.currency.code || '';\n const totalPrice = checkout?.outstandingBalance\n ? round(checkout.outstandingBalance, 2).toFixed(2)\n : '';\n\n const {\n initializationData: {\n gatewayMerchantId,\n storeCountry: countryCode,\n googleMerchantName: merchantName,\n googleMerchantId: merchantId,\n platformToken: authJwt,\n },\n supportedCards,\n } = paymentMethod;\n\n return {\n apiVersion: 2,\n apiVersionMinor: 0,\n merchantInfo: {\n authJwt,\n merchantId,\n merchantName,\n },\n allowedPaymentMethods: [\n {\n type: 'CARD',\n parameters: {\n allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n allowedCardNetworks: supportedCards.map((card) =>\n card === 'MC' ? 'MASTERCARD' : card,\n ),\n billingAddressRequired: true,\n billingAddressParameters: {\n format: BillingAddressFormat.Full,\n phoneNumberRequired: true,\n },\n },\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY',\n parameters: {\n gateway: 'adyen',\n gatewayMerchantId,\n },\n },\n },\n ],\n transactionInfo: {\n countryCode,\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n emailRequired: true,\n shippingAddressRequired: !hasShippingAddress,\n shippingAddressParameters: {\n phoneNumberRequired: true,\n },\n };\n }\n}\n","import { round } from 'lodash';\n\nimport { Checkout } from '../../../checkout';\nimport PaymentMethod from '../../payment-method';\n\nimport {\n BillingAddressFormat,\n GooglePayInitializer,\n GooglePaymentData,\n GooglePayPaymentDataRequestV2,\n TokenizePayload,\n TotalPriceStatusType,\n} from './googlepay';\n\nexport default class GooglePayAdyenV3Initializer implements GooglePayInitializer {\n initialize(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): Promise {\n return Promise.resolve(\n this._getGooglePayPaymentDataRequest(checkout, paymentMethod, hasShippingAddress),\n );\n }\n\n teardown(): Promise {\n return Promise.resolve();\n }\n\n parseResponse(paymentData: GooglePaymentData): Promise {\n const {\n paymentMethodData: {\n type,\n tokenizationData: { token },\n info: { cardNetwork: cardType, cardDetails: lastFour },\n },\n } = paymentData;\n\n return Promise.resolve({\n type,\n nonce: token,\n details: {\n cardType,\n lastFour,\n },\n });\n }\n\n private _getGooglePayPaymentDataRequest(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): GooglePayPaymentDataRequestV2 {\n const currencyCode = checkout?.cart.currency.code || '';\n const totalPrice = checkout?.outstandingBalance\n ? round(checkout.outstandingBalance, 2).toFixed(2)\n : '';\n\n const {\n initializationData: {\n gatewayMerchantId,\n storeCountry: countryCode,\n googleMerchantName: merchantName,\n googleMerchantId: merchantId,\n platformToken: authJwt,\n },\n supportedCards,\n } = paymentMethod;\n\n return {\n apiVersion: 2,\n apiVersionMinor: 0,\n merchantInfo: {\n authJwt,\n merchantId,\n merchantName,\n },\n allowedPaymentMethods: [\n {\n type: 'CARD',\n parameters: {\n allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n allowedCardNetworks: supportedCards.map((card) =>\n card === 'MC' ? 'MASTERCARD' : card,\n ),\n billingAddressRequired: true,\n billingAddressParameters: {\n format: BillingAddressFormat.Full,\n phoneNumberRequired: true,\n },\n },\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY',\n parameters: {\n gateway: 'adyen',\n gatewayMerchantId,\n },\n },\n },\n ],\n transactionInfo: {\n countryCode,\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n emailRequired: true,\n shippingAddressRequired: !hasShippingAddress,\n shippingAddressParameters: {\n phoneNumberRequired: true,\n },\n };\n }\n}\n","import { round } from 'lodash';\n\nimport { PaymentMethod } from '../..';\nimport { Checkout } from '../../../checkout';\n\nimport {\n BillingAddressFormat,\n GooglePayInitializer,\n GooglePaymentData,\n GooglePayPaymentDataRequestV2,\n TokenizationSpecification,\n TokenizePayload,\n TotalPriceStatusType,\n} from './googlepay';\n\nconst baseRequest = {\n apiVersion: 2,\n apiVersionMinor: 0,\n};\n\nexport default class GooglePayAuthorizeNetInitializer implements GooglePayInitializer {\n initialize(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): Promise {\n return Promise.resolve(\n this._getGooglePaymentDataRequest(checkout, paymentMethod, hasShippingAddress),\n );\n }\n\n teardown(): Promise {\n return Promise.resolve();\n }\n\n parseResponse(paymentData: GooglePaymentData): Promise {\n const {\n paymentMethodData: {\n type,\n tokenizationData: { token },\n info: { cardNetwork: cardType, cardDetails: lastFour },\n },\n } = paymentData;\n\n return Promise.resolve({\n type,\n nonce: btoa(token),\n details: {\n cardType,\n lastFour,\n },\n });\n }\n\n private _getGooglePaymentDataRequest(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): GooglePayPaymentDataRequestV2 {\n const currencyCode = checkout?.cart.currency.code || '';\n const totalPrice = checkout?.outstandingBalance\n ? round(checkout.outstandingBalance, 2).toFixed(2)\n : '';\n\n const {\n initializationData: {\n paymentGatewayId: gatewayMerchantId,\n storeCountry: countryCode,\n googleMerchantName: merchantName,\n googleMerchantId: merchantId,\n platformToken: authJwt,\n },\n supportedCards,\n } = paymentMethod;\n\n const paymentGatewaySpecification = this._getPaymentGatewaySpecification(gatewayMerchantId);\n const cardPaymentMethod = this._getCardPaymentMethod(\n paymentGatewaySpecification,\n supportedCards,\n );\n\n return {\n ...baseRequest,\n allowedPaymentMethods: [cardPaymentMethod],\n transactionInfo: {\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n currencyCode,\n countryCode,\n },\n merchantInfo: {\n merchantName,\n merchantId,\n authJwt,\n },\n emailRequired: true,\n shippingAddressRequired: !hasShippingAddress,\n shippingAddressParameters: {\n phoneNumberRequired: true,\n },\n };\n }\n\n private _getPaymentGatewaySpecification(gatewayMerchantId: string) {\n return {\n type: 'PAYMENT_GATEWAY',\n parameters: {\n gateway: 'authorizenet',\n gatewayMerchantId,\n },\n };\n }\n\n private _getCardPaymentMethod(\n tokenizationSpecification: TokenizationSpecification,\n supportedCards: string[],\n ) {\n return {\n type: 'CARD',\n parameters: {\n allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n allowedCardNetworks: supportedCards.map((card) =>\n card === 'MC' ? 'MASTERCARD' : card,\n ),\n billingAddressRequired: true,\n billingAddressParameters: {\n format: BillingAddressFormat.Full,\n phoneNumberRequired: true,\n },\n },\n tokenizationSpecification,\n };\n }\n}\n","import { round } from 'lodash';\n\nimport { Checkout } from '../../../checkout';\nimport PaymentMethod from '../../payment-method';\n\nimport {\n BillingAddressFormat,\n GooglePayInitializer,\n GooglePaymentData,\n GooglePayPaymentDataRequestV2,\n TokenizePayload,\n TotalPriceStatusType,\n} from './googlepay';\n\nexport default class GooglePayBNZInitializer implements GooglePayInitializer {\n initialize(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): Promise {\n return Promise.resolve(\n this._getGooglePayPaymentDataRequest(checkout, paymentMethod, hasShippingAddress),\n );\n }\n\n teardown(): Promise {\n return Promise.resolve();\n }\n\n parseResponse(paymentData: GooglePaymentData): Promise {\n const {\n paymentMethodData: {\n type,\n tokenizationData: { token },\n info: { cardNetwork: cardType, cardDetails: lastFour },\n },\n } = paymentData;\n\n return Promise.resolve({\n nonce: btoa(token),\n type,\n details: {\n cardType,\n lastFour,\n },\n });\n }\n\n private _getGooglePayPaymentDataRequest(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): GooglePayPaymentDataRequestV2 {\n const currencyCode = checkout?.cart.currency.code || '';\n const totalPrice = checkout?.outstandingBalance\n ? round(checkout.outstandingBalance, 2).toFixed(2)\n : '';\n\n const {\n initializationData: {\n gatewayMerchantId,\n googleMerchantName: merchantName,\n googleMerchantId: merchantId,\n platformToken: authJwt,\n },\n supportedCards,\n } = paymentMethod;\n\n return {\n apiVersion: 2,\n apiVersionMinor: 0,\n merchantInfo: {\n authJwt,\n merchantId,\n merchantName,\n },\n allowedPaymentMethods: [\n {\n type: 'CARD',\n parameters: {\n allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n allowedCardNetworks: supportedCards.map((card) =>\n card === 'MC' ? 'MASTERCARD' : card,\n ),\n billingAddressRequired: true,\n billingAddressParameters: {\n format: BillingAddressFormat.Full,\n phoneNumberRequired: true,\n },\n },\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY',\n parameters: {\n gateway: 'cybersource',\n gatewayMerchantId,\n },\n },\n },\n ],\n transactionInfo: {\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n emailRequired: true,\n shippingAddressRequired: !hasShippingAddress,\n shippingAddressParameters: {\n phoneNumberRequired: true,\n },\n };\n }\n}\n","import { round } from 'lodash';\n\nimport { Checkout } from '../../../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../../../common/error/errors';\nimport PaymentMethod from '../../payment-method';\nimport { BraintreeSDKCreator, GooglePayBraintreeSDK } from '../braintree';\n\nimport {\n BillingAddressFormat,\n GooglePayInitializer,\n GooglePaymentData,\n GooglePayPaymentDataRequestV2,\n TokenizePayload,\n TotalPriceStatusType,\n} from './googlepay';\nimport {\n GooglePayBraintreeDataRequest,\n GooglePayBraintreePaymentDataRequestV1,\n} from './googlepay-braintree';\n\nexport default class GooglePayBraintreeInitializer implements GooglePayInitializer {\n private _googlePaymentInstance!: GooglePayBraintreeSDK;\n\n constructor(private _braintreeSDKCreator: BraintreeSDKCreator) {}\n\n initialize(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): Promise {\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._braintreeSDKCreator.initialize(paymentMethod.clientToken);\n\n return this._braintreeSDKCreator\n .getGooglePaymentComponent()\n .then((googleBraintreePaymentInstance) => {\n this._googlePaymentInstance = googleBraintreePaymentInstance;\n\n return this._createGooglePayPayload(\n checkout,\n paymentMethod.initializationData,\n hasShippingAddress,\n );\n });\n }\n\n teardown(): Promise {\n return this._braintreeSDKCreator.teardown();\n }\n\n parseResponse(paymentData: GooglePaymentData): Promise {\n const payload = JSON.parse(paymentData.paymentMethodData.tokenizationData.token)\n .androidPayCards[0];\n\n return Promise.resolve({\n nonce: payload.nonce,\n type: payload.type,\n description: payload.description,\n details: {\n cardType: payload.details.cardType,\n lastFour: payload.details.lastFour,\n lastTwo: payload.details.lastTwo,\n },\n binData: payload.binData,\n });\n }\n\n private _createGooglePayPayload(\n checkout: Checkout | undefined,\n initializationData: any,\n hasShippingAddress: boolean,\n ): GooglePayPaymentDataRequestV2 {\n if (!initializationData.platformToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const currencyCode = checkout?.cart.currency.code || '';\n const totalPrice = checkout?.outstandingBalance\n ? round(checkout.outstandingBalance, 2).toFixed(2)\n : '';\n\n const googlePayBraintreePaymentDataRequest: GooglePayBraintreeDataRequest = {\n merchantInfo: {\n authJwt: initializationData.platformToken,\n merchantName: initializationData.googleMerchantName,\n merchantId: initializationData.googleMerchantId,\n },\n transactionInfo: {\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n cardRequirements: {\n billingAddressRequired: true,\n billingAddressFormat: 'FULL',\n },\n shippingAddressRequired: !hasShippingAddress,\n emailRequired: true,\n phoneNumberRequired: true,\n };\n\n return this._mapGooglePayBraintreeDataRequestToGooglePayDataRequestV2(\n this._googlePaymentInstance.createPaymentDataRequest(\n googlePayBraintreePaymentDataRequest,\n ),\n );\n }\n\n private _mapGooglePayBraintreeDataRequestToGooglePayDataRequestV2(\n googlePayBraintreeDataRequestV1: GooglePayBraintreePaymentDataRequestV1,\n ): GooglePayPaymentDataRequestV2 {\n return {\n apiVersion: 2,\n apiVersionMinor: 0,\n merchantInfo: {\n authJwt: googlePayBraintreeDataRequestV1.merchantInfo.authJwt,\n merchantId: googlePayBraintreeDataRequestV1.merchantInfo.merchantId,\n merchantName: googlePayBraintreeDataRequestV1.merchantInfo.merchantName,\n },\n allowedPaymentMethods: [\n {\n type: 'CARD',\n parameters: {\n allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n allowedCardNetworks:\n googlePayBraintreeDataRequestV1.cardRequirements.allowedCardNetworks,\n billingAddressRequired: true,\n billingAddressParameters: {\n format: BillingAddressFormat.Full,\n phoneNumberRequired: true,\n },\n },\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY',\n parameters: {\n gateway: 'braintree',\n 'braintree:apiVersion': 'v1',\n 'braintree:authorizationFingerprint':\n googlePayBraintreeDataRequestV1.paymentMethodTokenizationParameters\n .parameters['braintree:authorizationFingerprint'],\n 'braintree:merchantId':\n googlePayBraintreeDataRequestV1.paymentMethodTokenizationParameters\n .parameters['braintree:merchantId'],\n 'braintree:sdkVersion':\n googlePayBraintreeDataRequestV1.paymentMethodTokenizationParameters\n .parameters['braintree:sdkVersion'],\n },\n },\n },\n ],\n transactionInfo: googlePayBraintreeDataRequestV1.transactionInfo,\n emailRequired: true,\n shippingAddressRequired: googlePayBraintreeDataRequestV1.shippingAddressRequired,\n shippingAddressParameters: {\n phoneNumberRequired: googlePayBraintreeDataRequestV1.phoneNumberRequired,\n },\n };\n }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\nimport { round } from 'lodash';\n\nimport { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Checkout } from '../../../checkout';\nimport { InvalidArgumentError } from '../../../common/error/errors';\nimport { ContentType } from '../../../common/http-request';\nimport PaymentMethod from '../../payment-method';\nimport { CheckoutcomGooglePayToken, CheckoutcomToken } from '../checkoutcom';\n\nimport {\n BillingAddressFormat,\n GooglePayInitializer,\n GooglePaymentData,\n GooglePayPaymentDataRequestV2,\n TokenizePayload,\n TotalPriceStatusType,\n} from './googlepay';\n\nexport default class GooglePayCheckoutcomInitializer implements GooglePayInitializer {\n private _publishableKey = '';\n private _testMode = true;\n private _errorMessage = 'Unable to parse response from GooglePay.';\n\n constructor(private _requestSender: RequestSender) {}\n\n async initialize(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): Promise {\n this._publishableKey = paymentMethod.initializationData.checkoutcomkey;\n this._testMode = !!paymentMethod.config.testMode;\n\n return this._mapGooglePayCheckoutcomDataRequestToGooglePayDataRequestV2(\n checkout,\n paymentMethod.initializationData,\n hasShippingAddress,\n );\n }\n\n teardown(): Promise {\n return Promise.resolve();\n }\n\n async parseResponse(paymentData: GooglePaymentData): Promise {\n let token;\n\n try {\n token = JSON.parse(paymentData.paymentMethodData.tokenizationData.token);\n } catch (err) {\n throw new InvalidArgumentError(this._errorMessage);\n }\n\n if (!token.signature || !token.protocolVersion || !token.signedMessage) {\n throw new PaymentMethodFailedError(this._errorMessage);\n }\n\n const finalToken = await this._convertToken(this._testMode, this._publishableKey, token);\n\n const payload: TokenizePayload = {\n nonce: finalToken.token,\n type: 'CreditCard',\n description: paymentData.paymentMethodData.description,\n details: {\n cardType: paymentData.paymentMethodData.info.cardNetwork,\n lastFour: paymentData.paymentMethodData.info.cardDetails,\n },\n };\n\n if (finalToken.token_format) {\n payload.tokenFormat = finalToken.token_format;\n }\n\n return payload;\n }\n\n private async _convertToken(\n testMode: boolean,\n checkoutcomkey: string,\n token: CheckoutcomGooglePayToken,\n ): Promise {\n const checkoutcomToken: CheckoutcomToken = await this._requestCheckoutcomTokenize(\n testMode,\n checkoutcomkey,\n {\n type: 'googlepay',\n token_data: token,\n },\n );\n\n if (!checkoutcomToken || !checkoutcomToken.token) {\n throw new PaymentMethodFailedError('Unable to parse response from Checkout.com');\n }\n\n return checkoutcomToken;\n }\n\n private async _requestCheckoutcomTokenize(\n testMode: boolean,\n checkoutcomKey: string,\n data = {},\n ): Promise {\n const TEST_URL = 'https://api.sandbox.checkout.com/tokens';\n const LIVE_URL = 'https://api.checkout.com/tokens';\n\n const url = testMode ? TEST_URL : LIVE_URL;\n\n const response = await this._requestSender.post(url, {\n credentials: false,\n body: data,\n headers: {\n 'Content-Type': ContentType.Json,\n Authorization: checkoutcomKey,\n 'X-XSRF-TOKEN': null,\n },\n });\n\n return response.body as CheckoutcomToken;\n }\n\n private _mapGooglePayCheckoutcomDataRequestToGooglePayDataRequestV2(\n checkout: Checkout | undefined,\n initializationData: any,\n hasShippingAddress: boolean,\n ): GooglePayPaymentDataRequestV2 {\n const currencyCode = checkout?.cart.currency.code || '';\n const totalPrice = checkout?.outstandingBalance\n ? round(checkout.outstandingBalance, 2).toFixed(2)\n : '';\n\n return {\n apiVersion: 2,\n apiVersionMinor: 0,\n merchantInfo: {\n authJwt: initializationData.platformToken,\n merchantId: initializationData.googleMerchantId,\n merchantName: initializationData.googleMerchantName,\n },\n allowedPaymentMethods: [\n {\n type: 'CARD',\n parameters: {\n allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n allowedCardNetworks: ['AMEX', 'DISCOVER', 'JCB', 'MASTERCARD', 'VISA'],\n billingAddressRequired: true,\n billingAddressParameters: {\n format: BillingAddressFormat.Full,\n phoneNumberRequired: true,\n },\n },\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY',\n parameters: {\n gateway: 'checkoutltd',\n gatewayMerchantId: initializationData.checkoutcomkey,\n },\n },\n },\n ],\n transactionInfo: {\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n emailRequired: true,\n shippingAddressRequired: !hasShippingAddress,\n shippingAddressParameters: {\n phoneNumberRequired: true,\n },\n };\n }\n}\n","import { round } from 'lodash';\n\nimport { Checkout } from '../../../checkout';\nimport PaymentMethod from '../../payment-method';\n\nimport {\n BillingAddressFormat,\n GooglePayInitializer,\n GooglePaymentData,\n GooglePayPaymentDataRequestV2,\n TokenizePayload,\n TotalPriceStatusType,\n} from './googlepay';\n\nexport default class GooglePayCybersourceV2Initializer implements GooglePayInitializer {\n initialize(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): Promise {\n return Promise.resolve(\n this._getGooglePayPaymentDataRequest(checkout, paymentMethod, hasShippingAddress),\n );\n }\n\n teardown(): Promise {\n return Promise.resolve();\n }\n\n parseResponse(paymentData: GooglePaymentData): Promise {\n const {\n paymentMethodData: {\n type,\n tokenizationData: { token },\n info: { cardNetwork: cardType, cardDetails: lastFour },\n },\n } = paymentData;\n\n return Promise.resolve({\n nonce: btoa(token),\n type,\n details: {\n cardType,\n lastFour,\n },\n });\n }\n\n private _getGooglePayPaymentDataRequest(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): GooglePayPaymentDataRequestV2 {\n const currencyCode = checkout?.cart.currency.code || '';\n const totalPrice = checkout?.outstandingBalance\n ? round(checkout.outstandingBalance, 2).toFixed(2)\n : '';\n\n const {\n initializationData: {\n gatewayMerchantId,\n googleMerchantName: merchantName,\n googleMerchantId: merchantId,\n platformToken: authJwt,\n },\n supportedCards,\n } = paymentMethod;\n\n return {\n apiVersion: 2,\n apiVersionMinor: 0,\n merchantInfo: {\n authJwt,\n merchantId,\n merchantName,\n },\n allowedPaymentMethods: [\n {\n type: 'CARD',\n parameters: {\n allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n allowedCardNetworks: supportedCards.map((card) =>\n card === 'MC' ? 'MASTERCARD' : card,\n ),\n billingAddressRequired: true,\n billingAddressParameters: {\n format: BillingAddressFormat.Full,\n phoneNumberRequired: true,\n },\n },\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY',\n parameters: {\n gateway: 'cybersource',\n gatewayMerchantId,\n },\n },\n },\n ],\n transactionInfo: {\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n emailRequired: true,\n shippingAddressRequired: !hasShippingAddress,\n shippingAddressParameters: {\n phoneNumberRequired: true,\n },\n };\n }\n}\n","import { round } from 'lodash';\n\nimport { Checkout } from '../../../checkout';\nimport PaymentMethod from '../../payment-method';\n\nimport {\n BillingAddressFormat,\n GooglePayInitializer,\n GooglePaymentData,\n GooglePayPaymentDataRequestV2,\n TokenizePayload,\n TotalPriceStatusType,\n} from './googlepay';\n\nexport default class GooglePayOrbitalInitializer implements GooglePayInitializer {\n initialize(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): Promise {\n return Promise.resolve(\n this._getGooglePayPaymentDataRequest(checkout, paymentMethod, hasShippingAddress),\n );\n }\n\n teardown(): Promise {\n return Promise.resolve();\n }\n\n parseResponse(paymentData: GooglePaymentData): Promise {\n const {\n paymentMethodData: {\n type,\n tokenizationData: { token },\n info: { cardNetwork: cardType, cardDetails: lastFour },\n },\n } = paymentData;\n\n return Promise.resolve({\n nonce: btoa(token),\n type,\n details: {\n cardType,\n lastFour,\n },\n });\n }\n\n private _getGooglePayPaymentDataRequest(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): GooglePayPaymentDataRequestV2 {\n const currencyCode = checkout?.cart.currency.code || '';\n const totalPrice = checkout?.outstandingBalance\n ? round(checkout.outstandingBalance, 2).toFixed(2)\n : '';\n\n const {\n initializationData: {\n gatewayMerchantId,\n googleMerchantName: merchantName,\n googleMerchantId: merchantId,\n platformToken: authJwt,\n },\n supportedCards,\n } = paymentMethod;\n\n return {\n apiVersion: 2,\n apiVersionMinor: 0,\n merchantInfo: {\n authJwt,\n merchantId,\n merchantName,\n },\n allowedPaymentMethods: [\n {\n type: 'CARD',\n parameters: {\n allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n allowedCardNetworks: supportedCards.map((card) =>\n card === 'MC' ? 'MASTERCARD' : card,\n ),\n billingAddressRequired: true,\n billingAddressParameters: {\n format: BillingAddressFormat.Full,\n phoneNumberRequired: true,\n },\n },\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY',\n parameters: {\n gateway: 'chase',\n gatewayMerchantId,\n },\n },\n },\n ],\n transactionInfo: {\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n emailRequired: true,\n shippingAddressRequired: !hasShippingAddress,\n shippingAddressParameters: {\n phoneNumberRequired: true,\n },\n };\n }\n}\n","import { round } from 'lodash';\n\nimport { Checkout } from '../../../checkout';\nimport { InvalidArgumentError } from '../../../common/error/errors';\nimport PaymentMethod from '../../payment-method';\n\nimport {\n BillingAddressFormat,\n GooglePayInitializer,\n GooglePaymentData,\n GooglePayPaymentDataRequestV2,\n TokenizePayload,\n TotalPriceStatusType,\n} from './googlepay';\n\nexport default class GooglePayStripeInitializer implements GooglePayInitializer {\n initialize(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): Promise {\n return Promise.resolve(\n this._getGooglePayPaymentDataRequest(checkout, paymentMethod, hasShippingAddress),\n );\n }\n\n teardown(): Promise {\n return Promise.resolve();\n }\n\n parseResponse(paymentData: GooglePaymentData): Promise {\n try {\n const payload = JSON.parse(paymentData.paymentMethodData.tokenizationData.token);\n\n return Promise.resolve({\n nonce: payload.id,\n type: payload.type,\n details: {\n cardType: payload.card.brand,\n lastFour: payload.card.last4,\n },\n });\n } catch (err) {\n throw new InvalidArgumentError('Unable to parse response from Google Pay.');\n }\n }\n\n private _getGooglePayPaymentDataRequest(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): GooglePayPaymentDataRequestV2 {\n const currencyCode = checkout?.cart.currency.code || '';\n const totalPrice = checkout?.outstandingBalance\n ? round(checkout.outstandingBalance, 2).toFixed(2)\n : '';\n const consignments = checkout?.consignments || [];\n\n const {\n initializationData: {\n googleMerchantName: merchantName,\n googleMerchantId: merchantId,\n platformToken: authJwt,\n stripeVersion,\n stripePublishableKey,\n stripeConnectedAccount,\n bopis,\n },\n supportedCards,\n } = paymentMethod;\n\n const isPickup = consignments.every((consignment) => consignment.selectedPickupOption);\n\n return {\n apiVersion: 2,\n apiVersionMinor: 0,\n merchantInfo: {\n authJwt,\n merchantId,\n merchantName,\n },\n allowedPaymentMethods: [\n {\n type: 'CARD',\n parameters: {\n allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n allowedCardNetworks: supportedCards.map((card) =>\n card === 'MC' ? 'MASTERCARD' : card,\n ),\n billingAddressRequired: true,\n billingAddressParameters: {\n format: BillingAddressFormat.Full,\n phoneNumberRequired: true,\n },\n },\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY',\n parameters: {\n gateway: 'stripe',\n 'stripe:version': stripeVersion,\n 'stripe:publishableKey': `${stripePublishableKey}/${stripeConnectedAccount}`,\n },\n },\n },\n ],\n transactionInfo: {\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n emailRequired: true,\n shippingAddressRequired:\n bopis?.enabled && isPickup && bopis?.requiredAddress === 'none'\n ? false\n : !hasShippingAddress,\n shippingAddressParameters: {\n phoneNumberRequired: true,\n },\n };\n }\n}\n","import { round } from 'lodash';\n\nimport { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Checkout } from '../../../checkout';\nimport { InvalidArgumentError } from '../../../common/error/errors';\nimport PaymentMethod from '../../payment-method';\n\nimport {\n BillingAddressFormat,\n GooglePayInitializer,\n GooglePaymentData,\n GooglePayPaymentDataRequestV2,\n TokenizePayload,\n TotalPriceStatusType,\n} from './googlepay';\n\nexport default class GooglePayStripeUPEInitializer implements GooglePayInitializer {\n initialize(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): Promise {\n return Promise.resolve(\n this._getGooglePayPaymentDataRequest(checkout, paymentMethod, hasShippingAddress),\n );\n }\n\n teardown(): Promise {\n return Promise.resolve();\n }\n\n parseResponse(paymentData: GooglePaymentData): Promise {\n let payload;\n\n try {\n payload = JSON.parse(paymentData.paymentMethodData.tokenizationData.token);\n } catch (err) {\n throw new InvalidArgumentError('Unable to parse response from Google Pay.');\n }\n\n if (\n !payload.id ||\n !payload.type ||\n !payload.card ||\n !payload.card.brand ||\n !payload.card.last4\n ) {\n throw new PaymentMethodFailedError('Unable to parse response from Google Pay.');\n }\n\n return Promise.resolve({\n nonce: payload.id,\n type: payload.type,\n details: {\n cardType: payload.card.brand,\n lastFour: payload.card.last4,\n },\n });\n }\n\n private _getGooglePayPaymentDataRequest(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): GooglePayPaymentDataRequestV2 {\n const currencyCode = checkout?.cart.currency.code || '';\n const decimalPlaces = checkout?.cart.currency.decimalPlaces || 2;\n const totalPrice = checkout?.outstandingBalance\n ? round(checkout.outstandingBalance, decimalPlaces).toFixed(decimalPlaces)\n : '';\n\n const {\n initializationData: {\n googleMerchantName: merchantName,\n googleMerchantId: merchantId,\n platformToken: authJwt,\n stripeVersion,\n stripePublishableKey,\n stripeConnectedAccount,\n },\n supportedCards,\n } = paymentMethod;\n\n return {\n apiVersion: 2,\n apiVersionMinor: 0,\n merchantInfo: {\n authJwt,\n merchantId,\n merchantName,\n },\n allowedPaymentMethods: [\n {\n type: 'CARD',\n parameters: {\n allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n allowedCardNetworks: supportedCards.map((card) =>\n card === 'MC' ? 'MASTERCARD' : card,\n ),\n billingAddressRequired: true,\n billingAddressParameters: {\n format: BillingAddressFormat.Full,\n phoneNumberRequired: true,\n },\n },\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY',\n parameters: {\n gateway: 'stripe',\n 'stripe:version': stripeVersion,\n 'stripe:publishableKey': `${stripePublishableKey}/${stripeConnectedAccount}`,\n },\n },\n },\n ],\n transactionInfo: {\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n emailRequired: true,\n shippingAddressRequired: !hasShippingAddress,\n shippingAddressParameters: {\n phoneNumberRequired: true,\n },\n };\n }\n}\n","import { round } from 'lodash';\n\nimport { Checkout } from '../../../checkout';\nimport PaymentMethod from '../../payment-method';\n\nimport {\n BillingAddressFormat,\n GooglePayInitializer,\n GooglePaymentData,\n GooglePayPaymentDataRequestV2,\n TokenizePayload,\n TotalPriceStatusType,\n} from './googlepay';\n\nexport default class GooglePayWorldpayAccessInitializer implements GooglePayInitializer {\n initialize(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): Promise {\n return Promise.resolve(\n this._getGooglePayPaymentDataRequest(checkout, paymentMethod, hasShippingAddress),\n );\n }\n\n teardown(): Promise {\n return Promise.resolve();\n }\n\n parseResponse(paymentData: GooglePaymentData): Promise {\n const {\n paymentMethodData: {\n type,\n tokenizationData: { token },\n info: { cardNetwork: cardType, cardDetails: lastFour },\n },\n } = paymentData;\n\n return Promise.resolve({\n nonce: btoa(token),\n type,\n details: {\n cardType,\n lastFour,\n },\n });\n }\n\n private _getGooglePayPaymentDataRequest(\n checkout: Checkout | undefined,\n paymentMethod: PaymentMethod,\n hasShippingAddress: boolean,\n ): GooglePayPaymentDataRequestV2 {\n const currencyCode = checkout?.cart.currency.code || '';\n const totalPrice = checkout?.outstandingBalance\n ? round(checkout.outstandingBalance, 2).toFixed(2)\n : '';\n\n const {\n initializationData: {\n gatewayMerchantId,\n storeCountry: countryCode,\n googleMerchantName: merchantName,\n googleMerchantId: merchantId,\n platformToken: authJwt,\n },\n supportedCards,\n } = paymentMethod;\n\n return {\n apiVersion: 2,\n apiVersionMinor: 0,\n merchantInfo: {\n authJwt,\n merchantId,\n merchantName,\n },\n allowedPaymentMethods: [\n {\n type: 'CARD',\n parameters: {\n allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],\n allowedCardNetworks: supportedCards.map((card) =>\n card === 'MC' ? 'MASTERCARD' : card,\n ),\n billingAddressRequired: true,\n billingAddressParameters: {\n format: BillingAddressFormat.Full,\n phoneNumberRequired: true,\n },\n },\n tokenizationSpecification: {\n type: 'PAYMENT_GATEWAY',\n parameters: {\n gateway: 'worldpay',\n gatewayMerchantId,\n },\n },\n },\n ],\n transactionInfo: {\n countryCode,\n currencyCode,\n totalPriceStatus: TotalPriceStatusType.FINAL,\n totalPrice,\n },\n emailRequired: true,\n shippingAddressRequired: !hasShippingAddress,\n shippingAddressParameters: {\n phoneNumberRequired: true,\n },\n };\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { Masterpass, MasterpassHostWindow } from './masterpass';\n\ninterface MasterpassScriptLoaderParams {\n useMasterpassSrc: boolean;\n language: string;\n testMode?: boolean;\n checkoutId?: string;\n}\n\nexport default class MasterpassScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n public _window: MasterpassHostWindow = window,\n ) {}\n\n async load({\n useMasterpassSrc,\n language,\n testMode,\n checkoutId,\n }: MasterpassScriptLoaderParams): Promise {\n if (useMasterpassSrc) {\n const subdomain = testMode ? 'sandbox.' : '';\n const params = [`locale=${language}`, `checkoutid=${checkoutId}`];\n\n const sourceUrl = [\n `https://${subdomain}src.mastercard.com/srci/integration/merchant.js`,\n params.join('&'),\n ].join('?');\n\n await this._scriptLoader.loadScript(sourceUrl);\n\n if (!this._window.masterpass) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.masterpass;\n }\n\n await this._scriptLoader.loadScript(\n `//${testMode ? 'sandbox.' : ''}masterpass.com/integration/merchant.js`,\n );\n\n if (!this._window.masterpass) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.masterpass;\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport {\n StripeElements,\n StripeElementsOptions,\n StripeHostWindow,\n StripeUPEClient,\n} from './stripe-upe';\n\nexport default class StripeUPEScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, private _window: StripeHostWindow = window) {}\n\n async getStripeClient(\n stripePublishableKey: string,\n stripeAccount: string,\n locale?: string,\n ): Promise {\n let stripeClient = this._window.bcStripeClient;\n\n if (!stripeClient) {\n const stripe = await this.load();\n\n stripeClient = stripe(stripePublishableKey, {\n stripeAccount,\n locale,\n betas: [\n 'payment_element_beta_2',\n 'alipay_pm_beta_1',\n 'link_default_integration_beta_1',\n 'shipping_address_element_beta_1',\n 'address_element_beta_1',\n ],\n apiVersion: '2020-03-02;alipay_beta=v1;link_beta=v1',\n });\n\n Object.assign(this._window, { bcStripeClient: stripeClient });\n }\n\n return stripeClient;\n }\n\n getElements(stripeClient: StripeUPEClient, options: StripeElementsOptions): StripeElements {\n let stripeElements = this._window.bcStripeElements;\n\n if (!stripeElements) {\n stripeElements = stripeClient.elements(options);\n\n Object.assign(this._window, { bcStripeElements: stripeElements });\n } else {\n stripeElements.fetchUpdates();\n stripeElements.update(options);\n }\n\n return stripeElements;\n }\n\n private async load() {\n await this._scriptLoader.loadScript('https://js.stripe.com/v3/');\n\n if (!this._window.Stripe) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.Stripe;\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\n/**\n * @todo Convert this file into TypeScript properly\n */\nexport default class RemoteCheckoutRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n initializeBilling(\n methodName: string,\n params?: { referenceId: string },\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/remote-checkout/${methodName}/billing`;\n\n return this._requestSender.get(url, { params, timeout, headers: SDK_VERSION_HEADERS });\n }\n\n initializeShipping(\n methodName: string,\n params?: { referenceId: string },\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/remote-checkout/${methodName}/shipping`;\n\n return this._requestSender.get(url, { params, timeout, headers: SDK_VERSION_HEADERS });\n }\n\n initializePayment(\n methodName: string,\n params?: InitializePaymentOptions,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = `/remote-checkout/${methodName}/payment`;\n\n return this._requestSender.get(url, { params, timeout, headers: SDK_VERSION_HEADERS });\n }\n\n loadSettings(methodName: string, { timeout }: RequestOptions = {}): Promise> {\n const url = `/remote-checkout/${methodName}/settings`;\n\n return this._requestSender.get(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n\n signOut(methodName: string, { timeout }: RequestOptions = {}): Promise> {\n const url = `/remote-checkout/${methodName}/signout`;\n\n return this._requestSender.get(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n\n generateToken({ timeout }: RequestOptions = {}): Promise> {\n const url = '/remote-checkout-token';\n\n return this._requestSender.get(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n\n trackAuthorizationEvent({ timeout }: RequestOptions = {}): Promise> {\n const url =\n '/remote-checkout/events/shopper-checkout-service-provider-authorization-requested';\n\n return this._requestSender.post(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n\n forgetCheckout({ timeout }: RequestOptions = {}): Promise> {\n const url = `/remote-checkout/forget-checkout`;\n\n return this._requestSender.post(url, { timeout, headers: SDK_VERSION_HEADERS });\n }\n}\n\nexport interface InitializePaymentOptions {\n authorizationToken?: string;\n customerMessage?: string;\n referenceId?: string;\n useStoreCredit?: boolean;\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { AmazonPayRemoteCheckout } from './methods';\n\nexport enum RemoteCheckoutActionType {\n ForgetCheckoutRemoteCustomerRequested = 'FORGET_CHECKOUT_REMOTE_CUSTOMER_REQUESTED',\n ForgetCheckoutRemoteCustomerSucceeded = 'FORGET_CHECKOUT_REMOTE_CUSTOMER_SUCCEEDED',\n ForgetCheckoutRemoteCustomerFailed = 'FORGET_CHECKOUT_REMOTE_CUSTOMER_FAILED',\n\n InitializeRemoteBillingRequested = 'INITIALIZE_REMOTE_BILLING_REQUESTED',\n InitializeRemoteBillingSucceeded = 'INITIALIZE_REMOTE_BILLING_SUCCEEDED',\n InitializeRemoteBillingFailed = 'INITIALIZE_REMOTE_BILLING_FAILED',\n\n InitializeRemoteShippingRequested = 'INITIALIZE_REMOTE_SHIPPING_REQUESTED',\n InitializeRemoteShippingSucceeded = 'INITIALIZE_REMOTE_SHIPPING_SUCCEEDED',\n InitializeRemoteShippingFailed = 'INITIALIZE_REMOTE_SHIPPING_FAILED',\n\n InitializeRemotePaymentRequested = 'INITIALIZE_REMOTE_PAYMENT_REQUESTED',\n InitializeRemotePaymentSucceeded = 'INITIALIZE_REMOTE_PAYMENT_SUCCEEDED',\n InitializeRemotePaymentFailed = 'INITIALIZE_REMOTE_PAYMENT_FAILED',\n\n LoadRemoteSettingsRequested = 'LOAD_REMOTE_SETTINGS_REQUESTED',\n LoadRemoteSettingsSucceeded = 'LOAD_REMOTE_SETTINGS_SUCCEEDED',\n LoadRemoteSettingsFailed = 'LOAD_REMOTE_SETTINGS_FAILED',\n\n SignOutRemoteCustomerRequested = 'SIGN_OUT_REMOTE_CUSTOMER_REQUESTED',\n SignOutRemoteCustomerSucceeded = 'SIGN_OUT_REMOTE_CUSTOMER_SUCCEEDED',\n SignOutRemoteCustomerFailed = 'SIGN_OUT_REMOTE_CUSTOMER_FAILED',\n\n UpdateRemoteCheckout = 'UPDATE_REMOTE_CHECKOUT',\n}\n\nexport type RemoteCheckoutAction =\n | ForgetCheckoutRemoteCustomerAction\n | InitializeRemoteBillingAction\n | InitializeRemoteShippingAction\n | InitializeRemotePaymentAction\n | SignOutRemoteCustomerAction\n | LoadRemoteSettingsAction\n | UpdateRemoteCheckoutAction;\n\nexport type ForgetCheckoutRemoteCustomerAction =\n | ForgetCheckoutRemoteCustomerRequestedAction\n | ForgetCheckoutRemoteCustomerSucceededAction\n | ForgetCheckoutRemoteCustomerFailedAction;\n\nexport interface ForgetCheckoutRemoteCustomerRequestedAction extends Action {\n type: RemoteCheckoutActionType.ForgetCheckoutRemoteCustomerRequested;\n}\n\nexport interface ForgetCheckoutRemoteCustomerSucceededAction extends Action {\n type: RemoteCheckoutActionType.ForgetCheckoutRemoteCustomerSucceeded;\n}\n\nexport interface ForgetCheckoutRemoteCustomerFailedAction extends Action {\n type: RemoteCheckoutActionType.ForgetCheckoutRemoteCustomerFailed;\n}\n\nexport type InitializeRemoteBillingAction =\n | InitializeRemoteBillingSucceededAction\n | InitializeRemoteBillingFailedAction\n | InitializeRemoteBillingRequestedAction;\n\nexport interface InitializeRemoteBillingSucceededAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemoteBillingSucceeded;\n}\n\nexport interface InitializeRemoteBillingFailedAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemoteBillingFailed;\n}\n\nexport interface InitializeRemoteBillingRequestedAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemoteBillingRequested;\n}\n\nexport type InitializeRemoteShippingAction =\n | InitializeRemoteShippingSucceededAction\n | InitializeRemoteShippingFailedAction\n | InitializeRemoteShippingRequestedAction;\n\nexport interface InitializeRemoteShippingSucceededAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemoteShippingSucceeded;\n}\n\nexport interface InitializeRemoteShippingFailedAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemoteShippingFailed;\n}\n\nexport interface InitializeRemoteShippingRequestedAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemoteShippingRequested;\n}\n\nexport type InitializeRemotePaymentAction =\n | InitializeRemotePaymentSucceededAction\n | InitializeRemotePaymentFailedAction\n | InitializeRemotePaymentRequestedAction;\n\nexport interface InitializeRemotePaymentSucceededAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemotePaymentSucceeded;\n}\n\nexport interface InitializeRemotePaymentFailedAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemotePaymentFailed;\n}\n\nexport interface InitializeRemotePaymentRequestedAction extends Action {\n type: RemoteCheckoutActionType.InitializeRemotePaymentRequested;\n}\n\nexport type SignOutRemoteCustomerAction =\n | SignOutRemoteCustomerSucceededAction\n | SignOutRemoteCustomerFailedAction\n | SignOutRemoteCustomerRequestedAction;\n\nexport interface SignOutRemoteCustomerSucceededAction extends Action {\n type: RemoteCheckoutActionType.SignOutRemoteCustomerSucceeded;\n}\n\nexport interface SignOutRemoteCustomerFailedAction extends Action {\n type: RemoteCheckoutActionType.SignOutRemoteCustomerFailed;\n}\n\nexport interface SignOutRemoteCustomerRequestedAction extends Action {\n type: RemoteCheckoutActionType.SignOutRemoteCustomerRequested;\n}\n\nexport type LoadRemoteSettingsAction =\n | LoadRemoteSettingsSucceededAction\n | LoadRemoteSettingsRequestedAction\n | LoadRemoteSettingsFailedAction;\n\nexport interface LoadRemoteSettingsSucceededAction extends Action {\n type: RemoteCheckoutActionType.LoadRemoteSettingsSucceeded;\n}\n\nexport interface LoadRemoteSettingsRequestedAction extends Action {\n type: RemoteCheckoutActionType.LoadRemoteSettingsRequested;\n}\n\nexport interface LoadRemoteSettingsFailedAction extends Action {\n type: RemoteCheckoutActionType.LoadRemoteSettingsFailed;\n}\n\nexport interface UpdateRemoteCheckoutAction extends Action {\n type: RemoteCheckoutActionType.UpdateRemoteCheckout;\n}\n","import { Action, createAction, createErrorAction } from '@bigcommerce/data-store';\nimport { concat, defer, Observable, Observer, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { CheckoutActionCreator } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\n\nimport { RemoteCheckoutActionType } from './remote-checkout-actions';\nimport RemoteCheckoutRequestSender, {\n InitializePaymentOptions,\n} from './remote-checkout-request-sender';\nimport { RemoteCheckoutStateData } from './remote-checkout-state';\n\n/**\n * @todo Convert this file into TypeScript properly\n * i.e.: Action\n */\nexport default class RemoteCheckoutActionCreator {\n constructor(\n private _remoteCheckoutRequestSender: RemoteCheckoutRequestSender,\n private _checkoutActionCreator: CheckoutActionCreator,\n ) {}\n\n initializeBilling(\n methodId: string,\n params?: { referenceId: string },\n options?: RequestOptions,\n ): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(\n createAction(RemoteCheckoutActionType.InitializeRemoteBillingRequested, undefined, {\n methodId,\n }),\n );\n\n this._remoteCheckoutRequestSender\n .initializeBilling(methodId, params, options)\n .then(({ body = {} }) => {\n observer.next(\n createAction(\n RemoteCheckoutActionType.InitializeRemoteBillingSucceeded,\n body,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n RemoteCheckoutActionType.InitializeRemoteBillingFailed,\n response,\n { methodId },\n ),\n );\n });\n });\n }\n\n initializeShipping(\n methodId: string,\n params?: { referenceId: string },\n options?: RequestOptions,\n ): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(\n createAction(\n RemoteCheckoutActionType.InitializeRemoteShippingRequested,\n undefined,\n { methodId },\n ),\n );\n\n this._remoteCheckoutRequestSender\n .initializeShipping(methodId, params, options)\n .then(({ body = {} }) => {\n observer.next(\n createAction(\n RemoteCheckoutActionType.InitializeRemoteShippingSucceeded,\n body,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n RemoteCheckoutActionType.InitializeRemoteShippingFailed,\n response,\n { methodId },\n ),\n );\n });\n });\n }\n\n initializePayment(\n methodId: string,\n params?: InitializePaymentOptions,\n options?: RequestOptions,\n ): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(\n createAction(RemoteCheckoutActionType.InitializeRemotePaymentRequested, undefined, {\n methodId,\n }),\n );\n\n this._remoteCheckoutRequestSender\n .initializePayment(methodId, params, options)\n .then(({ body = {} }) => {\n observer.next(\n createAction(\n RemoteCheckoutActionType.InitializeRemotePaymentSucceeded,\n body,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n RemoteCheckoutActionType.InitializeRemotePaymentFailed,\n response,\n { methodId },\n ),\n );\n });\n });\n }\n\n loadSettings(methodId: string, options?: RequestOptions): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(\n createAction(RemoteCheckoutActionType.LoadRemoteSettingsRequested, undefined, {\n methodId,\n }),\n );\n\n this._remoteCheckoutRequestSender\n .loadSettings(methodId, options)\n .then(({ body }) => {\n observer.next(\n createAction(RemoteCheckoutActionType.LoadRemoteSettingsSucceeded, body, {\n methodId,\n }),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n RemoteCheckoutActionType.LoadRemoteSettingsFailed,\n response,\n { methodId },\n ),\n );\n });\n });\n }\n\n signOut(methodId: string, options?: RequestOptions): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(\n createAction(RemoteCheckoutActionType.SignOutRemoteCustomerRequested, undefined, {\n methodId,\n }),\n );\n\n this._remoteCheckoutRequestSender\n .signOut(methodId, options)\n .then(() => {\n observer.next(\n createAction(\n RemoteCheckoutActionType.SignOutRemoteCustomerSucceeded,\n undefined,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n RemoteCheckoutActionType.SignOutRemoteCustomerFailed,\n response,\n { methodId },\n ),\n );\n });\n });\n }\n\n forgetCheckout(methodId: string, options?: RequestOptions): Observable {\n return concat(\n of(\n createAction(\n RemoteCheckoutActionType.ForgetCheckoutRemoteCustomerRequested,\n undefined,\n { methodId },\n ),\n ),\n defer(async () => {\n await this._remoteCheckoutRequestSender.forgetCheckout(options);\n await this._checkoutActionCreator.loadCurrentCheckout();\n\n return createAction(\n RemoteCheckoutActionType.ForgetCheckoutRemoteCustomerSucceeded,\n undefined,\n { methodId },\n );\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(\n RemoteCheckoutActionType.ForgetCheckoutRemoteCustomerFailed,\n error,\n { methodId },\n ),\n ),\n );\n }\n\n updateCheckout(\n methodId: K,\n data: Partial,\n ): Action {\n return createAction(RemoteCheckoutActionType.UpdateRemoteCheckout, data, { methodId });\n }\n}\n","import StandardError from './standard-error';\n\n/**\n * Throw this error if we try to call a method that is only a stub and has not\n * been fully implemented.\n */\nexport default class NotImplementedError extends StandardError {\n constructor(message?: string) {\n super(message || 'Not implemented.');\n\n this.name = 'NotImplementedError';\n this.type = 'not_implemented';\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { InvalidArgumentError, NotImplementedError } from '../../../common/error/errors';\nimport { PaymentMethodActionCreator } from '../../../payment';\nimport {\n AmazonPayV2PaymentProcessor,\n AmazonPayV2Placement,\n} from '../../../payment/strategies/amazon-pay-v2';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport {\n CustomerInitializeOptions,\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class AmazonPayV2CustomerStrategy implements CustomerStrategy {\n constructor(\n private _store: CheckoutStore,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n private _amazonPayV2PaymentProcessor: AmazonPayV2PaymentProcessor,\n ) {}\n\n async initialize(options: CustomerInitializeOptions): Promise {\n const { methodId, amazonpay } = options;\n\n if (!methodId || !amazonpay?.container) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" or \"containerId\" argument is not provided.',\n );\n }\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n\n await this._amazonPayV2PaymentProcessor.initialize(getPaymentMethodOrThrow(methodId));\n\n this._amazonPayV2PaymentProcessor.renderAmazonPayButton({\n checkoutState: this._store.getState(),\n containerId: amazonpay.container,\n methodId,\n placement: AmazonPayV2Placement.Checkout,\n });\n\n return this._store.getState();\n }\n\n async deinitialize(): Promise {\n await this._amazonPayV2PaymentProcessor.deinitialize();\n\n return this._store.getState();\n }\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via Amazon, the shopper must click on \"Amazon Pay\" button.',\n );\n }\n\n async signOut(options?: CustomerRequestOptions): Promise {\n const state = this._store.getState();\n const payment = state.payment.getPaymentId();\n\n if (!payment) {\n return Promise.resolve(this._store.getState());\n }\n\n await this._amazonPayV2PaymentProcessor.signout();\n\n return this._store.dispatch(\n this._remoteCheckoutActionCreator.signOut(payment.providerId, options),\n );\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotImplementedError,\n} from '../../../common/error/errors';\nimport { PaymentMethod, PaymentMethodActionCreator } from '../../../payment';\nimport {\n BraintreeVisaCheckoutPaymentProcessor,\n VisaCheckoutPaymentSuccessPayload,\n VisaCheckoutScriptLoader,\n} from '../../../payment/strategies/braintree';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport {\n CustomerInitializeOptions,\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategyActionCreator from '../../customer-strategy-action-creator';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class BraintreeVisaCheckoutCustomerStrategy implements CustomerStrategy {\n private _paymentMethod?: PaymentMethod;\n private _buttonClassName = 'visa-checkout-wrapper';\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _customerStrategyActionCreator: CustomerStrategyActionCreator,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n private _braintreeVisaCheckoutPaymentProcessor: BraintreeVisaCheckoutPaymentProcessor,\n private _visaCheckoutScriptLoader: VisaCheckoutScriptLoader,\n private _formPoster: FormPoster,\n ) {}\n\n initialize(options: CustomerInitializeOptions): Promise {\n const { braintreevisacheckout: visaCheckoutOptions, methodId } = options;\n\n if (!visaCheckoutOptions || !methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"options.braintreevisacheckout\" argument is not provided.',\n );\n }\n\n return this._store\n .dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId))\n .then((state) => {\n this._paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n const checkout = state.checkout.getCheckout();\n const storeConfig = state.config.getStoreConfig();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n if (!this._paymentMethod || !this._paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { container, onError = () => {} } = visaCheckoutOptions;\n\n const initOptions = {\n locale: storeConfig.storeProfile.storeLanguage,\n collectShipping: true,\n subtotal: checkout.subtotal,\n currencyCode: storeConfig.currency.code,\n };\n\n return Promise.all([\n this._visaCheckoutScriptLoader.load(this._paymentMethod.config.testMode),\n this._braintreeVisaCheckoutPaymentProcessor.initialize(\n this._paymentMethod.clientToken,\n initOptions,\n ),\n ])\n .then(([visaCheckout, initOptions]) => {\n const signInButton = this._createSignInButton(\n container,\n this._buttonClassName,\n );\n\n visaCheckout.init(initOptions);\n visaCheckout.on(\n 'payment.success',\n (paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) =>\n this._paymentInstrumentSelected(paymentSuccessPayload).catch(\n (error) => onError(error),\n ),\n );\n visaCheckout.on('payment.error', (_, error) => onError(error));\n\n return signInButton;\n })\n .then((signInButton) => {\n signInButton.style.visibility = 'visible';\n });\n })\n .then(() => this._store.getState());\n }\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via VisaCheckout, the shopper must click on \"Visa Checkout\" button.',\n );\n }\n\n signOut(options?: CustomerRequestOptions): Promise {\n return this._store.dispatch(\n this._remoteCheckoutActionCreator.signOut('braintreevisacheckout', options),\n );\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n this._paymentMethod = undefined;\n\n return this._braintreeVisaCheckoutPaymentProcessor\n .deinitialize()\n .then(() => this._store.getState());\n }\n\n private _paymentInstrumentSelected(paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) {\n const state = this._store.getState();\n\n if (!this._paymentMethod) {\n throw new Error('Payment method not initialized');\n }\n\n const { id: methodId } = this._paymentMethod;\n\n return this._store.dispatch(\n this._customerStrategyActionCreator.widgetInteraction(\n () => {\n return this._braintreeVisaCheckoutPaymentProcessor\n .handleSuccess(\n paymentSuccessPayload,\n state.shippingAddress.getShippingAddress(),\n state.billingAddress.getBillingAddress(),\n )\n .then(async () => {\n await this._store.dispatch(\n this._checkoutActionCreator.loadCurrentCheckout(),\n );\n this._onPaymentSelectComplete();\n });\n },\n { methodId },\n ),\n { queueId: 'widgetInteraction' },\n );\n }\n\n private _onPaymentSelectComplete(): void {\n this._formPoster.postForm('/checkout.php', {\n headers: {\n Accept: 'text/html',\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n });\n }\n\n private _createSignInButton(containerId: string, buttonClass: string): HTMLElement {\n const container = document.querySelector(`#${containerId}`);\n\n if (!container) {\n throw new Error('Need a container to place the button');\n }\n\n return (\n (container.querySelector(`.${buttonClass}`) as HTMLElement) ||\n this._insertVisaCheckoutButton(container, buttonClass)\n );\n }\n\n private _insertVisaCheckoutButton(container: Element, buttonClass: string): HTMLElement {\n const buttonSource =\n 'https://secure.checkout.visa.com/wallet-services-web/xo/button.png?acceptCanadianVisaDebit=false&cobrand=true&height=34&width=178';\n const buttonTemplate = `\n \n Tell Me More`;\n\n const visaCheckoutButton = document.createElement('div');\n\n visaCheckoutButton.style.display = 'flex';\n visaCheckoutButton.style.flexDirection = 'column';\n visaCheckoutButton.style.visibility = 'hidden';\n visaCheckoutButton.className = buttonClass;\n visaCheckoutButton.innerHTML = buttonTemplate;\n\n container.appendChild(visaCheckoutButton);\n\n return visaCheckoutButton;\n }\n}\n","import { LegacyAddress } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BraintreeDetails } from '../../../payment/strategies/braintree';\n\nexport default function mapToLegacyBillingAddress(\n details: BraintreeDetails,\n): Partial {\n const { billingAddress, email, firstName, lastName, phone, shippingAddress } = details;\n\n const address = billingAddress || shippingAddress;\n\n return {\n email,\n first_name: firstName,\n last_name: lastName,\n phone_number: phone,\n address_line_1: address?.line1,\n address_line_2: address?.line2,\n city: address?.city,\n state: address?.state,\n country_code: address?.countryCode,\n postal_code: address?.postalCode,\n };\n}\n","import { LegacyAddress } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BraintreeDetails } from '../../../payment/strategies/braintree';\n\nexport default function mapToLegacyShippingAddress(\n details: BraintreeDetails,\n): Partial {\n const { email, phone, shippingAddress } = details;\n\n const recipientName = shippingAddress?.recipientName || '';\n const [firstName, lastName] = recipientName.split(' ');\n\n return {\n email,\n first_name: firstName || '',\n last_name: lastName || '',\n phone_number: phone,\n address_line_1: shippingAddress?.line1,\n address_line_2: shippingAddress?.line2,\n city: shippingAddress?.city,\n state: shippingAddress?.state,\n country_code: shippingAddress?.countryCode,\n postal_code: shippingAddress?.postalCode,\n };\n}\n","import { Address } from '../../../address';\n\nimport { BraintreeShippingAddressOverride } from './braintree';\n\nexport default function mapToBraintreeShippingAddressOverride(\n address: Address,\n): BraintreeShippingAddressOverride {\n return {\n recipientName: `${address.firstName} ${address.lastName}`,\n line1: address.address1,\n line2: address.address2,\n city: address.city,\n state: address.stateOrProvinceCode,\n postalCode: address.postalCode,\n countryCode: address.countryCode,\n phone: address.phone,\n };\n}\n","export interface PaypalSDK {\n Button: PaypalButton;\n checkout: PaypalExpressCheckout;\n FUNDING: PaypalFundingTypeList;\n Messages(options: MessagingOptions): MessagingRender;\n Buttons(options: PaypalButtonOptions): PaypalButtonRender;\n}\n\nexport interface PaypalFundingTypeList {\n CARD?: string;\n CREDIT?: string;\n PAYPAL?: string;\n PAYLATER?: string;\n}\n\nexport interface PaypalButton {\n render(options: PaypalButtonOptions, container: string): void;\n}\n\nexport interface PaypalButtonRender {\n render(container: string): void;\n isEligible(): boolean;\n}\n\nexport interface MessagingRender {\n render(container: string): void;\n}\n\nexport interface MessagingOptions {\n amount: number;\n placement: string;\n}\n\nexport interface PaypalButtonOptions {\n env?: string;\n commit?: boolean;\n style?: PaypalStyleOptions;\n funding?: PaypalFundingType;\n fundingSource?: string;\n client?: PaypalClientToken;\n payment?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onAuthorize?(data: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n createOrder?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onApprove?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n}\n\nexport interface PaypalClientToken {\n production?: string;\n sandbox?: string;\n}\n\nexport interface PaypalFundingType {\n allowed?: string[];\n disallowed?: string[];\n}\n\nexport enum PaypalButtonStyleLayoutOption {\n HORIZONTAL = 'horizontal',\n VERTICAL = 'vertical',\n}\n\nexport enum PaypalButtonStyleSizeOption {\n SMALL = 'small',\n MEDIUM = 'medium',\n LARGE = 'large',\n RESPONSIVE = 'responsive',\n}\n\nexport enum PaypalButtonStyleColorOption {\n GOLD = 'gold',\n BLUE = 'blue',\n SIlVER = 'silver',\n BLACK = 'black',\n}\n\nexport enum PaypalButtonStyleLabelOption {\n CHECKOUT = 'checkout',\n PAY = 'pay',\n BUYNOW = 'buynow',\n PAYPAL = 'paypal',\n CREDIT = 'credit',\n}\n\nexport enum PaypalButtonStyleShapeOption {\n PILL = 'pill',\n RECT = 'rect',\n}\n\nexport interface PaypalStyleOptions {\n layout?: PaypalButtonStyleLayoutOption;\n size?: PaypalButtonStyleSizeOption;\n color?: PaypalButtonStyleColorOption;\n label?: PaypalButtonStyleLabelOption;\n shape?: PaypalButtonStyleShapeOption;\n tagline?: boolean;\n fundingicons?: boolean;\n height?: number;\n}\n\nexport interface PaypalActions {\n payment: PaypalPaymentActions;\n request: PaypalRequestActions;\n}\n\nexport interface PaypalPaymentActions {\n get(id: string): Promise;\n}\n\nexport interface PaypalRequestActions {\n post(url: string, payload?: object, options?: object): Promise<{ id: string }>;\n}\n\nexport interface PaypalTransaction {\n amount?: PaypalAmount;\n payee?: PaypalPayee;\n description?: string;\n note_to_payee?: string;\n item_list?: PaypalItemList;\n}\n\nexport interface PaypalItemList {\n items?: PaypalItem[];\n shipping_address?: PaypalAddress;\n}\n\nexport interface PaypalItem {\n sku?: string;\n name?: string;\n description?: string;\n quantity: string;\n price: string;\n currency: string;\n tax?: string;\n}\n\nexport interface PaypalAmount {\n currency: string;\n total: string;\n}\n\nexport interface PaypalPayer {\n payer_info: object;\n}\n\nexport interface PaypalPayee {\n email?: string;\n merchant_id?: string;\n}\n\nexport interface PaypalAddress {\n line1: string;\n line2?: string;\n city?: string;\n country_code: string;\n postal_code?: string;\n state?: string;\n phone?: string;\n type?: string;\n}\n\nexport interface PaypalPaymentPayload {\n payment: PaypalPaymentPayload;\n payer: PaypalPayer;\n transactions?: PaypalTransaction[];\n}\n\nexport interface PaypalAuthorizeData {\n payerId: string;\n paymentId?: string;\n billingToken?: string;\n // the PayPal side of things uses uppercase ID instead of camel case Id\n payerID?: string;\n paymentID?: string;\n}\n\nexport interface PaypalExpressCheckout {\n initXO(): void;\n startFlow(url: string): void;\n closeFlow(): void;\n setup(merchantId: string, options: PaypalExpressCheckoutOptions): void;\n}\n\nexport interface PaypalExpressCheckoutOptions {\n button: string;\n environment: string;\n}\n\nexport interface PaypalHostWindow extends Window {\n paypal?: PaypalSDK;\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport mapToLegacyBillingAddress from '../../../checkout-buttons/strategies/braintree/map-to-legacy-billing-address';\nimport mapToLegacyShippingAddress from '../../../checkout-buttons/strategies/braintree/map-to-legacy-shipping-address';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../../../common/error/errors';\nimport { PaymentMethodActionCreator } from '../../../payment';\nimport {\n BraintreeError,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeSDKCreator,\n BraintreeTokenizePayload,\n mapToBraintreeShippingAddressOverride,\n} from '../../../payment/strategies/braintree';\nimport {\n PaypalAuthorizeData,\n PaypalButtonStyleColorOption,\n PaypalButtonStyleLabelOption,\n PaypalHostWindow,\n} from '../../../payment/strategies/paypal';\nimport CustomerActionCreator from '../../customer-action-creator';\nimport CustomerCredentials from '../../customer-credentials';\nimport {\n CustomerInitializeOptions,\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nimport BraintreePaypalCreditCustomerInitializeOptions from './braintree-paypal-credit-customer-options';\n\nexport default class BraintreePaypalCreditCustomerStrategy implements CustomerStrategy {\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _customerActionCreator: CustomerActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _braintreeSDKCreator: BraintreeSDKCreator,\n private _formPoster: FormPoster,\n private _window: PaypalHostWindow,\n ) {}\n\n async initialize(options: CustomerInitializeOptions): Promise {\n const { braintreepaypalcredit, methodId } = options;\n const { container, buttonHeight = 40 } = braintreepaypalcredit || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!braintreepaypalcredit) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypalcredit\" argument is not provided.`,\n );\n }\n\n if (!container) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"braintreepaypalcredit.container\" argument is not provided.`,\n );\n }\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const currencyCode = state.cart.getCartOrThrow().currency.code;\n const paypalCheckoutOptions: Partial = {\n currency: currencyCode,\n intent: paymentMethod.initializationData?.intent,\n isCreditEnabled: paymentMethod.initializationData?.isCreditEnabled,\n };\n\n const paypalCheckoutCallback = (braintreePaypalCheckout: BraintreePaypalCheckout) =>\n this._renderPayPalButton(\n braintreePaypalCheckout,\n braintreepaypalcredit,\n methodId,\n Boolean(paymentMethod.config.testMode),\n buttonHeight,\n );\n const paypalCheckoutErrorCallback = (error: BraintreeError) =>\n this._handleError(error, braintreepaypalcredit);\n\n this._braintreeSDKCreator.initialize(paymentMethod.clientToken);\n await this._braintreeSDKCreator.getPaypalCheckout(\n paypalCheckoutOptions,\n paypalCheckoutCallback,\n paypalCheckoutErrorCallback,\n );\n\n return this._store.getState();\n }\n\n deinitialize(): Promise {\n this._braintreeSDKCreator.teardown();\n\n return Promise.resolve(this._store.getState());\n }\n\n signIn(\n credentials: CustomerCredentials,\n options?: CustomerRequestOptions,\n ): Promise {\n return this._store.dispatch(\n this._customerActionCreator.signInCustomer(credentials, options),\n );\n }\n\n signOut(options?: CustomerRequestOptions): Promise {\n return this._store.dispatch(this._customerActionCreator.signOutCustomer(options));\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n\n private _renderPayPalButton(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypalcredit: BraintreePaypalCreditCustomerInitializeOptions,\n methodId: string,\n testMode: boolean,\n buttonHeight: number,\n ): void {\n const { container } = braintreepaypalcredit;\n const { paypal } = this._window;\n\n let hasRenderedSmartButton = false;\n\n if (paypal) {\n const fundingSources = [paypal.FUNDING.PAYLATER, paypal.FUNDING.CREDIT];\n const commonButtonStyle = {\n height: buttonHeight,\n color: PaypalButtonStyleColorOption.GOLD,\n };\n\n fundingSources.forEach((fundingSource) => {\n const buttonStyle =\n fundingSource === paypal.FUNDING.CREDIT\n ? { label: PaypalButtonStyleLabelOption.CREDIT, ...commonButtonStyle }\n : commonButtonStyle;\n\n if (!hasRenderedSmartButton) {\n const paypalButtonRender = paypal.Buttons({\n env: testMode ? 'sandbox' : 'production',\n commit: false,\n fundingSource,\n style: buttonStyle,\n createOrder: () =>\n this._setupPayment(\n braintreePaypalCheckout,\n braintreepaypalcredit,\n methodId,\n ),\n onApprove: (authorizeData: PaypalAuthorizeData) =>\n this._tokenizePayment(\n authorizeData,\n braintreePaypalCheckout,\n braintreepaypalcredit,\n methodId,\n ),\n });\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${container}`);\n hasRenderedSmartButton = true;\n }\n }\n });\n }\n\n if (!paypal || !hasRenderedSmartButton) {\n this._removeElement(container);\n }\n }\n\n private async _setupPayment(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypalcredit: BraintreePaypalCreditCustomerInitializeOptions,\n methodId: string,\n ): Promise {\n try {\n const state = await this._store.dispatch(\n this._checkoutActionCreator.loadDefaultCheckout(),\n );\n\n const customer = state.customer.getCustomer();\n const amount = state.checkout.getCheckoutOrThrow().outstandingBalance;\n const currencyCode = state.cart.getCartOrThrow().currency.code;\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n const address = customer?.addresses[0];\n const shippingAddressOverride = address\n ? mapToBraintreeShippingAddressOverride(address)\n : undefined;\n\n return await braintreePaypalCheckout.createPayment({\n flow: 'checkout',\n enableShippingAddress: true,\n shippingAddressEditable: false,\n shippingAddressOverride,\n amount,\n currency: currencyCode,\n offerCredit: true,\n intent: paymentMethod.initializationData?.intent,\n });\n } catch (error) {\n this._handleError(error, braintreepaypalcredit);\n }\n }\n\n private async _tokenizePayment(\n authorizeData: PaypalAuthorizeData,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypalcredit: BraintreePaypalCreditCustomerInitializeOptions,\n methodId: string,\n ): Promise {\n try {\n const { deviceData } = await this._braintreeSDKCreator.getDataCollector({\n paypal: true,\n });\n const tokenizePayload = await braintreePaypalCheckout.tokenizePayment(authorizeData);\n const { details, nonce } = tokenizePayload;\n\n this._formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n provider: methodId,\n action: 'set_external_checkout',\n nonce,\n device_data: deviceData,\n billing_address: JSON.stringify(mapToLegacyBillingAddress(details)),\n shipping_address: JSON.stringify(mapToLegacyShippingAddress(details)),\n });\n\n return tokenizePayload;\n } catch (error) {\n this._handleError(error, braintreepaypalcredit);\n }\n }\n\n private _handleError(\n error: BraintreeError,\n braintreepaypalcredit: BraintreePaypalCreditCustomerInitializeOptions,\n ): void {\n const { container, onError } = braintreepaypalcredit;\n\n this._removeElement(container);\n\n if (onError) {\n onError(error);\n } else {\n throw error;\n }\n }\n\n private _removeElement(elementId?: string): void {\n const element = elementId && document.getElementById(elementId);\n\n if (element) {\n element.remove();\n }\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotImplementedError,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { SDK_VERSION_HEADERS } from '../../../common/http-request';\nimport { PaymentMethod, PaymentMethodActionCreator } from '../../../payment';\nimport { ChasePayScriptLoader, ChasePaySuccessPayload } from '../../../payment/strategies/chasepay';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport {\n CustomerInitializeOptions,\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class ChasePayCustomerStrategy implements CustomerStrategy {\n private _paymentMethod?: PaymentMethod;\n\n constructor(\n private _store: CheckoutStore,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n private _chasePayScriptLoader: ChasePayScriptLoader,\n private _requestSender: RequestSender,\n private _formPoster: FormPoster,\n ) {}\n\n initialize(options: CustomerInitializeOptions): Promise {\n const { chasepay: chasePayOptions, methodId } = options;\n\n if (!chasePayOptions || !methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"options.chasepay\" argument is not provided.',\n );\n }\n\n return this._store\n .dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId))\n .then((state) => {\n this._paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n const cart = state.cart.getCart();\n const storeConfig = state.config.getStoreConfig();\n\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n if (\n !this._paymentMethod ||\n !this._paymentMethod.initializationData.digitalSessionId\n ) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { container } = chasePayOptions;\n\n return this._chasePayScriptLoader\n .load(this._paymentMethod.config.testMode)\n .then((JPMC) => {\n const ChasePay = JPMC.ChasePay;\n\n ChasePay.configure({\n language: storeConfig.storeProfile.storeLanguage,\n });\n\n if (ChasePay.isChasePayUp) {\n ChasePay.insertButtons({\n containers: [container],\n });\n }\n\n ChasePay.on(ChasePay.EventType.START_CHECKOUT, () => {\n this._store\n .dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n )\n .then(() => {\n const state = this._store.getState();\n const method = state.paymentMethods.getPaymentMethod(methodId);\n const sessionId =\n method &&\n method.initializationData &&\n method.initializationData.digitalSessionId;\n\n if (sessionId) {\n ChasePay.startCheckout(sessionId);\n }\n });\n });\n\n ChasePay.on(\n ChasePay.EventType.COMPLETE_CHECKOUT,\n (payload: ChasePaySuccessPayload) => {\n const state = this._store.getState();\n const method = state.paymentMethods.getPaymentMethod(methodId);\n const requestId =\n method &&\n method.initializationData &&\n method.initializationData.merchantRequestId;\n\n if (requestId) {\n this._setExternalCheckoutData(payload, requestId).then(() => {\n this._reloadPage();\n });\n }\n },\n );\n });\n })\n .then(() => this._store.getState());\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via Chase Pay®, the shopper must click on \"Chase Pay®\" button.',\n );\n }\n\n signOut(options?: CustomerRequestOptions): Promise {\n const state = this._store.getState();\n const payment = state.payment.getPaymentId();\n\n if (!payment) {\n return Promise.resolve(this._store.getState());\n }\n\n return this._store.dispatch(\n this._remoteCheckoutActionCreator.signOut(payment.providerId, options),\n );\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n\n private _setExternalCheckoutData(\n payload: ChasePaySuccessPayload,\n requestId: string,\n ): Promise> {\n const url = `checkout.php?provider=chasepay&action=set_external_checkout`;\n const options = {\n headers: {\n Accept: 'text/html',\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n ...SDK_VERSION_HEADERS,\n },\n body: {\n sessionToken: payload.sessionToken,\n merchantRequestId: requestId,\n },\n method: 'post',\n };\n\n return this._requestSender.sendRequest(url, options);\n }\n\n private _reloadPage() {\n this._formPoster.postForm('/checkout.php', {\n headers: {\n Accept: 'text/html',\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...SDK_VERSION_HEADERS,\n },\n params: {\n fromChasePay: true,\n },\n });\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport CustomerActionCreator from '../../customer-action-creator';\nimport CustomerCredentials from '../../customer-credentials';\nimport {\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class DefaultCustomerStrategy implements CustomerStrategy {\n constructor(\n private _store: CheckoutStore,\n private _customerActionCreator: CustomerActionCreator,\n ) {}\n\n signIn(\n credentials: CustomerCredentials,\n options?: CustomerRequestOptions,\n ): Promise {\n return this._store.dispatch(\n this._customerActionCreator.signInCustomer(credentials, options),\n );\n }\n\n signOut(options?: CustomerRequestOptions): Promise {\n return this._store.dispatch(this._customerActionCreator.signOutCustomer(options));\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n\n initialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n}\n","enum GooglePayCustomerMethodType {\n GOOGLEPAY_ADYENV2 = 'googlepayadyenv2',\n GOOGLEPAY_ADYENV3 = 'googlepayadyenv3',\n GOOGLEPAY_AUTHORIZENET = 'googlepayauthorizenet',\n GOOGLEPAY_BNZ = 'googlepaybnz',\n GOOGLEPAY_BRAINTREE = 'googlepaybraintree',\n GOOGLEPAY_CHECKOUTCOM = 'googlepaycheckoutcom',\n GOOGLEPAY_CYBERSOURCEV2 = 'googlepaycybersourcev2',\n GOOGLEPAY_ORBITAL = 'googlepayorbital',\n GOOGLEPAY_STRIPE = 'googlepaystripe',\n GOOGLEPAY_STRIPEUPE = 'googlepaystripeupe',\n GOOGLEPAY_WORLDPAYACCESS = 'googlepayworldpayaccess',\n}\n\nexport default GooglePayCustomerMethodType;\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotImplementedError,\n} from '../../../common/error/errors';\nimport { SDK_VERSION_HEADERS } from '../../../common/http-request';\nimport { bindDecorator as bind } from '../../../common/utility';\nimport { GooglePayPaymentProcessor } from '../../../payment/strategies/googlepay';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport { getShippableItemsCount } from '../../../shipping';\nimport {\n CustomerInitializeOptions,\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nimport GooglePayCustomerInitializeOptions from './googlepay-customer-initialize-options';\nimport { default as MethodType } from './googlepay-customer-method-type';\n\nexport default class GooglePayCustomerStrategy implements CustomerStrategy {\n private _walletButton?: HTMLElement;\n\n constructor(\n private _store: CheckoutStore,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n private _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n private _formPoster: FormPoster,\n ) {}\n\n initialize(options: CustomerInitializeOptions): Promise {\n const { methodId } = options;\n\n const googlePayOptions = this._getGooglePayOptions(options);\n\n if (!methodId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n return this._googlePayPaymentProcessor\n .initialize(methodId)\n .then(() => {\n this._walletButton = this._createSignInButton(\n googlePayOptions.container,\n googlePayOptions,\n );\n })\n .then(() => this._store.getState());\n }\n\n deinitialize(): Promise {\n if (this._walletButton && this._walletButton.parentNode) {\n this._walletButton.parentNode.removeChild(this._walletButton);\n this._walletButton = undefined;\n }\n\n return this._googlePayPaymentProcessor.deinitialize().then(() => this._store.getState());\n }\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via Google Pay, the shopper must click on \"Google Pay\" button.',\n );\n }\n\n signOut(options?: CustomerRequestOptions): Promise {\n const state = this._store.getState();\n const payment = state.payment.getPaymentId();\n\n if (!payment) {\n return Promise.resolve(this._store.getState());\n }\n\n return this._store.dispatch(\n this._remoteCheckoutActionCreator.forgetCheckout(payment.providerId, options),\n );\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n\n private _createSignInButton(\n containerId: string,\n buttonOptions: GooglePayCustomerInitializeOptions,\n ): HTMLElement {\n const container = document.querySelector(`#${containerId}`);\n const { buttonType, buttonColor } = buttonOptions;\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to create sign-in button without valid container ID.',\n );\n }\n\n const button = this._googlePayPaymentProcessor.createButton(\n this._handleWalletButtonClick,\n buttonType,\n buttonColor,\n );\n\n container.appendChild(button);\n\n return button;\n }\n\n private _getGooglePayOptions(\n options: CustomerInitializeOptions,\n ): GooglePayCustomerInitializeOptions {\n if (options.methodId === MethodType.GOOGLEPAY_ADYENV2 && options.googlepayadyenv2) {\n return options.googlepayadyenv2;\n }\n\n if (options.methodId === MethodType.GOOGLEPAY_ADYENV3 && options.googlepayadyenv3) {\n return options.googlepayadyenv3;\n }\n\n if (\n options.methodId === MethodType.GOOGLEPAY_AUTHORIZENET &&\n options.googlepayauthorizenet\n ) {\n return options.googlepayauthorizenet;\n }\n\n if (options.methodId === MethodType.GOOGLEPAY_BNZ && options.googlepaybnz) {\n return options.googlepaybnz;\n }\n\n if (options.methodId === MethodType.GOOGLEPAY_BRAINTREE && options.googlepaybraintree) {\n return options.googlepaybraintree;\n }\n\n if (options.methodId === MethodType.GOOGLEPAY_CHECKOUTCOM && options.googlepaycheckoutcom) {\n return options.googlepaycheckoutcom;\n }\n\n if (\n options.methodId === MethodType.GOOGLEPAY_CYBERSOURCEV2 &&\n options.googlepaycybersourcev2\n ) {\n return options.googlepaycybersourcev2;\n }\n\n if (options.methodId === MethodType.GOOGLEPAY_ORBITAL && options.googlepayorbital) {\n return options.googlepayorbital;\n }\n\n if (options.methodId === MethodType.GOOGLEPAY_STRIPE && options.googlepaystripe) {\n return options.googlepaystripe;\n }\n\n if (options.methodId === MethodType.GOOGLEPAY_STRIPEUPE && options.googlepaystripeupe) {\n return options.googlepaystripeupe;\n }\n if (\n options.methodId === MethodType.GOOGLEPAY_WORLDPAYACCESS &&\n options.googlepayworldpayaccess\n ) {\n return options.googlepayworldpayaccess;\n }\n\n throw new InvalidArgumentError();\n }\n\n @bind\n private async _handleWalletButtonClick(event: Event): Promise {\n event.preventDefault();\n\n const cart = this._store.getState().cart.getCartOrThrow();\n const hasPhysicalItems = getShippableItemsCount(cart) > 0;\n\n const payloadToUpdate = {\n transactionInfo: {\n currencyCode: cart.currency.code,\n totalPrice: String(cart.cartAmount),\n },\n };\n\n this._googlePayPaymentProcessor.updatePaymentDataRequest(payloadToUpdate);\n\n try {\n const paymentData = await this._googlePayPaymentProcessor.displayWallet();\n\n await this._googlePayPaymentProcessor.handleSuccess(paymentData);\n\n if (hasPhysicalItems && paymentData.shippingAddress) {\n await this._googlePayPaymentProcessor.updateShippingAddress(\n paymentData.shippingAddress,\n );\n }\n\n await this._onPaymentSelectComplete();\n } catch (error) {\n if (error && error.message !== 'CANCELED') {\n throw error;\n }\n }\n }\n\n private _onPaymentSelectComplete(): void {\n const checkoutUrl = this._store.getState().config.getStoreConfigOrThrow().links.siteLink;\n\n this._formPoster.postForm(\n window.location.pathname === '/embedded-checkout'\n ? `${checkoutUrl}/checkout`\n : '/checkout.php',\n {\n headers: {\n Accept: 'text/html',\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...SDK_VERSION_HEADERS,\n },\n },\n );\n }\n}\n","export default function getCallbackUrl(origin: string): string {\n return `${window.location.origin}/checkout.php?action=set_external_checkout&provider=masterpass&gateway=stripe&origin=${origin}`;\n}\n","export const supportedLocales: { [language: string]: string[] } = {\n es: ['es_es', 'es_mx', 'es_pe', 'es_co', 'es_ar', 'es_cl'],\n en: [\n 'en_us',\n 'en_gb',\n 'en_ca',\n 'en_es',\n 'en_fr',\n 'en_ie',\n 'en_sg',\n 'en_au',\n 'en_nz',\n 'en_my',\n 'en_hk',\n 'en_th',\n 'en_ae',\n 'en_sa',\n 'en_qa',\n 'en_kw',\n 'en_za',\n ],\n pt: ['pt_br'],\n zu: ['zu_za'],\n ar: ['ar_sa', 'ar_ae', 'ar_qa', 'ar_kw'],\n zh: ['zh_sg', 'zh_hk'],\n ms: ['ms_my'],\n uk: ['uk_ua'],\n sv: ['sv_se'],\n hr: ['hr_hr'],\n pl: ['pl_pl'],\n nl: ['nl_be'],\n it: ['it_it'],\n de: ['de_de'],\n fr: ['fr_fr', 'fr_ca'],\n};\n","import { supportedLocales } from './masterpass-supported-locales';\n\nexport default function formatLocale(localeLanguage: string): string {\n const [language, country] = localeLanguage.replace('-', '_').toLowerCase().split('_');\n const formattedLocale = `${language}_${country}`;\n const countryLocales = supportedLocales[language];\n\n if (!countryLocales) {\n return 'en_us';\n }\n\n return countryLocales.indexOf(formattedLocale) > -1 ? formattedLocale : countryLocales[0];\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotImplementedError,\n} from '../../../common/error/errors';\nimport { PaymentMethod, PaymentMethodActionCreator } from '../../../payment';\nimport {\n formatLocale,\n getCallbackUrl,\n MasterpassScriptLoader,\n} from '../../../payment/strategies/masterpass';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport {\n CustomerInitializeOptions,\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class MasterpassCustomerStrategy implements CustomerStrategy {\n private _signInButton?: HTMLElement;\n private _paymentMethod?: PaymentMethod;\n\n constructor(\n private _store: CheckoutStore,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n private _masterpassScriptLoader: MasterpassScriptLoader,\n private _locale: string,\n ) {}\n\n initialize(options: CustomerInitializeOptions): Promise {\n const { masterpass: masterpassOptions, methodId } = options;\n\n if (!masterpassOptions || !methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"options.masterpass\" argument is not provided.',\n );\n }\n\n return this._store\n .dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId))\n .then((state) => {\n this._paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n if (!this._paymentMethod || !this._paymentMethod.initializationData.checkoutId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const cart = state.cart.getCart();\n\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n const { container } = masterpassOptions;\n\n const payload = {\n checkoutId: this._paymentMethod.initializationData.checkoutId,\n allowedCardTypes: this._paymentMethod.initializationData.allowedCardTypes,\n amount: cart.cartAmount.toString(),\n currency: cart.currency.code,\n cartId: cart.id,\n suppressShippingAddress: false,\n callbackUrl: getCallbackUrl('checkout'),\n };\n\n const masterpassScriptLoaderParams = {\n useMasterpassSrc: this._paymentMethod.initializationData.isMasterpassSrcEnabled,\n language: formatLocale(this._locale),\n testMode: this._paymentMethod.config.testMode,\n checkoutId: this._paymentMethod.initializationData.checkoutId,\n };\n\n return this._masterpassScriptLoader\n .load(masterpassScriptLoaderParams)\n .then((Masterpass) => {\n this._signInButton = this._createSignInButton(container);\n\n this._signInButton.addEventListener('click', () => {\n Masterpass.checkout(payload);\n });\n });\n })\n .then(() => this._store.getState());\n }\n\n deinitialize(): Promise {\n this._paymentMethod = undefined;\n\n if (this._signInButton && this._signInButton.parentNode) {\n this._signInButton.parentNode.removeChild(this._signInButton);\n this._signInButton = undefined;\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via Masterpass, the shopper must click on \"Masterpass\" button.',\n );\n }\n\n signOut(options?: CustomerRequestOptions): Promise {\n const state = this._store.getState();\n const payment = state.payment.getPaymentId();\n\n if (!payment) {\n return Promise.resolve(this._store.getState());\n }\n\n return this._store.dispatch(\n this._remoteCheckoutActionCreator.signOut(payment.providerId, options),\n );\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n\n private _createSignInButton(containerId: string): HTMLElement {\n const container = document.querySelector(`#${containerId}`);\n\n if (!this._paymentMethod || !this._paymentMethod.initializationData.checkoutId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to create sign-in button without valid container ID.',\n );\n }\n\n const button = document.createElement('input');\n\n button.type = 'image';\n\n if (this._paymentMethod.initializationData.isMasterpassSrcEnabled) {\n const subdomain = this._paymentMethod.config.testMode ? 'sandbox.' : '';\n const { checkoutId } = this._paymentMethod.initializationData;\n\n const params = [\n `locale=${formatLocale(this._locale)}`,\n `paymentmethod=master,visa,amex,discover`,\n `checkoutid=${checkoutId}`,\n ];\n\n button.src = [\n `https://${subdomain}src.mastercard.com/assets/img/btn/src_chk_btn_126x030px.svg`,\n params.join('&'),\n ].join('?');\n } else {\n button.src =\n 'https://static.masterpass.com/dyn/img/btn/global/mp_chk_btn_160x037px.svg';\n }\n\n container.appendChild(button);\n\n return button;\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { NotImplementedError } from '../../../common/error/errors';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport {\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class SquareCustomerStrategy implements CustomerStrategy {\n constructor(\n private _store: CheckoutStore,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n ) {}\n\n signIn(): Promise {\n throw new NotImplementedError(\n 'In order to sign in via Masterpass, the shopper must click on \"Masterpass\" button.',\n );\n }\n\n signOut(options?: CustomerRequestOptions): Promise {\n const state = this._store.getState();\n const payment = state.payment.getPaymentId();\n\n if (!payment) {\n return Promise.resolve(this._store.getState());\n }\n\n return this._store.dispatch(\n this._remoteCheckoutActionCreator.signOut(payment.providerId, options),\n );\n }\n\n initialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n}\n","import { CustomFont, PaymentIntent, StripeConfigurationOptions } from '../stripev3';\n\nexport { StripeAdditionalAction } from '../stripev3';\n\nexport interface StripeError {\n /**\n * type of error. When the error type is card_error or validation_error, you can display the error message in error.message directly to your user.\n */\n type: string;\n /**\n * A human-readable message providing more details about the error. For card errors, these messages can be shown to your users.\n */\n message?: string;\n\n /**\n * The PaymentIntent object.\n */\n payment_intent: PaymentIntent;\n}\n\nexport interface StripeElement {\n /**\n * The `element.mount` method attaches your element to the DOM.\n */\n mount(domElement: string | HTMLElement): void;\n\n /**\n * Removes the element from the DOM and destroys it.\n * A destroyed element can not be re-activated or re-mounted to the DOM.\n */\n destroy(): void;\n\n /**\n * Unmounts the element from the DOM.\n * Call `element.mount` to re-attach it to the DOM.\n */\n unmount(): void;\n\n /**\n * The change event is triggered when the Element's value changes. The event payload always contains certain keys,\n * in addition to some Element-specific keys.\n * https://stripe.com/docs/js/element/events/on_change?type=paymentElement\n */\n on(event: 'change' | 'ready', handler: (event: StripeEventType) => void): void;\n}\n\nexport interface StripeEvent {\n complete: boolean;\n elementType: string;\n empty: boolean;\n}\n\nexport interface StripeCustomerEvent extends StripeEvent {\n collapsed?: boolean;\n authenticated: boolean;\n value: {\n email: string;\n };\n}\n\nexport interface StripeShippingEvent extends StripeEvent {\n mode?: string;\n isNewAddress?: boolean;\n phoneFieldRequired: boolean;\n value: {\n address: {\n city: string;\n country: string;\n line1: string;\n line2?: string;\n postal_code: string;\n state: string;\n };\n name?: string;\n firstName?: string;\n lastName?: string;\n phone?: string;\n };\n fields?: {\n phone: string;\n };\n display?: {\n name: string;\n };\n}\n\nexport type StripeEventType = StripeShippingEvent | StripeCustomerEvent;\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n * https://stripe.com/docs/api/payment_intents/confirm#confirm_payment_intent-shipping\n */\nexport interface AddressOptions {\n city?: string;\n country?: string;\n state?: string;\n postal_code?: string;\n line1?: string;\n line2?: string;\n}\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n * https://stripe.com/docs/js/elements_object/create_payment_element\n */\nexport interface AddressProperties {\n city?: AutoOrNever;\n country?: AutoOrNever;\n state?: AutoOrNever;\n postalCode?: AutoOrNever;\n line1?: AutoOrNever;\n line2?: AutoOrNever;\n}\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n */\nexport interface BillingDetailsOptions {\n name?: string;\n email?: string;\n address?: AddressOptions;\n phone?: string;\n}\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n */\nexport interface BillingDetailsProperties {\n name?: AutoOrNever;\n email?: AutoOrNever;\n address?: AutoOrNever | AddressProperties;\n phone?: AutoOrNever;\n}\n\n/**\n * Object definition for part of the data sent to confirm the PaymentIntent.\n */\nexport interface PaymentMethodDataOptions {\n billing_details: BillingDetailsOptions;\n}\n\n/**\n * Parameters that will be passed on to the Stripe API to confirm the PaymentIntent.\n */\nexport interface StripeUPEConfirmParams {\n /**\n * If you are [handling next actions yourself](https://stripe.com/docs/payments/payment-intents/verifying-status#next-actions), pass in a return_url. If the subsequent action\n * is redirect_to_url, this URL will be used on the return path for the redirect.\n *\n * @recommended\n */\n return_url?: string;\n payment_method_data?: PaymentMethodDataOptions;\n}\n\n/**\n * Data to be sent with a `stripe.confirmPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/js/payment_intents/confirm_payment) for a full list of parameters.\n */\nexport interface StripeConfirmPaymentData {\n /**\n * The Elements instance that was used to create the Payment Element.\n */\n elements: StripeElements;\n\n /**\n * Parameters that will be passed on to the Stripe API to confirm the PaymentIntent.\n */\n confirmParams?: StripeUPEConfirmParams;\n\n /**\n * By default, confirmPayment will always redirect to your return_url after a successful confirmation.\n * If you set redirect: \"if_required\", then confirmPayment will only redirect if your user chooses a redirect-based payment method.\n */\n redirect?: StripeStringConstants.ALWAYS | StripeStringConstants.IF_REQUIRED;\n}\n\nexport interface FieldsOptions {\n billingDetails?: AutoOrNever | BillingDetailsProperties;\n phone?: string;\n}\n\nexport interface WalletOptions {\n applePay?: AutoOrNever;\n googlePay?: AutoOrNever;\n}\n\n/**\n * All available options are here https://stripe.com/docs/js/elements_object/create_payment_element\n */\nexport interface StripeElementsCreateOptions {\n mode?: string;\n fields?: FieldsOptions;\n wallets?: WalletOptions;\n allowedCountries?: string[];\n defaultValues?: ShippingDefaultValues | CustomerDefaultValues;\n validation?: validationElement;\n display?: { name: DisplayName };\n}\n\ninterface validationElement {\n phone?: validationRequiredElement;\n}\n\ninterface validationRequiredElement {\n required?: string;\n}\n\ninterface ShippingDefaultValues {\n name?: string;\n firstName?: string;\n lastName?: string;\n phone: string;\n address: {\n line1: string;\n line2: string;\n city: string;\n state: string;\n postal_code: string;\n country: string;\n };\n}\n\n/*\nDecide which mode you are going to use the Address Element\nShipping: is used with the Payment Element and Link Authentication Element, it will automatically pass shipping\ninformation when confirming Payment Intent or Setup Intent.\nBilling: is used with the Payment Element, it will automatically pass the billing information when confirming\nPayment Intent or Setup Intent.\n */\nexport enum StripeFormMode {\n SHIPPING = 'shipping',\n BILLING = 'billing',\n}\n\nexport enum DisplayName {\n SPLIT = 'split',\n FULL = 'full',\n ORGANIZATION = 'organization',\n}\n\ninterface CustomerDefaultValues {\n mode: StripeFormMode;\n email: string;\n allowedCountries?: string[];\n display?: {\n name: DisplayName;\n };\n}\n\nexport interface StripeElements {\n /**\n * Creates an Elements instance, which manages a group of elements.\n * https://stripe.com/docs/js/elements_object/create\n */\n create(elementType: StripeElementType, options?: StripeElementsCreateOptions): StripeElement;\n\n /**\n * Looks up a previously created element.\n * https://stripe.com/docs/js/elements_object/get_payment_element or\n * https://stripe.com/docs/js/elements_object/get_link_authentication_element\n */\n getElement(elementType: StripeElementType): StripeElement | null;\n\n /**\n * Updates options on an existing instance of Elements.\n * https://stripe.com/docs/js/elements_object/update\n */\n update(options?: StripeUpdateElementsOptions): StripeElement;\n\n /**\n * Fetches updates from the associated PaymentIntent or SetupIntent on an existing instance of Elements,\n * and reflects these updates in the Payment Element.\n * https://stripe.com/docs/js/elements_object/fetch_updates\n */\n fetchUpdates(): void;\n}\n\n/**\n * All available options are here https://stripe.com/docs/stripe-js/appearance-api#supported-css-properties\n */\nexport interface StripeUPEAppearanceOptions {\n variables?: {\n colorPrimary?: string;\n colorBackground?: string;\n colorText?: string;\n colorDanger?: string;\n colorTextSecondary?: string;\n colorTextPlaceholder?: string;\n colorIcon?: string;\n colorIconCardError?: string;\n colorIconRedirect?: string;\n spacingUnit?: string;\n borderRadius?: string;\n };\n\n rules?: {\n '.Input'?: {\n borderColor?: string;\n color?: string;\n boxShadow?: string;\n };\n };\n}\n\nexport interface StripeElementsOptions {\n /**\n * An array of custom fonts, which elements created from the Elements object can use.\n * Fonts can be specified as [CssFontSource](https://stripe.com/docs/js/appendix/css_font_source_object)\n * or [CustomFontSource](https://stripe.com/docs/js/appendix/custom_font_source_object) objects.\n */\n fonts?: CustomFont[];\n\n /**\n * A [locale](https://stripe.com/docs/js/appendix/supported_locales) to display placeholders and\n * error strings in. Default is auto (Stripe detects the locale of the browser).\n * Setting the locale does not affect the behavior of postal code validation—a valid postal code\n * for the billing country of the card is still required.\n */\n locale?: string;\n\n /**\n * The client secret of this PaymentIntent. Used for client-side retrieval using a publishable key.\n * The client secret can be used to complete a payment from your frontend.\n * It should not be stored, logged, embedded in URLs, or exposed to anyone other than the customer.\n * Make sure that you have TLS enabled on any page that includes the client secret.\n * Refer to our docs to accept a payment and learn about how client_secret should be handled.\n */\n clientSecret: string;\n\n /**\n * Match the design of your site with the appearance option.\n * The layout of each Element stays consistent, but you can modify colors, fonts, borders, padding, and more.\n */\n appearance?: StripeUPEAppearanceOptions;\n}\n\nexport interface StripeUpdateElementsOptions {\n /**\n * A [locale](https://stripe.com/docs/js/appendix/supported_locales) to display placeholders and\n * error strings in. Default is auto (Stripe detects the locale of the browser).\n * Setting the locale does not affect the behavior of postal code validation—a valid postal code\n * for the billing country of the card is still required.\n */\n locale?: string;\n\n /**\n * Match the design of your site with the appearance option.\n * The layout of each Element stays consistent, but you can modify colors, fonts, borders, padding, and more.\n */\n appearance?: StripeUPEAppearanceOptions;\n}\n\nexport interface StripeUPEClient {\n /**\n * Use confirmPayment to confirm a PaymentIntent using data collected by the Payment Element.\n * When called, confirmPayment will attempt to complete any required actions,\n * such as authenticating your user by displaying a 3DS dialog or redirecting them to a bank authorization page.\n */\n confirmPayment(options: StripeConfirmPaymentData): Promise;\n\n /**\n * When called, it will confirm the PaymentIntent with data you provide and carry out 3DS or other next actions if they are required.\n */\n confirmCardPayment(clientSecret: string): Promise;\n\n /**\n * Retrieve a PaymentIntent using its client secret.\n */\n retrievePaymentIntent(clientSecret: string): Promise;\n\n /**\n * Create an `Elements` instance, which manages a group of elements.\n */\n elements(options: StripeElementsOptions): StripeElements;\n}\n\ninterface StripeUpeResult {\n paymentIntent?: PaymentIntent;\n error?: StripeError;\n}\n\nexport interface StripeHostWindow extends Window {\n bcStripeClient?: StripeUPEClient;\n bcStripeElements?: StripeElements;\n Stripe?(stripePublishableKey: string, options?: StripeConfigurationOptions): StripeUPEClient;\n}\n\nexport enum StripePaymentMethodType {\n CreditCard = 'card',\n SOFORT = 'sofort',\n EPS = 'eps',\n GRABPAY = 'grabpay',\n BANCONTACT = 'bancontact',\n IDEAL = 'ideal',\n GIROPAY = 'giropay',\n ALIPAY = 'alipay',\n KLARNA = 'klarna',\n}\n\ntype AutoOrNever = StripeStringConstants.AUTO | StripeStringConstants.NEVER;\n\nexport enum StripeStringConstants {\n NEVER = 'never',\n AUTO = 'auto',\n ALWAYS = 'always',\n PAYMENT = 'payment',\n IF_REQUIRED = 'if_required',\n}\n\nexport enum StripeElementType {\n PAYMENT = 'payment',\n AUTHENTICATION = 'linkAuthentication',\n SHIPPING = 'address',\n}\n","import { createAction } from '@bigcommerce/data-store';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../../../common/error/errors';\nimport { PaymentMethodActionCreator } from '../../../payment';\nimport {\n StripeElements,\n StripeElementType,\n StripeEventType,\n StripeFormMode,\n StripeScriptLoader,\n StripeUPEAppearanceOptions,\n StripeUPEClient,\n} from '../../../payment/strategies/stripe-upe';\nimport { ConsignmentActionCreator } from '../../../shipping';\nimport CustomerActionCreator from '../../customer-action-creator';\nimport { CustomerActionType } from '../../customer-actions';\nimport CustomerCredentials from '../../customer-credentials';\nimport {\n CustomerInitializeOptions,\n CustomerRequestOptions,\n ExecutePaymentMethodCheckoutOptions,\n} from '../../customer-request-options';\nimport CustomerStrategy from '../customer-strategy';\n\nexport default class StripeUPECustomerStrategy implements CustomerStrategy {\n private _stripeElements?: StripeElements;\n\n constructor(\n private _store: CheckoutStore,\n private _stripeUPEScriptLoader: StripeScriptLoader,\n private _customerActionCreator: CustomerActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _consignmentActionCreator: ConsignmentActionCreator,\n ) {}\n\n async initialize(options: CustomerInitializeOptions): Promise {\n let stripeUPEClient: StripeUPEClient;\n\n if (!options.stripeupe) {\n throw new InvalidArgumentError(\n `Unable to proceed because \"options\" argument is not provided.`,\n );\n }\n\n const { container, gatewayId, methodId, onEmailChange, getStyles, isLoading } =\n options.stripeupe;\n\n Object.entries(options.stripeupe).forEach(([key, value]) => {\n if (!value) {\n throw new InvalidArgumentError(\n `Unable to proceed because \"${key}\" argument is not provided.`,\n );\n }\n });\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n customer: { getCustomerOrThrow },\n } = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n }),\n );\n const {\n clientToken,\n initializationData: { stripePublishableKey, stripeConnectedAccount } = {},\n } = getPaymentMethodOrThrow(methodId, gatewayId);\n const { email, isStripeLinkAuthenticated } = getCustomerOrThrow();\n\n if (!email) {\n if (!stripePublishableKey || !clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n let appearance: StripeUPEAppearanceOptions | undefined;\n const styles = typeof getStyles === 'function' && getStyles();\n\n if (styles) {\n appearance = {\n variables: {\n colorPrimary: styles.fieldInnerShadow,\n colorBackground: styles.fieldBackground,\n colorText: styles.labelText,\n colorDanger: styles.fieldErrorText,\n colorTextSecondary: styles.labelText,\n colorTextPlaceholder: styles.fieldPlaceholderText,\n },\n rules: {\n '.Input': {\n borderColor: styles.fieldBorder,\n color: styles.fieldText,\n boxShadow: styles.fieldInnerShadow,\n },\n },\n };\n } else {\n appearance = {};\n }\n\n stripeUPEClient = await this._stripeUPEScriptLoader.getStripeClient(\n stripePublishableKey,\n stripeConnectedAccount,\n );\n\n this._stripeElements = this._stripeUPEScriptLoader.getElements(stripeUPEClient, {\n clientSecret: clientToken,\n appearance,\n });\n\n const {\n billingAddress: { getBillingAddress },\n consignments: { getConsignments },\n } = this._store.getState();\n const consignments = getConsignments();\n const id = consignments?.[0]?.id;\n const { email: billingEmail } = getBillingAddress() || {};\n const options = billingEmail\n ? { defaultValues: { mode: StripeFormMode.SHIPPING, email: billingEmail } }\n : {};\n const linkAuthenticationElement =\n this._stripeElements.getElement(StripeElementType.AUTHENTICATION) ||\n this._stripeElements.create(StripeElementType.AUTHENTICATION, options);\n\n linkAuthenticationElement.on('change', (event: StripeEventType) => {\n if (!('authenticated' in event)) {\n throw new MissingDataError(MissingDataErrorType.MissingCustomer);\n }\n\n this._store.dispatch(\n createAction(CustomerActionType.StripeLinkAuthenticated, event.authenticated),\n );\n event.complete\n ? onEmailChange(event.authenticated, event.value.email)\n : onEmailChange(false, '');\n\n if (isLoading) {\n isLoading(false);\n }\n\n if (isStripeLinkAuthenticated === undefined && event.authenticated && id) {\n this._store.dispatch(this._consignmentActionCreator.deleteConsignment(id));\n }\n });\n\n linkAuthenticationElement.mount(`#${container}`);\n }\n\n return this._store.getState();\n }\n\n deinitialize(): Promise {\n this._stripeElements?.getElement(StripeElementType.AUTHENTICATION)?.unmount();\n\n return Promise.resolve(this._store.getState());\n }\n\n signIn(\n credentials: CustomerCredentials,\n options?: CustomerRequestOptions,\n ): Promise {\n return this._store.dispatch(\n this._customerActionCreator.signInCustomer(credentials, options),\n );\n }\n\n signOut(options?: CustomerRequestOptions): Promise {\n return this._store.dispatch(this._customerActionCreator.signOutCustomer(options));\n }\n\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n options?.continueWithCheckoutCallback?.();\n\n return Promise.resolve(this._store.getState());\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport class ExtensionNotFoundError extends StandardError {\n constructor(message?: string) {\n super(message || 'Unable to proceed due to no extension configured for this region.');\n\n this.name = 'ExtensionNotFoundError';\n this.type = 'extension_not_found';\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Extension } from './extension';\n\nexport enum ExtensionActionType {\n LoadExtensionsRequested = 'LOAD_EXTENSIONS_REQUESTED',\n LoadExtensionsSucceeded = 'LOAD_EXTENSIONS_SUCCEEDED',\n LoadExtensionsFailed = 'LOAD_EXTENSIONS_FAILED',\n RenderExtensionRequested = 'RENDER_EXTENSION_REQUESTED',\n RenderExtensionSucceeded = 'RENDER_EXTENSION_SUCCEEDED',\n RenderExtensionFailed = 'RENDER_EXTENSION_FAILED',\n}\n\nexport type ExtensionAction =\n | LoadExtensionsRequestedAction\n | LoadExtensionsSucceededAction\n | LoadExtensionsFailedAction\n | RenderExtensionRequestedAction\n | RenderExtensionSucceededAction\n | RenderExtensionFailedAction;\n\nexport interface LoadExtensionsRequestedAction extends Action {\n type: ExtensionActionType.LoadExtensionsRequested;\n}\n\nexport interface LoadExtensionsSucceededAction extends Action {\n type: ExtensionActionType.LoadExtensionsSucceeded;\n}\n\nexport interface LoadExtensionsFailedAction extends Action {\n type: ExtensionActionType.LoadExtensionsFailed;\n}\n\nexport interface RenderExtensionRequestedAction extends Action {\n type: ExtensionActionType.RenderExtensionRequested;\n}\n\nexport interface RenderExtensionSucceededAction extends Action {\n type: ExtensionActionType.RenderExtensionSucceeded;\n}\n\nexport interface RenderExtensionFailedAction extends Action {\n type: ExtensionActionType.RenderExtensionFailed;\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport class InvalidExtensionConfigError extends StandardError {\n constructor(message?: string) {\n super(\n message || 'Unable to proceed due to invalid configuration provided for the extension.',\n );\n\n this.name = 'InvalidExtensionConfigError';\n this.type = 'invalid_extension_config';\n }\n}\n","import { InvalidExtensionConfigError } from './errors';\nimport { Extension } from './extension';\n\nexport class ExtensionIframe {\n private _iframe: HTMLIFrameElement;\n\n constructor(\n private _containerId: string,\n private _extension: Extension,\n private _cartId: string,\n ) {\n const url = new URL(this._extension.url);\n\n url.searchParams.set('extensionId', this._extension.id);\n url.searchParams.set('cartId', this._cartId);\n\n this._iframe = document.createElement('iframe');\n this._iframe.src = url.toString();\n this._iframe.style.border = 'none';\n this._iframe.style.height = '100%';\n this._iframe.style.overflow = 'hidden';\n this._iframe.style.width = '100%';\n }\n\n attach(): void {\n const container = document.getElementById(this._containerId);\n\n if (!container) {\n throw new InvalidExtensionConfigError(\n 'Unable to proceed because the provided container ID is invalid.',\n );\n }\n\n container.appendChild(this._iframe);\n }\n\n detach(): void {\n if (!this._iframe.parentElement) {\n return;\n }\n\n this._iframe.parentElement.removeChild(this._iframe);\n }\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { RequestOptions } from '../common/http-request';\n\nimport { ExtensionNotFoundError } from './errors';\nimport { ExtensionRegion } from './extension';\nimport { ExtensionAction, ExtensionActionType } from './extension-actions';\nimport { ExtensionIframe } from './extension-iframe';\nimport { ExtensionRequestSender } from './extension-request-sender';\n\nexport class ExtensionActionCreator {\n constructor(private _requestSender: ExtensionRequestSender) {}\n\n loadExtensions(\n options?: RequestOptions,\n ): ThunkAction {\n return () =>\n Observable.create((observer: Observer) => {\n observer.next(createAction(ExtensionActionType.LoadExtensionsRequested));\n\n this._requestSender\n .loadExtensions(options)\n .then((response) => {\n const extensions = response.body;\n\n observer.next(\n createAction(ExtensionActionType.LoadExtensionsSucceeded, extensions),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(ExtensionActionType.LoadExtensionsFailed, response),\n );\n });\n });\n }\n\n renderExtension(\n container: string,\n region: ExtensionRegion,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const { id: cartId } = state.cart.getCartOrThrow();\n const extension = state.extensions.getExtensionByRegion(region);\n\n if (!extension) {\n throw new ExtensionNotFoundError(\n `Unable to proceed due to no extension configured for ${region}.`,\n );\n }\n\n observer.next(createAction(ExtensionActionType.RenderExtensionRequested));\n\n try {\n const iframe = new ExtensionIframe(container, extension, cartId);\n\n iframe.attach();\n\n observer.next(createAction(ExtensionActionType.RenderExtensionSucceeded));\n observer.complete();\n } catch (error) {\n observer.error(\n createErrorAction(ExtensionActionType.RenderExtensionFailed, error),\n );\n }\n });\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { ContentType, RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nimport { Extension } from './extension';\n\nexport const EXTENSIONS_API_URL = '/api/storefront/checkout-extensions';\n\nexport class ExtensionRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n loadExtensions({ timeout, params }: RequestOptions = {}): Promise> {\n return this._requestSender.get(EXTENSIONS_API_URL, {\n timeout,\n headers: {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n },\n params,\n });\n }\n}\n","import InvalidArgumentError from './invalid-argument-error';\n\n/**\n * This error should be thrown when we are unable to submit a payment because\n * the caller has not provided all the required fields, i.e.: if an argument is\n * missing or it is not the expected data type.\n */\nexport default class PaymentArgumentInvalidError extends InvalidArgumentError {\n constructor(invalidFields?: string[]) {\n let message = 'Unable to submit payment for the order because the payload is invalid.';\n\n if (invalidFields) {\n message = `${message} Make sure the following fields are provided correctly: ${invalidFields.join(\n ', ',\n )}.`;\n }\n\n super(message);\n\n this.name = 'PaymentArgumentInvalidError';\n }\n}\n","import {\n FormattedPayload,\n FormattedVaultedInstrument,\n HostedVaultedInstrument,\n PaymentInstrument,\n VaultedInstrument,\n} from './payment';\n\nexport default function isVaultedInstrument(\n instrument: PaymentInstrument,\n): instrument is VaultedInstrument {\n return Boolean((instrument as VaultedInstrument).instrumentId);\n}\n\nexport function isHostedVaultedInstrument(\n instrument: PaymentInstrument,\n): instrument is HostedVaultedInstrument {\n return (\n Boolean((instrument as HostedVaultedInstrument).instrumentId) &&\n !Object.prototype.hasOwnProperty.call(instrument, 'ccNumber') &&\n !Object.prototype.hasOwnProperty.call(instrument, 'ccCvv')\n );\n}\n\nexport function isFormattedVaultedInstrument(\n instrument: PaymentInstrument,\n): instrument is FormattedPayload {\n const formattedInstrument = (instrument as FormattedPayload)\n .formattedPayload;\n\n if (!formattedInstrument) {\n return false;\n }\n\n return (\n typeof formattedInstrument.bigpay_token === 'string' ||\n Boolean(formattedInstrument.bigpay_token && formattedInstrument.bigpay_token.token)\n );\n}\n","import BrowserInfo from './browser-info';\n\nexport default function getBrowserInfo(): BrowserInfo {\n const { navigator } = window;\n\n let language: string;\n\n if (navigator.language) {\n language = navigator.language;\n } else {\n language = (navigator as any).userLanguage;\n }\n\n return {\n color_depth: window.screen.colorDepth || 24,\n java_enabled: typeof navigator.javaEnabled === 'function' ? navigator.javaEnabled() : false,\n language,\n screen_height: window.screen.height,\n screen_width: window.screen.width,\n time_zone_offset: new Date().getTimezoneOffset().toString(),\n };\n}\n","import StandardError from './standard-error';\n\n/**\n * Throw this error if we are trying to make an order finalization request for a\n * payment method that does not require such procedure.\n */\nexport default class OrderFinalizationNotRequiredError extends StandardError {\n constructor() {\n super('The current order does not need to be finalized at this stage.');\n\n this.name = 'OrderFinalizationNotRequiredError';\n this.type = 'order_finalization_not_required';\n }\n}\n","import RequestError from './request-error';\n\n// Have to use `as` https://stackoverflow.com/questions/73987044/typeguarding-an-unknown-nested-object should be fixed in 4.8+\nconst isRequestError = (error: unknown): error is RequestError => {\n return typeof error === 'object' && error !== null && 'body' in error;\n};\n\nexport default isRequestError;\n","import StandardError from './standard-error';\n\nexport interface PaymentInvalidFormErrorDetails {\n [key: string]: Array<{ message: string; type: string }>;\n}\n\nexport default class PaymentInvalidFormError extends StandardError {\n constructor(public details: PaymentInvalidFormErrorDetails, message?: string) {\n super(message || 'Unable to proceed because the payment form contains invalid data.');\n\n this.name = 'PaymentInvalidFormError';\n this.type = 'payment_invalid_form';\n }\n}\n","export enum AdyenActionType {\n /*\n * The payment qualifies for 3D Secure 2, and will go through either the frictionless\n * or the challenge flow.\n * */\n ThreeDS2Fingerprint = 'threeDS2Fingerprint',\n\n /*\n * The payment qualifies for 3D Secure 2, and the issuer is initiating a challenge flow.\n * */\n ThreeDS2Challenge = 'threeDS2Challenge',\n\n /*\n * We will initiate a 3D Secure 1 fallback, because the issuer does not support 3D Secure 2.\n * */\n Redirect = 'redirect',\n\n /*\n * The Component presents the QR code and calls the onAdditionalDetails event.\n * */\n QRCode = 'qrCode',\n\n /*\n * The Component displays the voucher which the shopper uses to complete the payment.\n * */\n Voucher = 'voucher',\n}\n\nexport enum AdyenComponentType {\n SecuredFields = 'securedfields',\n}\n\nexport enum AdyenPaymentMethodType {\n ACH = 'ach',\n AliPay = 'alipay',\n Bancontact = 'bcmc',\n CreditCard = 'scheme',\n Klarna = 'klarna',\n KlarnaPayNow = 'klarna_paynow',\n KlarnaAccount = 'klarna_account',\n IDEAL = 'ideal',\n GiroPay = 'giropay',\n GooglePay = 'paywithgoogle',\n SEPA = 'sepadirectdebit',\n Sofort = 'directEbanking',\n Vipps = 'vipps',\n WeChatPayQR = 'wechatpayQR',\n}\n\nexport enum HTTPMethod {\n POST = 'POST',\n}\n\nexport enum ResultCode {\n ChallengeShopper = 'ChallengeShopper',\n Error = 'Error',\n IdentifyShopper = 'IdentifyShopper',\n}\n\ninterface AdyenPaymentMethodState {\n type: string;\n}\n\ninterface CardDataPaymentMethodState {\n paymentMethod: CardPaymentMethodState;\n}\n\ninterface WechatDataPaymentMethodState {\n paymentMethod: AdyenPaymentMethodState;\n}\n\ninterface CardPaymentMethodState extends AdyenPaymentMethodState {\n encryptedCardNumber: string;\n encryptedExpiryMonth: string;\n encryptedExpiryYear: string;\n encryptedSecurityCode: string;\n holderName: string;\n}\n\nexport interface AdyenAction {\n method: HTTPMethod;\n\n /**\n * Value that you need to submit in your /payments/details request when handling\n * the redirect.\n */\n paymentData: string;\n\n paymentMethodType: AdyenPaymentMethodType;\n\n /*\n * The Component performs additional front-end actions depending on the action.type.\n * Your next steps depend on the type of action that the Component performs.\n */\n type: AdyenActionType;\n\n /**\n * The HTTP request method that you should use. After the shopper completes the payment,\n * they will be redirected back to your returnURL using the same method.\n */\n url: string;\n}\n\nexport interface AdyenAdditionalAction {\n resultCode: ResultCode;\n action: string;\n}\n\nexport interface AdyenAdditionalActionCallbacks {\n /**\n * A callback that gets called before adyen component is loaded\n */\n onBeforeLoad?(shopperInteraction?: boolean): void;\n\n /**\n * A callback that gets called when adyen component is loaded\n */\n onLoad?(cancel?: () => void): void;\n\n /**\n * A callback that gets called when adyen component verification\n * is completed\n */\n onComplete?(): void;\n}\n\nexport interface AdyenAdditionalActionErrorResponse {\n provider_data: AdyenAdditionalAction;\n errors: [\n {\n code: string;\n },\n ];\n}\n\nexport interface AdyenAdditionalActionOptions extends AdyenAdditionalActionCallbacks {\n /**\n * The location to insert the additional action component.\n */\n containerId: string;\n\n /**\n * Specify Three3DS2Challenge Widget Size\n *\n * Values\n * '01' = 250px x 400px\n * '02' = 390px x 400px\n * '03' = 500px x 600px\n * '04' = 600px x 400px\n * '05' = 100% x 100%\n */\n widgetSize?: string;\n}\n\nexport interface AdyenAdditionalActionState {\n data: AdyenAdditionalAction;\n isValid?: boolean;\n}\n\nexport interface AdyenBaseCardComponentOptions {\n /**\n * Array of card brands that will be recognized by the component.\n *\n */\n brands?: string[];\n\n /**\n * Set a style object to customize the input fields. See Styling Secured Fields\n * for a list of supported properties.\n */\n styles?: StyleOptions;\n}\n\nexport interface AdyenComponentEvents {\n /**\n * Called when the shopper enters data in the card input fields.\n * Here you have the option to override your main Adyen Checkout configuration.\n */\n onChange?(state: AdyenComponentState, component: AdyenComponent): void;\n\n /**\n * Called in case of an invalid card number, invalid expiry date, or\n * incomplete field. Called again when errors are cleared.\n */\n onError?(state: AdyenV2ValidationState, component: AdyenComponent): void;\n\n onFieldValid?(state: AdyenV2ValidationState, component: AdyenComponent): void;\n}\n\nexport interface AdyenClient {\n create(type: string, componentOptions?: AdyenComponentOptions): AdyenComponent;\n\n createFromAction(\n action: AdyenAction,\n componentOptions?:\n | ThreeDS2DeviceFingerprintComponentOptions\n | ThreeDS2ChallengeComponentOptions,\n ): AdyenComponent;\n}\n\nexport interface AdyenComponent {\n componentRef?: {\n showValidation(): void;\n };\n props?: {\n type?: string;\n };\n state?: CardState;\n mount(containerId: string): HTMLElement;\n unmount(): void;\n}\n\nexport interface AdyenConfiguration {\n /*\n * Use test, and then change this to live when you're ready to accept live payments.\n */\n environment?: string;\n\n /*\n * The shopper's locale. This is used to set the language rendered in the Components.\n */\n locale?: string;\n\n /*\n * The Origin Key of your website.\n */\n originKey?: string;\n\n /*\n * The Client Key of your Adyen account.\n */\n clientKey?: string;\n\n /*\n * Supported from Components version 3.0.0 and later. The full paymentMethods response,\n * returned in step 1. We recommend that you pass this on the AdyenCheckout instance.\n * Otherwise, you need to pass the specific payment method details separately for each\n * Component.\n */\n paymentMethodsResponse?: PaymentMethodsResponse;\n\n /**\n * If your shoppers use a language that isn't supported by the Components, you can create your own localization.\n * To create a localization:\n * Add a translations object to your payment page, specifying:\n * The localization you want to create.\n * An object containing the fields that are used in the Components, as well as the text you want displayed for each field.\n *\n * \"en\": {\n * \"paymentMethods.moreMethodsButton\": \"More payment methods\",\n * \"payButton\": \"Pay\",\n * \"storeDetails\": \"Save for my next payment\",\n * ...\n * }\n */\n translations?: {\n [index: string]: {\n [index: string]: string;\n };\n };\n\n /*\n * Specify the function that you created, for example, handleOnChange. If you wish\n * to override this function, you can also define an onChange event on the Component\n * level.\n */\n onChange?(state: CardState, component?: AdyenComponent): void;\n\n onAdditionalDetails?(state: CardState, component?: AdyenComponent): void;\n}\n\nexport interface AdyenPlaceholderData {\n holderName?: string;\n prefillCardHolderName?: boolean;\n billingAddress?: {\n street: string;\n houseNumberOrName: string;\n postalCode: string;\n city: string;\n stateOrProvince: string;\n country: string;\n };\n}\n\nexport interface AdyenCreditCardComponentOptions\n extends AdyenBaseCardComponentOptions,\n AdyenComponentEvents {\n /**\n * Set an object containing the details array for type: scheme from\n * the /paymentMethods response.\n */\n details?: InputDetail[];\n\n /**\n * Set to true to show the checkbox to save card details for the next payment.\n */\n enableStoreDetails?: boolean;\n\n /**\n * Set to true to request the name of the card holder.\n */\n hasHolderName?: boolean;\n\n /**\n * Set to true to require the card holder name.\n */\n holderNameRequired?: boolean;\n\n /**\n * Information to prefill fields.\n */\n data?: AdyenPlaceholderData;\n\n /**\n * Defaults to ['mc','visa','amex']. Configure supported card types to\n * facilitate brand recognition used in the Secured Fields onBrand callback.\n * See list of available card types. If a shopper enters a card type not\n * specified in the GroupTypes configuration, the onBrand callback will not be invoked.\n */\n groupTypes?: string[];\n\n /**\n * Specify the sample values you want to appear for card detail input fields.\n */\n placeholders?: CreditCardPlaceHolder | SepaPlaceHolder;\n}\n\nexport interface AdyenCustomCardComponentOptions\n extends AdyenBaseCardComponentOptions,\n AdyenComponentEvents {\n /**\n * Specify aria attributes for the input fields for web accessibility.\n */\n ariaLabels?: CustomCardAriaLabels;\n\n /**\n * Automatically shift the focus from date field to the CVC field.\n */\n autofocus?: boolean;\n}\n\nexport interface AdyenError {\n errorCode: string;\n message: string;\n}\n\nexport interface AdyenHostWindow extends Window {\n AdyenCheckout?: new (configuration: AdyenConfiguration) => AdyenClient;\n}\n\nexport interface AdyenIdealComponentOptions extends AdyenBaseCardComponentOptions {\n /**\n * Optional. Set to **false** to remove the bank logos from the iDEAL form.\n */\n showImage?: boolean;\n}\n\nexport interface AdyenStoredPaymentMethod {\n /**\n * The brand of the card.\n */\n brand?: string;\n\n /**\n * The month the card expires.\n */\n expiryMonth?: string;\n\n /**\n * The year the card expires.\n */\n expiryYear?: string;\n\n /**\n * The unique payment method code.\n */\n holderName?: string;\n\n /**\n * A unique identifier of this stored payment method.\n */\n id?: string;\n\n /**\n * The last four digits of the PAN.\n */\n lastFour?: string;\n\n /**\n * The display name of the stored payment method.\n */\n name: string;\n\n /**\n * The shopper’s email address.\n */\n shopperEmail?: string;\n\n /**\n * The supported shopper interactions for this stored payment method.\n */\n supportedShopperInteractions?: string[];\n\n /**\n * The type of payment method.\n */\n type?: string;\n}\n\nexport interface AdyenThreeDS2Options extends AdyenAdditionalActionCallbacks {\n /**\n * Specify Three3DS2Challenge Widget Size\n *\n * Values\n * '01' = 250px x 400px\n * '02' = 390px x 400px\n * '03' = 500px x 600px\n * '04' = 600px x 400px\n * '05' = 100% x 100%\n */\n widgetSize?: string;\n}\n\nexport interface Bank {\n /**\n * The bank account number (without separators).\n */\n bankAccountNumber?: string;\n\n /**\n * The bank city.\n */\n bankCity?: string;\n\n /**\n * The location id of the bank. The field value is nil in most cases.\n */\n bankLocationId?: string;\n\n /**\n * The name of the bank.\n */\n bankName?: string;\n\n /**\n * The Business Identifier Code (BIC) is the SWIFT address assigned to\n * a bank. The field value is nil in most cases.\n */\n bic?: string;\n\n /**\n * Country code where the bank is located.\n * A valid value is an ISO two-character country code (e.g. 'NL').\n */\n countryCode?: string;\n\n /**\n * The International Bank Account Number (IBAN).\n */\n iban?: string;\n\n /**\n * The name of the bank account holder. If you submit a name with non-Latin\n * characters, we automatically replace some of them with corresponding Latin\n * characters to meet the FATF recommendations. For example:\n * χ12 is converted to ch12.\n * üA is converted to euA.\n * Peter Møller is converted to Peter Mller, because banks don't accept 'ø'.\n * After replacement, the ownerName must have at least three alphanumeric characters\n * (A-Z, a-z, 0-9), and at least one of them must be a valid Latin character\n * (A-Z, a-z). For example:\n * John17 - allowed.\n * J17 - allowed.\n * 171 - not allowed.\n * John-7 - allowed.\n */\n ownerName?: string;\n\n /**\n * The bank account holder's tax ID.\n */\n taxId?: string;\n}\n\nexport interface Card {\n /**\n * The card verification code (1-20 characters). Depending on the card brand, it\n * is known also as:\n * CVV2/CVC2 – length: 3 digits\n * CID – length: 4 digits\n */\n cvc?: string;\n\n /**\n * The card expiry month. Format: 2 digits, zero-padded for single digits. For example:\n * 03 = March\n * 11 = November\n * Required\n */\n expiryMonth: string;\n\n /**\n * The card expiry year. Format: 4 digits. For example: 2020\n * Required\n */\n expiryYear: string;\n\n /**\n * The name of the cardholder, as printed on the card.\n * Required\n */\n holderName: string;\n\n /**\n * The issue number of the card (for some UK debit cards only).\n */\n issueNumber?: string;\n\n /**\n * The card number (4-19 characters). Do not use any separators. When this value is\n * returned in a response, only the last 4 digits of the card number are returned.\n * Required\n */\n number: string;\n\n /**\n * The month component of the start date (for some UK debit cards only).\n */\n startNumber?: string;\n\n /**\n * The year component of the start date (for some UK debit cards only).\n */\n startYear?: string;\n}\n\nexport interface CardState {\n data: CardDataPaymentMethodState;\n isValid?: boolean;\n issuer?: string;\n valid?: { [key: string]: boolean };\n errors?: CardStateErrors;\n}\n\nexport interface CardStateErrors {\n [key: string]: string;\n}\n\nexport interface WechatState {\n data: WechatDataPaymentMethodState;\n}\n\nexport interface CreditCardPlaceHolder {\n encryptedCardNumber?: string;\n encryptedExpiryDate?: string;\n encryptedSecurityCode: string;\n}\n\ninterface AccountDataPaymentMethodState {\n paymentMethod: AdyenPaymentMethodState;\n}\n\nexport interface AccountState {\n data: AccountDataPaymentMethodState;\n}\n\nexport interface CssProperties {\n background?: string;\n caretColor?: string;\n color?: string;\n display?: string;\n font?: string;\n fontFamily?: string;\n fontSize?: string;\n fontSizeAdjust?: string;\n fontSmoothing?: string;\n fontStretch?: string;\n fontStyle?: string;\n fontVariant?: string;\n fontVariantAlternates?: string;\n fontVariantCaps?: string;\n fontVariantEastAsian?: string;\n fontVariantLigatures?: string;\n fontVariantNumeric?: string;\n fontWeight?: string;\n letterSpacing?: string;\n lineHeight?: string;\n mozOsxFontSmoothing?: string;\n mozTransition?: string;\n outline?: string;\n opacity?: string | number;\n padding?: string;\n textAlign?: string;\n textShadow?: string;\n transition?: string;\n webkitFontSmoothing?: string;\n webkitTransition?: string;\n}\n\nexport interface CustomCardAriaLabel {\n label?: string;\n iframeTitle?: string;\n}\n\nexport interface CustomCardAriaLabels {\n lang?: string;\n encryptedCardNumber?: CustomCardAriaLabel;\n encryptedExpiryDate?: CustomCardAriaLabel;\n encryptedSecurityCode?: CustomCardAriaLabel;\n}\n\nexport interface Group {\n /**\n * The name of the group.\n */\n name?: string;\n\n /**\n * Echo data to be used if the payment method is displayed as part of this group.\n */\n paymentMethodData?: string;\n\n /**\n * The unique code of the group.\n */\n type?: string;\n}\n\nexport interface InputDetail {\n /**\n * Configuration parameters for the required input.\n */\n configuration?: object;\n\n /**\n * Input details can also be provided recursively.\n */\n details?: SubInputDetail[];\n\n /**\n * In case of a select, the URL from which to query the items.\n */\n itemSearchUrl?: string;\n\n /**\n * In case of a select, the items to choose from.\n */\n items?: Item[];\n\n /**\n * The value to provide in the result.\n */\n key?: string;\n\n /**\n * True if this input value is optional.\n */\n optional?: boolean;\n\n /**\n * The type of the required input.\n */\n type?: string;\n\n /**\n * The value can be pre-filled, if available.\n */\n value?: string;\n}\n\nexport interface Item {\n /**\n * The value to provide in the result.\n */\n id?: string;\n\n /**\n * The display name.\n */\n name?: string;\n}\n\nexport interface PaymentMethod {\n /**\n * List of possible brands. For example: visa, mc.\n */\n brands?: string[];\n\n /**\n * The configuration of the payment method.\n */\n configuration?: object;\n\n /**\n * All input details to be provided to complete the payment with this payment\n * method.\n */\n details?: InputDetail[];\n\n /**\n * The group where this payment method belongs to.\n */\n group?: Group;\n\n /**\n * The displayable name of this payment method.\n */\n name?: string;\n\n /**\n * Echo data required to send in next calls.\n */\n paymentMethodData?: string;\n\n /**\n * Indicates whether this payment method supports tokenization or not.\n */\n supportsRecurring?: boolean;\n\n /**\n * The unique payment method code.\n */\n type?: string;\n}\n\nexport interface PaymentMethodGroup {\n /**\n * The type to submit for any payment method in this group.\n */\n groupType?: string;\n\n /**\n * The human-readable name of this group.\n */\n name?: string;\n\n /**\n * The types of payment methods that belong in this group.\n */\n types?: string[];\n}\n\nexport interface PaymentMethodsResponse {\n /**\n * Groups of payment methods.\n */\n groups?: PaymentMethodGroup[];\n\n /**\n * Detailed list of one-click payment methods.\n */\n oneClickPaymentMethods?: RecurringDetail;\n\n /**\n * Detailed list of payment methods required to generate payment forms.\n */\n paymentMethods?: PaymentMethod[];\n\n /**\n * List of all stored payment methods.\n */\n storedPaymentMethods?: AdyenStoredPaymentMethod[];\n}\n\nexport interface RecurringDetail extends PaymentMethod {\n /**\n * The reference that uniquely identifies the recurring detail.\n */\n recurringDetailReference?: string;\n\n /**\n * Contains information on previously stored payment details.\n */\n storedDetails?: StoredDetails;\n}\n\nexport interface SepaPlaceHolder {\n ownerName?: string;\n ibanNumber?: string;\n}\n\nexport interface StoredDetails {\n /**\n * The stored bank account.\n */\n bank?: Bank;\n\n /**\n * The stored card information.\n */\n card?: Card;\n\n /**\n * The email associated with stored payment details.\n */\n emailAddress?: string;\n}\n\nexport interface StyleOptions {\n /**\n * Base styling applied to the iframe. All styling extends from this style.\n */\n base?: CssProperties;\n\n /**\n * Styling applied when a field fails validation.\n */\n error?: CssProperties;\n\n /**\n * Styling applied to the field's placeholder values.\n */\n placeholder?: CssProperties;\n\n /**\n * Styling applied once a field passes validation.\n */\n validated?: CssProperties;\n}\n\nexport interface SubInputDetail {\n /**\n * Configuration parameters for the required input.\n */\n configuration?: object;\n\n /**\n * In case of a select, the items to choose from.\n */\n items?: Item[];\n\n /**\n * The value to provide in the result.\n */\n key?: string;\n\n /**\n * True if this input is optional to provide.\n */\n optional?: boolean;\n\n /**\n * The type of the required input.\n */\n type?: string;\n\n /**\n * The value can be pre-filled, if available.\n */\n value?: string;\n}\n\nexport interface ThreeDS2ChallengeComponentOptions {\n size?: string;\n onAdditionalDetails?(state: AdyenAdditionalActionState, component?: AdyenComponent): void;\n onError(error: AdyenError): void;\n}\n\nexport interface ThreeDS2DeviceFingerprintComponentOptions {\n onAdditionalDetails?(state: AdyenAdditionalActionState, component?: AdyenComponent): void;\n onError(error: AdyenError): void;\n}\n\nexport type AdyenComponentState = CardState | WechatState;\n\nexport interface AdyenV2ValidationState {\n valid: boolean;\n fieldType?: AdyenV2CardFields;\n endDigits?: string;\n encryptedFieldName?: string;\n i18n?: string;\n error?: string;\n errorKey?: string;\n}\n\nexport enum AdyenV2CardFields {\n CardNumber = 'encryptedCardNumber',\n SecurityCode = 'encryptedSecurityCode',\n ExpiryDate = 'encryptedExpiryDate',\n}\n\nexport type AdyenComponentOptions =\n | AdyenCreditCardComponentOptions\n | AdyenIdealComponentOptions\n | AdyenCustomCardComponentOptions;\n\nexport function isCardState(param: any): param is CardState {\n return (\n (param && typeof param.data.paymentMethod.encryptedSecurityCode === 'string') ||\n typeof param.data.paymentMethod.encryptedExpiryMonth === 'string'\n );\n}\n\nexport function isAccountState(param: any): param is AccountState {\n const bankSupported = ['ideal', 'sepadirectdebit', 'directEbanking', 'giropay'];\n\n return bankSupported.indexOf(param.data.paymentMethod.type) !== -1;\n}\n\nexport interface AdyenPaymentMethodInitializationData {\n originKey?: string;\n clientKey?: string;\n environment?: string;\n paymentMethodsResponse?: PaymentMethodsResponse;\n prefillCardHolderName?: boolean;\n}\n","import { some } from 'lodash';\n\nimport {\n BillingAddress,\n getBrowserInfo,\n HostedInstrument,\n InvalidArgumentError,\n isRequestError,\n isVaultedInstrument,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n PaymentMethod,\n PaymentMethodCancelledError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n AdyenAction,\n AdyenActionType,\n AdyenAdditionalAction,\n AdyenAdditionalActionState,\n AdyenClient,\n AdyenComponent,\n AdyenComponentState,\n AdyenComponentType,\n AdyenError,\n AdyenPaymentMethodInitializationData,\n AdyenPaymentMethodType,\n AdyenPlaceholderData,\n CardStateErrors,\n isAccountState,\n isCardState,\n} from './adyenv2';\nimport AdyenV2PaymentInitializeOptions, {\n WithAdyenV2PaymentInitializeOptions,\n} from './adyenv2-initialize-options';\nimport AdyenV2ScriptLoader from './adyenv2-script-loader';\n\nexport default class AdyenV2PaymentStrategy implements PaymentStrategy {\n private _adyenClient?: AdyenClient;\n private _cardVerificationComponent?: AdyenComponent;\n private _componentState?: AdyenComponentState;\n private _paymentComponent?: AdyenComponent;\n private _paymentInitializeOptions?: AdyenV2PaymentInitializeOptions;\n\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _scriptLoader: AdyenV2ScriptLoader,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithAdyenV2PaymentInitializeOptions,\n ): Promise {\n const { adyenv2 } = options;\n\n if (!adyenv2) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.adyenv2\" argument is not provided.',\n );\n }\n\n this._paymentInitializeOptions = adyenv2;\n\n const paymentMethod = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(options.methodId);\n const { originKey, clientKey, environment, paymentMethodsResponse } =\n paymentMethod.initializationData || {};\n const clientSideAuthentication = {\n key: '',\n value: '',\n };\n\n if (originKey) {\n clientSideAuthentication.key = 'originKey';\n clientSideAuthentication.value = originKey;\n } else {\n clientSideAuthentication.key = 'clientKey';\n clientSideAuthentication.value = clientKey || '';\n }\n\n this._adyenClient = await this._scriptLoader.load({\n environment,\n locale: this._paymentIntegrationService.getState().getLocale(),\n [clientSideAuthentication.key]: clientSideAuthentication.value,\n paymentMethodsResponse,\n translations: {\n es: { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-AR': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-ES': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-MX': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-CL': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-CO': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-PE': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n },\n });\n\n this._paymentComponent = await this._mountPaymentComponent(paymentMethod);\n\n if (\n paymentMethod.method === AdyenPaymentMethodType.CreditCard ||\n paymentMethod.method === AdyenPaymentMethodType.Bancontact\n ) {\n this._cardVerificationComponent = await this._mountCardVerificationComponent();\n }\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment && payment.paymentData;\n const shouldSaveInstrument =\n paymentData && (paymentData as HostedInstrument).shouldSaveInstrument;\n const shouldSetAsDefaultInstrument =\n paymentData && (paymentData as HostedInstrument).shouldSetAsDefaultInstrument;\n\n if (!payment) {\n return Promise.reject(new PaymentArgumentInvalidError(['payment']));\n }\n\n this._validateCardData();\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n const componentState = this._componentState;\n\n if (!componentState) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (paymentData && isVaultedInstrument(paymentData)) {\n let bigpayToken = {};\n\n if (isCardState(componentState)) {\n const {\n encryptedCardNumber,\n encryptedSecurityCode,\n encryptedExpiryMonth,\n encryptedExpiryYear,\n } = componentState.data.paymentMethod;\n\n bigpayToken = {\n credit_card_number_confirmation: encryptedCardNumber,\n expiry_month: encryptedExpiryMonth,\n expiry_year: encryptedExpiryYear,\n verification_value: encryptedSecurityCode,\n };\n }\n\n if (isCardState(componentState) || isAccountState(componentState)) {\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n formattedPayload: {\n bigpay_token: {\n ...bigpayToken,\n token: paymentData.instrumentId,\n },\n origin: window.location.origin,\n browser_info: getBrowserInfo(),\n set_as_default_stored_instrument:\n shouldSetAsDefaultInstrument || null,\n },\n },\n });\n\n return;\n } catch (error) {\n await this._processAdditionalAction(\n error,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n\n return;\n }\n }\n }\n\n try {\n await this._paymentIntegrationService.submitPayment({\n methodId: payment.methodId,\n paymentData: {\n formattedPayload: {\n credit_card_token: {\n token: JSON.stringify({\n ...componentState.data.paymentMethod,\n origin: window.location.origin,\n }),\n },\n browser_info: getBrowserInfo(),\n vault_payment_instrument: shouldSaveInstrument || null,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n },\n },\n });\n } catch (error) {\n await this._processAdditionalAction(\n error,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this._componentState = undefined;\n\n if (this._paymentComponent) {\n this._paymentComponent.unmount();\n this._paymentComponent = undefined;\n }\n\n if (this._cardVerificationComponent) {\n this._cardVerificationComponent.unmount();\n this._cardVerificationComponent = undefined;\n }\n\n return Promise.resolve();\n }\n\n private _getAdyenClient(): AdyenClient {\n if (!this._adyenClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._adyenClient;\n }\n\n private _getPaymentInitializeOptions(): AdyenV2PaymentInitializeOptions {\n if (!this._paymentInitializeOptions) {\n throw new InvalidArgumentError(\n '\"options.adyenv2\" argument was not provided during initialization.',\n );\n }\n\n return this._paymentInitializeOptions;\n }\n\n private _getThreeDS2ChallengeWidgetSize(): string {\n const { additionalActionOptions, threeDS2Options } = this._getPaymentInitializeOptions();\n const widgetSize = additionalActionOptions.widgetSize || threeDS2Options?.widgetSize;\n\n if (!widgetSize) {\n return '05';\n }\n\n return widgetSize;\n }\n\n private _handleAction(additionalAction: AdyenAdditionalAction): Promise {\n return new Promise((resolve, reject) => {\n const { threeDS2ContainerId, additionalActionOptions } =\n this._getPaymentInitializeOptions();\n const { onBeforeLoad, containerId, onLoad, onComplete } = additionalActionOptions;\n const adyenAction: AdyenAction = JSON.parse(additionalAction.action);\n\n const additionalActionComponent = this._getAdyenClient().createFromAction(adyenAction, {\n onAdditionalDetails: (additionalActionState: AdyenAdditionalActionState) => {\n const paymentPayload = {\n methodId: adyenAction.paymentMethodType,\n paymentData: {\n nonce: JSON.stringify(additionalActionState.data),\n },\n };\n\n if (onComplete) {\n onComplete();\n }\n\n resolve(paymentPayload);\n },\n size: this._getThreeDS2ChallengeWidgetSize(),\n onError: (error: AdyenError) => reject(error),\n });\n\n if (onBeforeLoad) {\n onBeforeLoad(\n adyenAction.type === AdyenActionType.ThreeDS2Challenge ||\n adyenAction.type === AdyenActionType.QRCode,\n );\n }\n\n additionalActionComponent.mount(`#${containerId || threeDS2ContainerId}`);\n\n if (onLoad) {\n onLoad(() => {\n reject(new PaymentMethodCancelledError());\n additionalActionComponent.unmount();\n });\n }\n });\n }\n\n private _mapAdyenPlaceholderData(\n billingAddress?: BillingAddress,\n prefillCardHolderName?: boolean,\n ): AdyenPlaceholderData {\n if (!billingAddress) {\n return {};\n }\n\n const {\n firstName,\n lastName,\n address1: street,\n address2: houseNumberOrName,\n postalCode,\n city,\n stateOrProvinceCode: stateOrProvince,\n countryCode: country,\n } = billingAddress;\n\n return {\n holderName: prefillCardHolderName ? `${firstName} ${lastName}` : '',\n billingAddress: {\n street,\n houseNumberOrName,\n postalCode,\n city,\n stateOrProvince,\n country,\n },\n };\n }\n\n private _mountCardVerificationComponent(): Promise {\n const adyenv2 = this._getPaymentInitializeOptions();\n const adyenClient = this._getAdyenClient();\n let cardVerificationComponent: AdyenComponent;\n\n return new Promise((resolve, reject) => {\n if (adyenv2.cardVerificationContainerId) {\n cardVerificationComponent = adyenClient.create(AdyenComponentType.SecuredFields, {\n ...adyenv2.options,\n styles: {\n ...adyenv2.options?.styles,\n placeholder: {\n color: 'transparent',\n caretColor: '#000',\n ...adyenv2.options?.styles?.placeholder,\n },\n },\n onChange: (componentState) => this._updateComponentState(componentState),\n onError: (validateState) => adyenv2.validateCardFields(validateState),\n onFieldValid: (validateState) => adyenv2.validateCardFields(validateState),\n });\n\n try {\n cardVerificationComponent.mount(`#${adyenv2.cardVerificationContainerId}`);\n } catch (error) {\n reject(new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized));\n }\n }\n\n resolve(cardVerificationComponent);\n });\n }\n\n private _mountPaymentComponent(paymentMethod: PaymentMethod): Promise {\n let paymentComponent: AdyenComponent;\n const adyenv2 = this._getPaymentInitializeOptions();\n const adyenClient = this._getAdyenClient();\n\n return new Promise((resolve, reject) => {\n switch (paymentMethod.method) {\n case AdyenPaymentMethodType.CreditCard:\n case AdyenPaymentMethodType.ACH:\n case AdyenPaymentMethodType.Bancontact: {\n const billingAddress = this._paymentIntegrationService\n .getState()\n .getBillingAddress();\n const { prefillCardHolderName } = paymentMethod.initializationData;\n paymentComponent = adyenClient.create(paymentMethod.method, {\n ...adyenv2.options,\n onChange: (componentState) => this._updateComponentState(componentState),\n data: this._mapAdyenPlaceholderData(billingAddress, prefillCardHolderName),\n });\n\n try {\n paymentComponent.mount(`#${adyenv2.containerId}`);\n } catch (error) {\n reject(\n new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n break;\n }\n\n case AdyenPaymentMethodType.IDEAL:\n case AdyenPaymentMethodType.SEPA:\n if (!adyenv2.hasVaultedInstruments) {\n paymentComponent = adyenClient.create(paymentMethod.method, {\n ...adyenv2.options,\n onChange: (componentState) =>\n this._updateComponentState(componentState),\n });\n\n try {\n paymentComponent.mount(`#${adyenv2.containerId}`);\n } catch (error) {\n reject(\n new NotInitializedError(\n NotInitializedErrorType.PaymentNotInitialized,\n ),\n );\n }\n } else {\n this._updateComponentState({\n data: {\n paymentMethod: {\n type: paymentMethod.method,\n },\n },\n });\n }\n\n break;\n\n case AdyenPaymentMethodType.AliPay:\n case AdyenPaymentMethodType.GiroPay:\n case AdyenPaymentMethodType.Sofort:\n case AdyenPaymentMethodType.Klarna:\n case AdyenPaymentMethodType.KlarnaPayNow:\n case AdyenPaymentMethodType.KlarnaAccount:\n case AdyenPaymentMethodType.Vipps:\n case AdyenPaymentMethodType.WeChatPayQR:\n this._updateComponentState({\n data: {\n paymentMethod: {\n type: paymentMethod.method,\n },\n },\n });\n }\n\n resolve(paymentComponent);\n });\n }\n\n private async _processAdditionalAction(\n error: unknown,\n shouldSaveInstrument?: boolean,\n shouldSetAsDefaultInstrument?: boolean,\n ): Promise {\n if (\n !isRequestError(error) ||\n !some(error.body.errors, { code: 'additional_action_required' })\n ) {\n throw error;\n }\n\n const payment = await this._handleAction(error.body.provider_data);\n\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n ...payment.paymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n },\n });\n } catch (paymentError) {\n return this._processAdditionalAction(\n paymentError,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n private _updateComponentState(componentState: AdyenComponentState) {\n this._componentState = componentState;\n }\n\n private _validateCardData(): void {\n const adyenv2 = this._getPaymentInitializeOptions();\n const cardComponent = adyenv2.hasVaultedInstruments\n ? this._cardVerificationComponent\n : this._paymentComponent;\n\n if (!cardComponent?.componentRef?.showValidation || !cardComponent.state) {\n return;\n }\n\n cardComponent.componentRef.showValidation();\n\n /**\n * For some reason adyen sdk doesn't return isValid for payment methods with select field in form(iDeal for example)\n * so we need to check state issuer field\n */\n if (\n Object.keys(cardComponent.state).length === 0 ||\n (!cardComponent.state.isValid && !cardComponent.state.issuer)\n ) {\n throw new PaymentInvalidFormError(this._mapCardErrors(cardComponent.state.errors));\n }\n }\n\n private _mapCardErrors(cardStateErrors: CardStateErrors = {}): PaymentInvalidFormErrorDetails {\n const errors: PaymentInvalidFormErrorDetails = {};\n\n Object.keys(cardStateErrors).forEach((key) => {\n errors[key] = [\n {\n message: cardStateErrors[key],\n type: key,\n },\n ];\n });\n\n return errors;\n }\n}\n","import { ScriptLoader, StylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { AdyenClient, AdyenConfiguration, AdyenHostWindow } from './adyenv2';\n\nexport default class AdyenV2ScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _stylesheetLoader: StylesheetLoader,\n private _window: AdyenHostWindow = window,\n ) {}\n\n async load(configuration: AdyenConfiguration): Promise {\n await Promise.all([\n this._stylesheetLoader.loadStylesheet(\n `https://checkoutshopper-${\n configuration.environment ?? ''\n }.adyen.com/checkoutshopper/sdk/3.10.1/adyen.css`,\n ),\n this._scriptLoader.loadScript(\n `https://checkoutshopper-${\n configuration.environment ?? ''\n }.adyen.com/checkoutshopper/sdk/3.10.1/adyen.js`,\n ),\n ]);\n\n if (!this._window.AdyenCheckout) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return new this._window.AdyenCheckout(configuration);\n }\n}\n","import { getScriptLoader, getStylesheetLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport AdyenV2PaymentStrategy from './adyenv2-payment-strategy';\nimport AdyenV2ScriptLoader from './adyenv2-script-loader';\n\nconst createAdyenV2PaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new AdyenV2PaymentStrategy(\n paymentIntegrationService,\n new AdyenV2ScriptLoader(getScriptLoader(), getStylesheetLoader()),\n );\n};\n\nexport default toResolvableModule(createAdyenV2PaymentStrategy, [{ gateway: 'adyenv2' }]);\n","import { HostedInstrument } from './payment';\n\nexport default function isHostedInstrumentLike(\n instrument: unknown,\n): instrument is HostedInstrument {\n return (\n typeof instrument === 'object' &&\n instrument !== null &&\n (typeof (instrument as HostedInstrument).shouldSaveInstrument === 'undefined' ||\n typeof (instrument as HostedInstrument).shouldSaveInstrument === 'boolean') &&\n (typeof (instrument as HostedInstrument).shouldSetAsDefaultInstrument === 'undefined' ||\n typeof (instrument as HostedInstrument).shouldSetAsDefaultInstrument === 'boolean')\n );\n}\n","export enum AdyenActionType {\n /*\n * The payment qualifies for 3D Secure 2, and will go through either the frictionless\n * or the challenge flow.\n * */\n ThreeDS2Fingerprint = 'threeDS2Fingerprint',\n\n /*\n * The payment qualifies for 3D Secure 2, and the issuer is initiating a challenge flow.\n * */\n ThreeDS2 = 'threeDS2',\n\n /*\n * We will initiate a 3D Secure 1 fallback, because the issuer does not support 3D Secure 2.\n * */\n Redirect = 'redirect',\n\n /*\n * The Component presents the QR code and calls the onAdditionalDetails event.\n * */\n QRCode = 'qrCode',\n\n /*\n * The Component displays the voucher which the shopper uses to complete the payment.\n * */\n Voucher = 'voucher',\n\n /*\n * The Component displays the widget which the shopper uses to complete the payment.\n * */\n Sdk = 'sdk',\n}\n\nexport enum AdyenComponentType {\n SecuredFields = 'securedfields',\n}\n\nexport enum AdyenPaymentMethodType {\n ACH = 'ach',\n AliPay = 'alipay',\n Bancontact = 'bcmc',\n CreditCard = 'scheme',\n Klarna = 'klarna',\n KlarnaPayNow = 'klarna_paynow',\n KlarnaAccount = 'klarna_account',\n IDEAL = 'ideal',\n GiroPay = 'giropay',\n GooglePay = 'paywithgoogle',\n SEPA = 'sepadirectdebit',\n Sofort = 'directEbanking',\n Vipps = 'vipps',\n WeChatPayQR = 'wechatpayQR',\n}\n\nexport enum HTTPMethod {\n POST = 'POST',\n}\n\nexport enum ResultCode {\n ChallengeShopper = 'ChallengeShopper',\n Error = 'Error',\n IdentifyShopper = 'IdentifyShopper',\n}\n\ninterface AdyenPaymentMethodState {\n type: string;\n}\n\ninterface WechatDataPaymentMethodState {\n paymentMethod: AdyenPaymentMethodState;\n}\n\ninterface CardPaymentMethodState {\n encryptedCardNumber: string;\n encryptedExpiryMonth: string;\n encryptedExpiryYear: string;\n encryptedSecurityCode: string;\n holderName: string;\n}\n\nexport interface AdyenAction {\n method: HTTPMethod;\n\n /**\n * Value that you need to submit in your /payments/details request when handling\n * the redirect.\n */\n paymentData: string;\n\n paymentMethodType: AdyenPaymentMethodType;\n\n /*\n * The Component performs additional front-end actions depending on the action.type.\n * Your next steps depend on the type of action that the Component performs.\n */\n type: AdyenActionType;\n\n /**\n * The HTTP request method that you should use. After the shopper completes the payment,\n * they will be redirected back to your returnURL using the same method.\n */\n url: string;\n}\n\nexport interface AdyenAdditionalAction {\n resultCode: ResultCode;\n action: string;\n}\n\nexport interface AdyenAdditionalActionCallbacks {\n /**\n * A callback that gets called before adyen component is loaded\n */\n onBeforeLoad?(shopperInteraction?: boolean): void;\n\n /**\n * A callback that gets called when adyen component is loaded\n */\n onLoad?(cancel?: () => void): void;\n\n /**\n * A callback that gets called when adyen component verification\n * is completed\n */\n onComplete?(): void;\n}\n\nexport interface AdyenAdditionalActionErrorResponse {\n provider_data: AdyenAdditionalAction;\n errors: [\n {\n code: string;\n },\n ];\n}\n\nexport interface AdyenAdditionalActionOptions extends AdyenAdditionalActionCallbacks {\n /**\n * The location to insert the additional action component.\n */\n containerId: string;\n\n /**\n * Specify Three3DS2Challenge Widget Size\n *\n * Values\n * '01' = 250px x 400px\n * '02' = 390px x 400px\n * '03' = 500px x 600px\n * '04' = 600px x 400px\n * '05' = 100% x 100%\n */\n widgetSize?: string;\n}\n\nexport interface AdyenAdditionalActionState {\n data: AdyenAdditionalAction;\n isValid?: boolean;\n}\n\nexport interface AdyenBaseCardComponentOptions {\n /**\n * Array of card brands that will be recognized by the component.\n *\n */\n brands?: string[];\n\n /**\n * Set a style object to customize the input fields. See Styling Secured Fields\n * for a list of supported properties.\n */\n styles?: StyleOptions;\n\n showBrandsUnderCardNumber?: boolean;\n}\n\nexport interface AdyenComponentEvents {\n /**\n * Called when the shopper enters data in the card input fields.\n * Here you have the option to override your main Adyen Checkout configuration.\n */\n onChange?(state: AdyenV3ComponentState, component: AdyenComponent): void;\n\n /**\n * Called when the shopper selects the Pay button and payment details are valid.\n */\n onSubmit?(state: AdyenV3ComponentState, component: AdyenComponent): void;\n\n /**\n * Called in case of an invalid card number, invalid expiry date, or\n * incomplete field. Called again when errors are cleared.\n */\n onError?(state: AdyenV3ValidationState, component: AdyenComponent): void;\n\n onFieldValid?(state: AdyenV3ValidationState, component: AdyenComponent): void;\n}\n\nexport interface AdyenClient {\n create(type: string, componentOptions?: AdyenComponentOptions): AdyenComponent;\n\n createFromAction(\n action: AdyenAction,\n componentOptions?:\n | ThreeDS2DeviceFingerprintComponentOptions\n | ThreeDS2ChallengeComponentOptions,\n ): AdyenComponent;\n}\n\nexport interface AdyenComponent {\n componentRef?: {\n showValidation(): void;\n };\n props?: {\n type?: string;\n };\n state?: CardState;\n mount(containerId: string): HTMLElement;\n unmount(): void;\n submit(): void;\n}\n\nexport interface AdyenConfiguration {\n /*\n * Use test, and then change this to live when you're ready to accept live payments.\n */\n environment?: string;\n\n /*\n * The shopper's locale. This is used to set the language rendered in the Components.\n */\n locale?: string;\n\n /*\n * The Origin Key of your website.\n */\n originKey?: string;\n\n /*\n * The Client Key of your Adyen account.\n */\n clientKey?: string;\n\n /*\n * Supported from Components version 3.0.0 and later. The full paymentMethods response,\n * returned in step 1. We recommend that you pass this on the AdyenCheckout instance.\n * Otherwise, you need to pass the specific payment method details separately for each\n * Component.\n */\n paymentMethodsResponse?: PaymentMethodsResponse;\n\n /**\n * Configuration for specific payment methods.\n */\n paymentMethodsConfiguration: {\n klarna: {\n useKlarnaWidget: boolean;\n };\n klarna_account: {\n useKlarnaWidget: boolean;\n };\n klarna_paynow: {\n useKlarnaWidget: boolean;\n };\n };\n\n showPayButton?: boolean;\n\n /**\n * If your shoppers use a language that isn't supported by the Components, you can create your own localization.\n * To create a localization:\n * Add a translations object to your payment page, specifying:\n * The localization you want to create.\n * An object containing the fields that are used in the Components, as well as the text you want displayed for each field.\n *\n * \"en\": {\n * \"paymentMethods.moreMethodsButton\": \"More payment methods\",\n * \"payButton\": \"Pay\",\n * \"storeDetails\": \"Save for my next payment\",\n * ...\n * }\n */\n translations?: {\n [index: string]: {\n [index: string]: string;\n };\n };\n\n /*\n * Specify the function that you created, for example, handleOnChange. If you wish\n * to override this function, you can also define an onChange event on the Component\n * level.\n */\n onChange?(state: CardState, component?: AdyenComponent): void;\n\n onAdditionalDetails?(state: CardState, component?: AdyenComponent): void;\n}\n\nexport interface AdyenPlaceholderData {\n holderName?: string;\n prefillCardHolderName?: boolean;\n billingAddress?: {\n street: string;\n houseNumberOrName: string;\n postalCode: string;\n city: string;\n stateOrProvince: string;\n country: string;\n };\n}\n\nexport interface AdyenV3CreditCardComponentOptions\n extends AdyenBaseCardComponentOptions,\n AdyenComponentEvents {\n /**\n * Set an object containing the details array for type: scheme from\n * the /paymentMethods response.\n */\n details?: InputDetail[];\n\n /**\n * Set to true to show the checkbox to save card details for the next payment.\n */\n enableStoreDetails?: boolean;\n\n /**\n * Set to true to request the name of the card holder.\n */\n hasHolderName?: boolean;\n\n /**\n * Set to true to require the card holder name.\n */\n holderNameRequired?: boolean;\n\n /**\n * Information to prefill fields.\n */\n data?: AdyenPlaceholderData;\n\n /**\n * Defaults to ['mc','visa','amex']. Configure supported card types to\n * facilitate brand recognition used in the Secured Fields onBrand callback.\n * See list of available card types. If a shopper enters a card type not\n * specified in the GroupTypes configuration, the onBrand callback will not be invoked.\n */\n groupTypes?: string[];\n\n /**\n * Specify the sample values you want to appear for card detail input fields.\n */\n placeholders?: CreditCardPlaceHolder | SepaPlaceHolder;\n}\n\nexport interface AdyenCustomCardComponentOptions\n extends AdyenBaseCardComponentOptions,\n AdyenComponentEvents {\n /**\n * Specify aria attributes for the input fields for web accessibility.\n */\n ariaLabels?: CustomCardAriaLabels;\n\n /**\n * Automatically shift the focus from date field to the CVC field.\n */\n autofocus?: boolean;\n}\n\nexport interface AdyenError {\n errorCode: string;\n message: string;\n}\n\ntype AdyenClientConstructor = (configuration: AdyenConfiguration) => Promise;\n\nexport interface AdyenHostWindow extends Window {\n AdyenCheckout?: AdyenClientConstructor;\n}\nexport interface AdyenV3IdealComponentOptions {\n /**\n * Optional. Set to **false** to remove the bank logos from the iDEAL form.\n */\n showImage?: boolean;\n}\n\nexport interface AdyenStoredPaymentMethod {\n /**\n * The brand of the card.\n */\n brand?: string;\n\n /**\n * The month the card expires.\n */\n expiryMonth?: string;\n\n /**\n * The year the card expires.\n */\n expiryYear?: string;\n\n /**\n * The unique payment method code.\n */\n holderName?: string;\n\n /**\n * A unique identifier of this stored payment method.\n */\n id?: string;\n\n /**\n * The last four digits of the PAN.\n */\n lastFour?: string;\n\n /**\n * The display name of the stored payment method.\n */\n name: string;\n\n /**\n * The shopper’s email address.\n */\n shopperEmail?: string;\n\n /**\n * The supported shopper interactions for this stored payment method.\n */\n supportedShopperInteractions?: string[];\n\n /**\n * The type of payment method.\n */\n type?: string;\n}\n\nexport interface Bank {\n /**\n * The bank account number (without separators).\n */\n bankAccountNumber?: string;\n\n /**\n * The bank city.\n */\n bankCity?: string;\n\n /**\n * The location id of the bank. The field value is nil in most cases.\n */\n bankLocationId?: string;\n\n /**\n * The name of the bank.\n */\n bankName?: string;\n\n /**\n * The Business Identifier Code (BIC) is the SWIFT address assigned to\n * a bank. The field value is nil in most cases.\n */\n bic?: string;\n\n /**\n * Country code where the bank is located.\n * A valid value is an ISO two-character country code (e.g. 'NL').\n */\n countryCode?: string;\n\n /**\n * The International Bank Account Number (IBAN).\n */\n iban?: string;\n\n /**\n * The name of the bank account holder. If you submit a name with non-Latin\n * characters, we automatically replace some of them with corresponding Latin\n * characters to meet the FATF recommendations. For example:\n * χ12 is converted to ch12.\n * üA is converted to euA.\n * Peter Møller is converted to Peter Mller, because banks don't accept 'ø'.\n * After replacement, the ownerName must have at least three alphanumeric characters\n * (A-Z, a-z, 0-9), and at least one of them must be a valid Latin character\n * (A-Z, a-z). For example:\n * John17 - allowed.\n * J17 - allowed.\n * 171 - not allowed.\n * John-7 - allowed.\n */\n ownerName?: string;\n\n /**\n * The bank account holder's tax ID.\n */\n taxId?: string;\n}\n\nexport interface Card {\n /**\n * The card verification code (1-20 characters). Depending on the card brand, it\n * is known also as:\n * CVv3/CVC2 – length: 3 digits\n * CID – length: 4 digits\n */\n cvc?: string;\n\n /**\n * The card expiry month. Format: 2 digits, zero-padded for single digits. For example:\n * 03 = March\n * 11 = November\n * Required\n */\n expiryMonth: string;\n\n /**\n * The card expiry year. Format: 4 digits. For example: 2020\n * Required\n */\n expiryYear: string;\n\n /**\n * The name of the cardholder, as printed on the card.\n * Required\n */\n holderName: string;\n\n /**\n * The issue number of the card (for some UK debit cards only).\n */\n issueNumber?: string;\n\n /**\n * The card number (4-19 characters). Do not use any separators. When this value is\n * returned in a response, only the last 4 digits of the card number are returned.\n * Required\n */\n number: string;\n\n /**\n * The month component of the start date (for some UK debit cards only).\n */\n startNumber?: string;\n\n /**\n * The year component of the start date (for some UK debit cards only).\n */\n startYear?: string;\n}\n\nexport interface CardState {\n data: CardDataPaymentMethodState;\n isValid?: boolean;\n valid?: { [key: string]: boolean };\n errors?: CardStateErrors;\n}\n\ninterface CardDataPaymentMethodState {\n paymentMethod: CardPaymentMethodState;\n}\n\nexport interface CardStateErrors {\n [key: string]: string;\n}\n\nexport interface WechatState {\n data: WechatDataPaymentMethodState;\n}\n\nexport interface CreditCardPlaceHolder {\n encryptedCardNumber?: string;\n encryptedExpiryDate?: string;\n encryptedSecurityCode: string;\n}\n\ninterface AccountDataPaymentMethodState {\n paymentMethod: AdyenPaymentMethodState;\n}\n\nexport interface AccountState {\n data: AccountDataPaymentMethodState;\n}\n\nexport interface CssProperties {\n background?: string;\n caretColor?: string;\n color?: string;\n display?: string;\n font?: string;\n fontFamily?: string;\n fontSize?: string;\n fontSizeAdjust?: string;\n fontSmoothing?: string;\n fontStretch?: string;\n fontStyle?: string;\n fontVariant?: string;\n fontVariantAlternates?: string;\n fontVariantCaps?: string;\n fontVariantEastAsian?: string;\n fontVariantLigatures?: string;\n fontVariantNumeric?: string;\n fontWeight?: string;\n letterSpacing?: string;\n lineHeight?: string;\n mozOsxFontSmoothing?: string;\n mozTransition?: string;\n outline?: string;\n opacity?: string | number;\n padding?: string;\n textAlign?: string;\n textShadow?: string;\n transition?: string;\n webkitFontSmoothing?: string;\n webkitTransition?: string;\n}\n\nexport interface CustomCardAriaLabel {\n label?: string;\n iframeTitle?: string;\n}\n\nexport interface CustomCardAriaLabels {\n lang?: string;\n encryptedCardNumber?: CustomCardAriaLabel;\n encryptedExpiryDate?: CustomCardAriaLabel;\n encryptedSecurityCode?: CustomCardAriaLabel;\n}\n\nexport interface Group {\n /**\n * The name of the group.\n */\n name?: string;\n\n /**\n * Echo data to be used if the payment method is displayed as part of this group.\n */\n paymentMethodData?: string;\n\n /**\n * The unique code of the group.\n */\n type?: string;\n}\n\nexport interface InputDetail {\n /**\n * Configuration parameters for the required input.\n */\n configuration?: object;\n\n /**\n * Input details can also be provided recursively.\n */\n details?: SubInputDetail[];\n\n /**\n * In case of a select, the URL from which to query the items.\n */\n itemSearchUrl?: string;\n\n /**\n * In case of a select, the items to choose from.\n */\n items?: Item[];\n\n /**\n * The value to provide in the result.\n */\n key?: string;\n\n /**\n * True if this input value is optional.\n */\n optional?: boolean;\n\n /**\n * The type of the required input.\n */\n type?: string;\n\n /**\n * The value can be pre-filled, if available.\n */\n value?: string;\n}\n\nexport interface Item {\n /**\n * The value to provide in the result.\n */\n id?: string;\n\n /**\n * The display name.\n */\n name?: string;\n}\n\nexport interface PaymentMethod {\n /**\n * List of possible brands. For example: visa, mc.\n */\n brands?: string[];\n\n /**\n * The configuration of the payment method.\n */\n configuration?: object;\n\n /**\n * All input details to be provided to complete the payment with this payment\n * method.\n */\n details?: InputDetail[];\n\n /**\n * The group where this payment method belongs to.\n */\n group?: Group;\n\n /**\n * The displayable name of this payment method.\n */\n name?: string;\n\n /**\n * Echo data required to send in next calls.\n */\n paymentMethodData?: string;\n\n /**\n * Indicates whether this payment method supports tokenization or not.\n */\n supportsRecurring?: boolean;\n\n /**\n * The unique payment method code.\n */\n type?: string;\n}\n\nexport interface PaymentMethodGroup {\n /**\n * The type to submit for any payment method in this group.\n */\n groupType?: string;\n\n /**\n * The human-readable name of this group.\n */\n name?: string;\n\n /**\n * The types of payment methods that belong in this group.\n */\n types?: string[];\n}\n\nexport interface PaymentMethodsResponse {\n /**\n * Groups of payment methods.\n */\n groups?: PaymentMethodGroup[];\n\n /**\n * Detailed list of one-click payment methods.\n */\n oneClickPaymentMethods?: RecurringDetail;\n\n /**\n * Detailed list of payment methods required to generate payment forms.\n */\n paymentMethods?: PaymentMethod[];\n\n /**\n * List of all stored payment methods.\n */\n storedPaymentMethods?: AdyenStoredPaymentMethod[];\n}\n\nexport interface RecurringDetail extends PaymentMethod {\n /**\n * The reference that uniquely identifies the recurring detail.\n */\n recurringDetailReference?: string;\n\n /**\n * Contains information on previously stored payment details.\n */\n storedDetails?: StoredDetails;\n}\n\nexport interface SepaPlaceHolder {\n ownerName?: string;\n ibanNumber?: string;\n}\n\nexport interface StoredDetails {\n /**\n * The stored bank account.\n */\n bank?: Bank;\n\n /**\n * The stored card information.\n */\n card?: Card;\n\n /**\n * The email associated with stored payment details.\n */\n emailAddress?: string;\n}\n\nexport interface StyleOptions {\n /**\n * Base styling applied to the iframe. All styling extends from this style.\n */\n base?: CssProperties;\n\n /**\n * Styling applied when a field fails validation.\n */\n error?: CssProperties;\n\n /**\n * Styling applied to the field's placeholder values.\n */\n placeholder?: CssProperties;\n\n /**\n * Styling applied once a field passes validation.\n */\n validated?: CssProperties;\n}\n\nexport interface SubInputDetail {\n /**\n * Configuration parameters for the required input.\n */\n configuration?: object;\n\n /**\n * In case of a select, the items to choose from.\n */\n items?: Item[];\n\n /**\n * The value to provide in the result.\n */\n key?: string;\n\n /**\n * True if this input is optional to provide.\n */\n optional?: boolean;\n\n /**\n * The type of the required input.\n */\n type?: string;\n\n /**\n * The value can be pre-filled, if available.\n */\n value?: string;\n}\n\nexport interface ThreeDS2ChallengeComponentOptions {\n challengeWindowSize?: string;\n onAdditionalDetails?(state: AdyenAdditionalActionState, component?: AdyenComponent): void;\n onError(error: AdyenError): void;\n}\n\nexport interface ThreeDS2DeviceFingerprintComponentOptions {\n onAdditionalDetails?(state: AdyenAdditionalActionState, component?: AdyenComponent): void;\n onError(error: AdyenError): void;\n}\n\nexport interface AdyenV3ValidationState {\n valid: boolean;\n fieldType?: AdyenV3CardFields;\n endDigits?: string;\n encryptedFieldName?: string;\n i18n?: string;\n error?: string;\n errorKey?: string;\n}\n\nexport enum AdyenV3CardFields {\n CardNumber = 'encryptedCardNumber',\n SecurityCode = 'encryptedSecurityCode',\n ExpiryDate = 'encryptedExpiryDate',\n}\n\nexport type AdyenV3ComponentState = CardState | WechatState;\n\nexport type AdyenComponentOptions =\n | AdyenV3CreditCardComponentOptions\n | AdyenV3IdealComponentOptions\n | AdyenCustomCardComponentOptions;\n\nexport function isCardState(param: unknown): param is CardState {\n return (\n (typeof param === 'object' &&\n !!param &&\n typeof (param as CardState).data.paymentMethod.encryptedSecurityCode === 'string') ||\n typeof (param as CardState).data.paymentMethod.encryptedExpiryMonth === 'string'\n );\n}\n\nexport interface AdyenPaymentMethodInitializationData {\n clientKey?: string;\n environment?: string;\n paymentMethodsResponse?: PaymentMethodsResponse;\n prefillCardHolderName?: boolean;\n}\n","import { some } from 'lodash';\n\nimport {\n BillingAddress,\n getBrowserInfo,\n InvalidArgumentError,\n isHostedInstrumentLike,\n isRequestError,\n isVaultedInstrument,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationSelectors,\n PaymentIntegrationService,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n PaymentMethod,\n PaymentMethodCancelledError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n AdyenAction,\n AdyenActionType,\n AdyenAdditionalAction,\n AdyenAdditionalActionState,\n AdyenClient,\n AdyenComponent,\n AdyenComponentType,\n AdyenError,\n AdyenPaymentMethodInitializationData,\n AdyenPaymentMethodType,\n AdyenPlaceholderData,\n AdyenV3ComponentState,\n CardStateErrors,\n isCardState,\n} from './adyenv3';\nimport AdyenV3PaymentInitializeOptions, {\n WithAdyenV3PaymentInitializeOptions,\n} from './adyenv3-initialize-options';\nimport AdyenV3ScriptLoader from './adyenv3-script-loader';\n\nexport default class Adyenv3PaymentStrategy implements PaymentStrategy {\n private _adyenClient?: AdyenClient;\n private _cardVerificationComponent?: AdyenComponent;\n private _componentState?: AdyenV3ComponentState;\n private _paymentComponent?: AdyenComponent;\n private _paymentInitializeOptions?: AdyenV3PaymentInitializeOptions;\n\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _scriptLoader: AdyenV3ScriptLoader,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithAdyenV3PaymentInitializeOptions,\n ): Promise {\n const { adyenv3 } = options;\n\n if (!adyenv3) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.adyenv3\" argument is not provided.',\n );\n }\n\n this._paymentInitializeOptions = adyenv3;\n\n const paymentMethod = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(options.methodId);\n const { environment, clientKey, paymentMethodsResponse } =\n paymentMethod.initializationData || {};\n\n this._adyenClient = await this._scriptLoader.load({\n paymentMethodsConfiguration: {\n klarna: {\n useKlarnaWidget: true,\n },\n klarna_account: {\n useKlarnaWidget: true,\n },\n klarna_paynow: {\n useKlarnaWidget: true,\n },\n },\n environment,\n locale: this._paymentIntegrationService.getState().getLocale(),\n clientKey,\n paymentMethodsResponse,\n showPayButton: false,\n translations: {\n es: { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-AR': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-ES': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-MX': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-CL': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-CO': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n 'es-PE': { 'creditCard.expiryDateField.title': 'Fecha de caducidad' },\n },\n });\n\n this._paymentComponent = await this._mountPaymentComponent(paymentMethod);\n\n if (\n paymentMethod.method === AdyenPaymentMethodType.CreditCard ||\n paymentMethod.method === AdyenPaymentMethodType.Bancontact\n ) {\n this._cardVerificationComponent = await this._mountCardVerificationComponent();\n }\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const paymentData = payment.paymentData;\n\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = isHostedInstrumentLike(\n paymentData,\n )\n ? paymentData\n : { shouldSaveInstrument: false, shouldSetAsDefaultInstrument: false };\n\n this._validateCardData();\n\n const componentState = this._componentState || {\n data: { paymentMethod: { type: payment.methodId } },\n };\n\n if (\n payment.methodId === 'klarna' ||\n payment.methodId === 'klarna_account' ||\n payment.methodId === 'klarna_paynow'\n ) {\n this._paymentComponent?.submit();\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n if (paymentData && isVaultedInstrument(paymentData)) {\n let bigpayToken = {};\n\n if (isCardState(componentState)) {\n const {\n encryptedCardNumber,\n encryptedSecurityCode,\n encryptedExpiryMonth,\n encryptedExpiryYear,\n } = componentState.data.paymentMethod;\n\n bigpayToken = {\n credit_card_number_confirmation: encryptedCardNumber,\n expiry_month: encryptedExpiryMonth,\n expiry_year: encryptedExpiryYear,\n verification_value: encryptedSecurityCode,\n };\n }\n\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n formattedPayload: {\n bigpay_token: {\n ...bigpayToken,\n token: paymentData.instrumentId,\n },\n origin: window.location.origin,\n browser_info: getBrowserInfo(),\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n },\n },\n });\n\n return;\n } catch (error) {\n await this._processAdditionalAction(\n error,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n\n return;\n }\n }\n\n try {\n await this._paymentIntegrationService.submitPayment({\n methodId: payment.methodId,\n paymentData: {\n formattedPayload: {\n credit_card_token: {\n token: JSON.stringify({\n ...componentState.data.paymentMethod,\n type: payment.methodId,\n origin: window.location.origin,\n }),\n },\n browser_info: getBrowserInfo(),\n vault_payment_instrument: shouldSaveInstrument || null,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n },\n },\n });\n } catch (error) {\n await this._processAdditionalAction(\n error,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this._componentState = undefined;\n\n if (this._paymentComponent) {\n this._paymentComponent.unmount();\n this._paymentComponent = undefined;\n }\n\n if (this._cardVerificationComponent) {\n this._cardVerificationComponent.unmount();\n this._cardVerificationComponent = undefined;\n }\n\n return Promise.resolve();\n }\n\n private _updateComponentState(componentState: AdyenV3ComponentState) {\n this._componentState = componentState;\n }\n\n private _getAdyenClient(): AdyenClient {\n if (!this._adyenClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._adyenClient;\n }\n\n private _getPaymentInitializeOptions(): AdyenV3PaymentInitializeOptions {\n if (!this._paymentInitializeOptions) {\n throw new InvalidArgumentError(\n '\"options.adyenv3\" argument was not provided during initialization.',\n );\n }\n\n return this._paymentInitializeOptions;\n }\n\n private _handleAction(additionalAction: AdyenAdditionalAction): Promise {\n return new Promise((resolve, reject) => {\n const { additionalActionOptions } = this._getPaymentInitializeOptions();\n const { onBeforeLoad, containerId, onLoad, onComplete, widgetSize } =\n additionalActionOptions;\n const adyenAction: AdyenAction = JSON.parse(additionalAction.action);\n\n const additionalActionComponent = this._getAdyenClient().createFromAction(adyenAction, {\n onAdditionalDetails: (additionalActionState: AdyenAdditionalActionState) => {\n const paymentPayload = {\n methodId: adyenAction.paymentMethodType,\n paymentData: {\n nonce: JSON.stringify(additionalActionState.data),\n },\n };\n\n if (onComplete) {\n onComplete();\n }\n\n resolve(paymentPayload);\n },\n challengeWindowSize: widgetSize || '05',\n onError: (error: AdyenError) => reject(error),\n });\n\n if (onBeforeLoad) {\n onBeforeLoad(\n adyenAction.type === AdyenActionType.ThreeDS2 ||\n adyenAction.type === AdyenActionType.QRCode ||\n adyenAction.type === AdyenActionType.Sdk,\n );\n }\n\n additionalActionComponent.mount(`#${containerId}`);\n\n if (onLoad) {\n onLoad(() => {\n reject(new PaymentMethodCancelledError());\n additionalActionComponent.unmount();\n });\n }\n });\n }\n\n private _mapAdyenPlaceholderData(\n billingAddress?: BillingAddress,\n prefillCardHolderName?: boolean,\n ): AdyenPlaceholderData {\n if (!billingAddress) {\n return {};\n }\n\n const {\n firstName,\n lastName,\n address1: street,\n address2: houseNumberOrName,\n postalCode,\n city,\n stateOrProvinceCode: stateOrProvince,\n countryCode: country,\n } = billingAddress;\n\n return {\n holderName: prefillCardHolderName ? `${firstName} ${lastName}` : '',\n billingAddress: {\n street,\n houseNumberOrName,\n postalCode,\n city,\n stateOrProvince,\n country,\n },\n };\n }\n\n private _mountCardVerificationComponent(): Promise {\n const adyenv3 = this._getPaymentInitializeOptions();\n const adyenClient = this._getAdyenClient();\n let cardVerificationComponent: AdyenComponent;\n\n return new Promise((resolve, reject) => {\n if (adyenv3.cardVerificationContainerId) {\n cardVerificationComponent = adyenClient.create(AdyenComponentType.SecuredFields, {\n ...adyenv3.options,\n styles: {\n ...adyenv3.options?.styles,\n placeholder: {\n color: 'transparent',\n caretColor: '#000',\n ...adyenv3.options?.styles?.placeholder,\n },\n },\n onChange: (componentState) => this._updateComponentState(componentState),\n onError: (validateState) => adyenv3.validateCardFields(validateState),\n onFieldValid: (validateState) => adyenv3.validateCardFields(validateState),\n });\n\n try {\n cardVerificationComponent.mount(`#${adyenv3.cardVerificationContainerId}`);\n } catch (error) {\n reject(new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized));\n }\n }\n\n resolve(cardVerificationComponent);\n });\n }\n\n private _mountPaymentComponent(paymentMethod: PaymentMethod): Promise {\n let paymentComponent: AdyenComponent;\n const adyenv3 = this._getPaymentInitializeOptions();\n const adyenClient = this._getAdyenClient();\n\n return new Promise((resolve, reject) => {\n const billingAddress = this._paymentIntegrationService.getState().getBillingAddress();\n\n const { prefillCardHolderName } = paymentMethod.initializationData;\n\n paymentComponent = adyenClient.create(paymentMethod.method, {\n ...adyenv3.options,\n showBrandsUnderCardNumber: false,\n onChange: (componentState) => this._updateComponentState(componentState),\n onSubmit: (componentState) => this._updateComponentState(componentState),\n ...(billingAddress\n ? { data: this._mapAdyenPlaceholderData(billingAddress, prefillCardHolderName) }\n : {}),\n });\n\n try {\n paymentComponent.mount(`#${adyenv3.containerId}`);\n } catch (error) {\n reject(new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized));\n }\n\n resolve(paymentComponent);\n });\n }\n\n private async _processAdditionalAction(\n error: unknown,\n shouldSaveInstrument?: boolean,\n shouldSetAsDefaultInstrument?: boolean,\n ): Promise {\n if (\n !isRequestError(error) ||\n !some(error.body.errors, { code: 'additional_action_required' })\n ) {\n throw error;\n }\n\n const payment = await this._handleAction(error.body.provider_data);\n\n try {\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n ...payment.paymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n },\n });\n } catch (paymentError) {\n return this._processAdditionalAction(\n paymentError,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n private _validateCardData(): void {\n const adyenv3 = this._getPaymentInitializeOptions();\n const cardComponent = adyenv3.hasVaultedInstruments\n ? this._cardVerificationComponent\n : this._paymentComponent;\n\n if (!cardComponent?.componentRef?.showValidation || !cardComponent.state) {\n return;\n }\n\n cardComponent.componentRef.showValidation();\n\n if (Object.keys(cardComponent.state).length === 0 || !cardComponent.state.isValid) {\n throw new PaymentInvalidFormError(this._mapCardErrors(cardComponent.state.errors));\n }\n }\n\n private _mapCardErrors(cardStateErrors: CardStateErrors = {}): PaymentInvalidFormErrorDetails {\n const errors: PaymentInvalidFormErrorDetails = {};\n\n Object.keys(cardStateErrors).forEach((key) => {\n errors[key] = [\n {\n message: cardStateErrors[key],\n type: key,\n },\n ];\n });\n\n return errors;\n }\n}\n","import { ScriptLoader, StylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { AdyenClient, AdyenConfiguration, AdyenHostWindow } from './adyenv3';\n\nexport default class AdyenV3ScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _stylesheetLoader: StylesheetLoader,\n private _window: AdyenHostWindow = window,\n ) {}\n\n async load(configuration: AdyenConfiguration): Promise {\n await Promise.all([\n this._stylesheetLoader.loadStylesheet(\n `https://checkoutshopper-${\n configuration.environment ?? ''\n }.adyen.com/checkoutshopper/sdk/5.24.0/adyen.css`,\n ),\n this._scriptLoader.loadScript(\n `https://checkoutshopper-${\n configuration.environment ?? ''\n }.adyen.com/checkoutshopper/sdk/5.24.0/adyen.js`,\n ),\n ]);\n\n if (!this._window.AdyenCheckout) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n const checkout = await this._window.AdyenCheckout(configuration);\n\n return checkout;\n }\n}\n","import { getScriptLoader, getStylesheetLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport AdyenV3PaymentStrategy from './adyenv3-payment-strategy';\nimport AdyenV3ScriptLoader from './adyenv3-script-loader';\n\nconst createAdyenV3PaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new AdyenV3PaymentStrategy(\n paymentIntegrationService,\n new AdyenV3ScriptLoader(getScriptLoader(), getStylesheetLoader()),\n );\n};\n\nexport default toResolvableModule(createAdyenV3PaymentStrategy, [{ gateway: 'adyenv3' }]);\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport {\n Cart,\n Checkout,\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n PaymentRequestOptions,\n PaymentStrategy,\n StoreConfig,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithApplePayPaymentInitializeOptions } from './apple-pay-payment-initialize-options';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst validationEndpoint = (bigPayEndpoint: string) =>\n `${bigPayEndpoint}/api/public/v1/payments/applepay/validate_merchant`;\n\ninterface ApplePayPromise {\n resolve(): void;\n reject(reason?: Error): void;\n}\n\nenum DefaultLabels {\n Shipping = 'Shipping',\n Subtotal = 'Subtotal',\n}\n\nexport default class ApplePayPaymentStrategy implements PaymentStrategy {\n private _shippingLabel: string = DefaultLabels.Shipping;\n private _subTotalLabel: string = DefaultLabels.Subtotal;\n\n constructor(\n private _requestSender: RequestSender,\n private _paymentIntegrationService: PaymentIntegrationService,\n private _sessionFactory: ApplePaySessionFactory,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithApplePayPaymentInitializeOptions,\n ): Promise {\n if (!options?.methodId) {\n throw new InvalidArgumentError(\n 'Unable to submit payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n const { methodId } = options;\n\n this._shippingLabel = options.applepay?.shippingLabel || DefaultLabels.Shipping;\n this._subTotalLabel = options.applepay?.subtotalLabel || DefaultLabels.Subtotal;\n await this._paymentIntegrationService.loadPaymentMethod(methodId);\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment } = payload;\n const state = this._paymentIntegrationService.getState();\n const checkout = state.getCheckoutOrThrow();\n const cart = state.getCartOrThrow();\n const config = state.getStoreConfigOrThrow();\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId } = payment;\n\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n const request = this._getBaseRequest(cart, checkout, config, paymentMethod);\n const applePaySession = this._sessionFactory.create(request);\n\n await this._paymentIntegrationService.submitOrder(\n {\n useStoreCredit: payload.useStoreCredit,\n },\n options,\n );\n\n applePaySession.begin();\n\n return new Promise((resolve, reject) => {\n this._handleApplePayEvents(applePaySession, paymentMethod, {\n resolve,\n reject,\n });\n });\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private _getBaseRequest(\n cart: Cart,\n checkout: Checkout,\n config: StoreConfig,\n paymentMethod: PaymentMethod,\n ): ApplePayJS.ApplePayPaymentRequest {\n const {\n storeProfile: { storeCountryCode, storeName },\n } = config;\n const {\n currency: { decimalPlaces },\n } = cart;\n const {\n initializationData: { merchantCapabilities, supportedNetworks },\n } = paymentMethod;\n const lineItems: ApplePayJS.ApplePayLineItem[] = [\n {\n label: this._subTotalLabel,\n amount: `${checkout.subtotal.toFixed(decimalPlaces)}`,\n },\n ];\n\n checkout.taxes.forEach((tax) =>\n lineItems.push({\n label: tax.name,\n amount: `${tax.amount.toFixed()}`,\n }),\n );\n\n lineItems.push({\n label: this._shippingLabel,\n amount: `${checkout.shippingCostTotal.toFixed(decimalPlaces)}`,\n });\n\n return {\n countryCode: storeCountryCode,\n currencyCode: cart.currency.code,\n merchantCapabilities,\n supportedNetworks,\n lineItems,\n total: {\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(cart.currency.decimalPlaces)}`,\n type: 'final',\n },\n };\n }\n\n private _handleApplePayEvents(\n applePaySession: ApplePaySession,\n paymentMethod: PaymentMethod,\n promise: ApplePayPromise,\n ) {\n applePaySession.onvalidatemerchant = async (event) => {\n try {\n const { body: merchantSession } = await this._onValidateMerchant(\n paymentMethod,\n event,\n );\n\n applePaySession.completeMerchantValidation(merchantSession);\n } catch (err) {\n throw new Error('Merchant validation failed');\n }\n };\n\n applePaySession.oncancel = async () =>\n promise.reject(new PaymentMethodCancelledError('Continue with applepay'));\n\n applePaySession.onpaymentauthorized = (event: ApplePayJS.ApplePayPaymentAuthorizedEvent) =>\n this._onPaymentAuthorized(event, applePaySession, paymentMethod, promise);\n }\n\n private async _onValidateMerchant(\n paymentData: PaymentMethod,\n event: ApplePayJS.ApplePayValidateMerchantEvent,\n ) {\n const body = [\n `validationUrl=${event.validationURL}`,\n `merchantIdentifier=${paymentData.initializationData.merchantId}`,\n `displayName=${paymentData.initializationData.storeName}`,\n `domainName=${window.location.hostname}`,\n ].join('&');\n\n return this._requestSender.post(\n validationEndpoint(paymentData.initializationData.paymentsUrl),\n {\n credentials: false,\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'X-XSRF-TOKEN': null,\n },\n body,\n },\n );\n }\n\n private async _onPaymentAuthorized(\n event: ApplePayJS.ApplePayPaymentAuthorizedEvent,\n applePaySession: ApplePaySession,\n paymentMethod: PaymentMethod,\n promise: ApplePayPromise,\n ) {\n const { token } = event.payment;\n const payment: Payment = {\n methodId: paymentMethod.id,\n paymentData: {\n formattedPayload: {\n apple_pay_token: {\n payment_data: token.paymentData,\n payment_method: token.paymentMethod,\n transaction_id: token.transactionIdentifier,\n },\n },\n },\n };\n\n try {\n await this._paymentIntegrationService.submitPayment(payment);\n applePaySession.completePayment(ApplePaySession.STATUS_SUCCESS);\n\n return promise.resolve();\n } catch (error) {\n applePaySession.completePayment(ApplePaySession.STATUS_FAILURE);\n\n return promise.reject(\n new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ApplePayPaymentStrategy from './apple-pay-payment-strategy';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst createApplePayPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new ApplePayPaymentStrategy(\n createRequestSender({ host: getHost() }),\n paymentIntegrationService,\n new ApplePaySessionFactory(),\n );\n};\n\nexport default toResolvableModule(createApplePayPaymentStrategy, [{ id: 'applepay' }]);\n","export default function guard(value: T, errorFactory?: () => Error): NonNullable {\n if (value === undefined || value === null) {\n throw errorFactory ? errorFactory() : new Error('An unexpected error has occurred.');\n }\n\n return value as NonNullable;\n}\n","// copied from packages/core/src/hosted-form/hosted-field-type.ts\n\nenum HostedFieldType {\n CardCode = 'cardCode',\n CardCodeVerification = 'cardCodeVerification',\n CardExpiry = 'cardExpiry',\n CardName = 'cardName',\n CardNumber = 'cardNumber',\n CardNumberVerification = 'cardNumberVerification',\n}\n\nexport default HostedFieldType;\n","import {\n HostedCardFieldOptionsMap,\n HostedFieldOptionsMap,\n HostedFieldType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isHostedCardFieldOptionsMap(\n fields: HostedFieldOptionsMap,\n): fields is HostedCardFieldOptionsMap {\n return HostedFieldType.CardNumber in fields;\n}\n","import {\n HostedFieldOptionsMap,\n HostedFieldType,\n HostedStoredCardFieldOptionsMap,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isHostedStoredCardFieldOptionsMap(\n fields: HostedFieldOptionsMap,\n): fields is HostedStoredCardFieldOptionsMap {\n return (\n HostedFieldType.CardCodeVerification in fields ||\n HostedFieldType.CardNumberVerification in fields\n );\n}\n","import { WithCreditCardPaymentInitializeOptions } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n guard,\n InvalidArgumentError,\n isHostedInstrumentLike,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BlueSnapDirectHostedForm from './bluesnap-direct-hosted-form';\nimport isHostedCardFieldOptionsMap from './is-hosted-card-field-options-map';\nimport isHostedStoredCardFieldOptionsMap from './is-hosted-stored-card-field-options-map';\nimport { BlueSnapDirectThreeDSecureData } from './types';\n\nexport default class BlueSnapDirectCreditCardPaymentStrategy implements PaymentStrategy {\n private _paymentFieldsToken?: string;\n private _shouldUseHostedFields?: boolean;\n\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _blueSnapDirectHostedForm: BlueSnapDirectHostedForm,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithCreditCardPaymentInitializeOptions,\n ): Promise {\n const { methodId, gatewayId, creditCard } = options;\n\n if (!gatewayId || !creditCard) {\n throw new InvalidArgumentError();\n }\n\n const state = await this._paymentIntegrationService.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n });\n\n const {\n config: { testMode, is3dsEnabled },\n clientToken,\n } = state.getPaymentMethodOrThrow(methodId, gatewayId);\n\n this._paymentFieldsToken = clientToken;\n this._shouldUseHostedFields =\n isHostedCardFieldOptionsMap(creditCard.form.fields) ||\n (isHostedStoredCardFieldOptionsMap(creditCard.form.fields) &&\n (!!creditCard.form.fields.cardNumberVerification ||\n !!creditCard.form.fields.cardCodeVerification));\n\n if (this._shouldUseHostedFields) {\n await this._blueSnapDirectHostedForm.initialize(testMode, creditCard.form.fields);\n await this._blueSnapDirectHostedForm.attach(\n this._getPaymentFieldsToken(),\n creditCard,\n is3dsEnabled,\n );\n }\n }\n\n async execute(payload: OrderRequestBody): Promise {\n if (!payload.payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { paymentData } = payload.payment;\n\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = isHostedInstrumentLike(\n paymentData,\n )\n ? paymentData\n : { shouldSaveInstrument: false, shouldSetAsDefaultInstrument: false };\n\n const pfToken = this._getPaymentFieldsToken();\n\n const { is3dsEnabled } = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(payload.payment.methodId, payload.payment.gatewayId).config;\n\n const bluesnapSubmitedForm = this._shouldUseHostedFields\n ? await this._blueSnapDirectHostedForm\n .validate()\n .submit(\n is3dsEnabled ? this._getBlueSnapDirectThreeDSecureData() : undefined,\n !(isHostedInstrumentLike(paymentData) && isVaultedInstrument(paymentData)),\n )\n : undefined;\n\n await this._paymentIntegrationService.submitOrder();\n\n if (\n isHostedInstrumentLike(paymentData) &&\n isVaultedInstrument(paymentData) &&\n paymentData.instrumentId\n ) {\n await this._paymentIntegrationService.submitPayment({\n ...payload.payment,\n paymentData: {\n instrumentId: paymentData.instrumentId,\n ...(this._shouldUseHostedFields ? { nonce: pfToken } : {}),\n shouldSetAsDefaultInstrument: !!shouldSetAsDefaultInstrument,\n },\n });\n\n return;\n }\n\n await this._paymentIntegrationService.submitPayment({\n ...payload.payment,\n paymentData: {\n formattedPayload: {\n credit_card_token: {\n token: JSON.stringify({\n pfToken,\n cardHolderName:\n bluesnapSubmitedForm && bluesnapSubmitedForm.cardHolderName,\n }),\n },\n vault_payment_instrument: shouldSaveInstrument,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n },\n },\n });\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n if (this._shouldUseHostedFields) {\n this._blueSnapDirectHostedForm.detach();\n }\n\n return Promise.resolve();\n }\n\n private _getBlueSnapDirectThreeDSecureData(): BlueSnapDirectThreeDSecureData {\n const {\n getBillingAddress,\n getShippingAddress,\n getCustomer,\n getCheckoutOrThrow,\n getCartOrThrow,\n } = this._paymentIntegrationService.getState();\n const billingAddress = getBillingAddress();\n const shippingAddress = getShippingAddress();\n const email = getCustomer()?.email || billingAddress?.email;\n const phone = billingAddress?.phone || shippingAddress?.phone;\n\n return {\n amount: getCheckoutOrThrow().outstandingBalance,\n currency: getCartOrThrow().currency.code,\n ...(email && { email }),\n ...(phone && { phone }),\n ...(billingAddress && {\n billingFirstName: billingAddress.firstName,\n billingLastName: billingAddress.lastName,\n billingCountry: billingAddress.countryCode,\n billingState: billingAddress.stateOrProvinceCode,\n billingCity: billingAddress.city,\n billingAddress: `${billingAddress.address1} ${billingAddress.address2}`.trim(),\n billingZip: billingAddress.postalCode,\n }),\n ...(shippingAddress && {\n shippingFirstName: shippingAddress.firstName,\n shippingLastName: shippingAddress.lastName,\n shippingCountry: shippingAddress.countryCode,\n shippingState: shippingAddress.stateOrProvinceCode,\n shippingCity: shippingAddress.city,\n shippingAddress: `${shippingAddress.address1} ${shippingAddress.address2}`.trim(),\n shippingZip: shippingAddress.postalCode,\n }),\n };\n }\n\n private _getPaymentFieldsToken(): string {\n return guard(\n this._paymentFieldsToken,\n () => new MissingDataError(MissingDataErrorType.MissingPaymentToken),\n );\n }\n}\n","export type BluesnapDirectNocInputAllowedStyle = Pick<\n CSSStyleDeclaration,\n 'color' | 'fontFamily' | 'fontSize' | 'fontWeight'\n>;\n\nexport interface BlueSnapDirectStyleDeclaration {\n [k: string]: string;\n}\n\nexport interface BlueSnapDirectStyle {\n '.invalid'?: BlueSnapDirectStyleDeclaration;\n ':focus'?: BlueSnapDirectStyleDeclaration;\n input?: BlueSnapDirectStyleDeclaration;\n}\n\nexport enum BlueSnapDirectCardType {\n AMEX = 'american-express',\n CHINA_UNION_PAY = 'unionpay',\n DINERS = 'diners-club',\n DISCOVER = 'discover',\n JCB = 'jcb',\n MASTERCARD = 'mastercard',\n UNKNOWN = 'unknown',\n VISA = 'visa',\n}\n\nexport type BlueSnapDirectCardTypeValues = keyof typeof BlueSnapDirectCardType;\n\nexport enum BlueSnapDirectEventOrigin {\n ON_BLUR = 'onBlur',\n ON_SUBMIT = 'onSubmit',\n}\n\nexport enum BlueSnapDirectErrorDescription {\n EMPTY = 'empty',\n INVALID = 'invalid',\n THREE_DS_NOT_ENABLED = '3D Secure is not enabled',\n}\n\nexport type BlueSnapDirectInputValidationErrorDescription = Extract<\n BlueSnapDirectErrorDescription,\n BlueSnapDirectErrorDescription.EMPTY | BlueSnapDirectErrorDescription.INVALID\n>;\n\nexport enum BlueSnapDirectErrorCode {\n CC_NOT_SUPORTED = '22013',\n ERROR_403 = '403',\n ERROR_404 = '404',\n ERROR_500 = '500',\n INVALID_OR_EMPTY = '10',\n SESSION_EXPIRED = '400',\n THREE_DS_AUTH_FAILED = '14101',\n THREE_DS_CLIENT_ERROR = '14103',\n THREE_DS_MISSING_FIELDS = '14102',\n THREE_DS_NOT_ENABLED = '14100',\n TOKEN_EXPIRED = '14040',\n TOKEN_NOT_ASSOCIATED = '14042',\n TOKEN_NOT_FOUND = '14041',\n}\n\nexport enum BlueSnapDirectHostedFieldTagId {\n CardCode = 'cvv',\n CardExpiry = 'exp',\n CardName = 'noc',\n CardNumber = 'ccn',\n}\n\nexport interface BlueSnapDirectHostedPaymentFieldsOptions {\n token: string;\n onFieldEventHandler?: {\n setupComplete?: () => void;\n threeDsChallengeExecuted?: () => void;\n onFocus?: (tagId: BlueSnapDirectHostedFieldTagId) => void;\n onBlur?: (tagId: BlueSnapDirectHostedFieldTagId) => void;\n onError?: (\n tagId: BlueSnapDirectHostedFieldTagId | undefined,\n errorCode: BlueSnapDirectErrorCode,\n errorDescription: BlueSnapDirectErrorDescription | undefined,\n eventOrigin: BlueSnapDirectEventOrigin | undefined,\n ) => void;\n onType?: (\n tagId: BlueSnapDirectHostedFieldTagId,\n cardType: BlueSnapDirectCardTypeValues,\n cardData: BlueSnapDirectCardData | undefined,\n ) => void;\n onEnter?: (tagId: BlueSnapDirectHostedFieldTagId) => void;\n onValid?: (tagId: BlueSnapDirectHostedFieldTagId) => void;\n };\n ccnPlaceHolder?: string;\n cvvPlaceHolder?: string;\n expPlaceHolder?: string;\n style?: BlueSnapDirectStyle;\n '3DS'?: boolean;\n}\n\ninterface BlueSnapDirectCallback {\n statusCode: string;\n transactionFraudInfo: {\n fraudSessionId: string;\n };\n}\n\ninterface BlueSnapDirectCardData {\n binCategory: string;\n cardSubType: string;\n ccBin: string;\n ccType: string;\n isRegulatedCard: string;\n issuingCountry: string;\n last4Digits: string;\n}\n\nexport interface BlueSnapDirectCallbackCardData extends BlueSnapDirectCardData {\n cardCategory: string;\n exp: string;\n}\n\ninterface BlueSnapDirectCallbackData extends BlueSnapDirectCallback {\n cardData: BlueSnapDirectCallbackCardData;\n}\n\nexport interface WithBlueSnapDirectCardHolderName {\n cardHolderName?: string;\n}\n\ninterface BlueSnapDirectSubmitError {\n errorCode: string;\n errorDescription: string;\n eventType: string;\n tagId: string;\n}\n\nexport interface BlueSnapDirectCallbackError extends BlueSnapDirectCallback {\n error: BlueSnapDirectSubmitError[];\n}\n\nexport type BlueSnapDirectCallbackResults =\n | BlueSnapDirectCallbackData\n | BlueSnapDirectCallbackError;\n\nexport interface BlueSnapDirectThreeDSecureData {\n amount: number;\n currency: string;\n billingFirstName?: string;\n billingLastName?: string;\n billingCountry?: string;\n billingState?: string;\n billingCity?: string;\n billingAddress?: string;\n billingZip?: string;\n shippingFirstName?: string;\n shippingLastName?: string;\n shippingCountry?: string;\n shippingState?: string;\n shippingCity?: string;\n shippingAddress?: string;\n shippingZip?: string;\n email?: string;\n phone?: string;\n}\n\nexport interface BlueSnapDirectSdk {\n hostedPaymentFieldsCreate(options: BlueSnapDirectHostedPaymentFieldsOptions): void;\n hostedPaymentFieldsSubmitData(\n callback: (results: BlueSnapDirectCallbackResults) => void,\n threeDSecureData?: BlueSnapDirectThreeDSecureData,\n ): void;\n}\n\nexport interface BlueSnapDirectHostWindow extends Window {\n bluesnap?: BlueSnapDirectSdk;\n}\n\nexport interface BlueSnapDirectStyleProps {\n border?: string;\n height?: string;\n width?: string;\n}\n\nexport interface BlueSnapDirectRedirectResponseProviderData {\n [key: string]: string;\n merchantid: string;\n}\n\nexport interface BlueSnapDirectRedirectResponse {\n body: {\n additional_action_required: {\n type: 'offsite_redirect';\n data: {\n redirect_url: string;\n };\n };\n status: string;\n provider_data: string;\n };\n}\n\n/**\n * A set of options that are required to initialize the BlueSnap V2 payment\n * method.\n *\n * The payment step is done through a web page via an iframe provided by the\n * strategy.\n *\n * ```html\n * \n *
\n *\n * \n * \n * ```\n *\n * ```js\n * service.initializePayment({\n * methodId: 'bluesnapDirect',\n * bluesnapDirect: {\n * onLoad: (iframe) => {\n * document.getElementById('container')\n * .appendChild(iframe);\n *\n * document.getElementById('cancel-button')\n * .addEventListener('click', () => {\n * document.getElementById('container').innerHTML = '';\n * });\n * },\n * },\n * });\n * ```\n */\nexport interface BlueSnapDirectAPMInitializeOptions {\n /**\n * A set of CSS properties to apply to the iframe.\n */\n style?: BlueSnapDirectStyleProps;\n\n /**\n * A callback that gets called when the iframe is ready to be added to the\n * current page. It is responsible for determining where the iframe should\n * be inserted in the DOM.\n *\n * @param iframe - The iframe element containing the payment web page\n * provided by the strategy.\n * @param cancel - A function, when called, will cancel the payment\n * process and remove the iframe.\n */\n onLoad(iframe: HTMLIFrameElement, cancel: () => void): void;\n}\n\nexport interface WithBlueSnapDirectAPMPaymentInitializeOptions {\n /**\n * The options that are required to initialize the Apple Pay payment\n * method. They can be omitted unless you need to support Apple Pay.\n */\n bluesnapdirect?: BlueSnapDirectAPMInitializeOptions;\n}\n","import { HostedFieldType } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BlueSnapDirectHostedFieldTagId as HostedFieldTagId } from './types';\n\nexport const BlueSnapHostedFieldType: {\n [HostedFieldTagId.CardNumber]: HostedFieldType.CardNumber;\n [HostedFieldTagId.CardExpiry]: HostedFieldType.CardExpiry;\n [HostedFieldTagId.CardName]: HostedFieldType.CardName;\n [HostedFieldTagId.CardCode]: HostedFieldType.CardCode;\n} = {\n [HostedFieldTagId.CardNumber]: HostedFieldType.CardNumber,\n [HostedFieldTagId.CardExpiry]: HostedFieldType.CardExpiry,\n [HostedFieldTagId.CardName]: HostedFieldType.CardName,\n [HostedFieldTagId.CardCode]: HostedFieldType.CardCode,\n};\n\nexport const CREDIT_CARD_ERRORS = {\n empty: {\n [HostedFieldType.CardNumber]: {\n fieldType: 'cardNumber',\n message: 'Credit card number is required',\n type: 'required',\n },\n [HostedFieldType.CardNumberVerification]: {\n fieldType: 'cardNumber',\n message: 'Credit card number is required',\n type: 'required',\n },\n [HostedFieldType.CardExpiry]: {\n fieldType: 'cardExpiry',\n message: 'Expiration date is required',\n type: 'required',\n },\n [HostedFieldType.CardCode]: {\n fieldType: 'cardCode',\n message: 'CVV is required',\n type: 'required',\n },\n [HostedFieldType.CardCodeVerification]: {\n fieldType: 'cardCode',\n message: 'CVV is required',\n type: 'required',\n },\n [HostedFieldType.CardName]: {\n fieldType: 'cardName',\n message: 'Full name is required',\n type: 'required',\n },\n },\n invalid: {\n [HostedFieldType.CardNumber]: {\n fieldType: 'cardNumber',\n message: 'Credit card number must be valid',\n type: 'invalid_card_number',\n },\n [HostedFieldType.CardNumberVerification]: {\n fieldType: 'cardNumber',\n message: 'Credit card number must be valid',\n type: 'invalid_card_number',\n },\n [HostedFieldType.CardExpiry]: {\n fieldType: 'cardExpiry',\n message: 'Expiration date must be a valid future date in MM / YY format',\n type: 'invalid_card_expiry',\n },\n [HostedFieldType.CardCode]: {\n fieldType: 'cardCode',\n message: 'CVV must be valid',\n type: 'invalid_card_code',\n },\n [HostedFieldType.CardCodeVerification]: {\n fieldType: 'cardCode',\n message: 'CVV must be valid',\n type: 'invalid_card_code',\n },\n [HostedFieldType.CardName]: {\n fieldType: 'cardName',\n message: 'Full name is required',\n type: 'required',\n },\n },\n};\n","import { kebabCase } from 'lodash';\n\nimport { CreditCardPaymentInitializeOptions } from '@bigcommerce/checkout-sdk/credit-card-integration';\nimport {\n guard,\n HostedCardFieldOptionsMap,\n HostedFieldBlurEventData,\n HostedFieldEnterEventData,\n HostedFieldFocusEventData,\n HostedFieldOptionsMap,\n HostedFieldStylesMap,\n HostedFormOptions,\n HostedInputValidateErrorData,\n HostedStoredCardFieldOptionsMap,\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n PaymentMethodFailedError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BlueSnapHostedFieldType } from './bluesnap-direct-constants';\nimport BlueSnapHostedInputValidator from './bluesnap-direct-hosted-input-validator';\nimport BluesnapDirectNameOnCardInput from './bluesnap-direct-name-on-card-input';\nimport BlueSnapDirectScriptLoader from './bluesnap-direct-script-loader';\nimport isValidationErrorDescription from './is-bluesnap-direct-input-validation-error-description';\nimport isHostedCardFieldOptionsMap from './is-hosted-card-field-options-map';\nimport isHostedStoredCardFieldOptionsMap from './is-hosted-stored-card-field-options-map';\nimport {\n BlueSnapDirectSdk,\n BlueSnapDirectStyle,\n BlueSnapDirectCallbackCardData as CallbackCardData,\n BlueSnapDirectCallbackError as CallbackError,\n BlueSnapDirectCallbackResults as CallbackResults,\n WithBlueSnapDirectCardHolderName as CardHolderName,\n BlueSnapDirectCardType as CardType,\n BlueSnapDirectCardTypeValues as CardTypeValues,\n BlueSnapDirectErrorCode as ErrorCode,\n BlueSnapDirectErrorDescription as ErrorDescription,\n BlueSnapDirectEventOrigin as EventOrigin,\n BlueSnapDirectHostedFieldTagId as HostedFieldTagId,\n BlueSnapDirectHostedPaymentFieldsOptions as HostedPaymentFieldsOptions,\n BlueSnapDirectThreeDSecureData as ThreeDSecureData,\n} from './types';\n\nexport default class BlueSnapDirectHostedForm {\n private _blueSnapSdk?: BlueSnapDirectSdk;\n private _onValidate: HostedFormOptions['onValidate'];\n\n constructor(\n private _scriptLoader: BlueSnapDirectScriptLoader,\n private _nameOnCardInput: BluesnapDirectNameOnCardInput,\n private _hostedInputValidator: BlueSnapHostedInputValidator,\n ) {}\n\n async initialize(testMode = false, fields?: HostedFieldOptionsMap): Promise {\n this._blueSnapSdk = await this._scriptLoader.load(testMode);\n\n if (!fields) {\n return;\n }\n\n if (isHostedCardFieldOptionsMap(fields)) {\n this._hostedInputValidator.initialize();\n\n return;\n }\n\n if (\n isHostedStoredCardFieldOptionsMap(fields) &&\n !!fields.cardNumberVerification &&\n !!fields.cardCodeVerification\n ) {\n this._hostedInputValidator.initializeValidationFields();\n\n return;\n }\n\n if (isHostedStoredCardFieldOptionsMap(fields) && !!fields.cardCodeVerification) {\n this._hostedInputValidator.initializeValidationCVVFields();\n }\n }\n\n async attach(\n paymentFieldsToken: string,\n { form: { fields, ...callbacksAndStyles } }: CreditCardPaymentInitializeOptions,\n enable3DS = false,\n ): Promise {\n const blueSnapSdk = this._getBlueSnapSdk();\n\n if (!isHostedCardFieldOptionsMap(fields) && !isHostedStoredCardFieldOptionsMap(fields)) {\n throw new InvalidArgumentError(\n 'Field options must be of type HostedCardFieldOptionsMap',\n );\n }\n\n this._onValidate = callbacksAndStyles.onValidate;\n\n if (isHostedCardFieldOptionsMap(fields)) {\n this._setCustomBlueSnapAttributes(fields);\n }\n\n if (isHostedStoredCardFieldOptionsMap(fields)) {\n this._setCustomStoredCardsBlueSnapAttributes(fields);\n }\n\n return new Promise((resolve) => {\n const options = this._getHostedPaymentFieldsOptions(\n paymentFieldsToken,\n fields,\n callbacksAndStyles,\n resolve,\n enable3DS,\n );\n\n blueSnapSdk.hostedPaymentFieldsCreate(options);\n\n if (isHostedCardFieldOptionsMap(fields)) {\n this._nameOnCardInput.attach(\n options,\n fields.cardName.accessibilityLabel,\n fields.cardName.placeholder,\n );\n }\n });\n }\n\n validate(): this {\n const results = this._hostedInputValidator.validate();\n\n this._onValidate?.(results);\n\n if (!results.isValid) {\n const details = Object.entries(results.errors).reduce(\n (result, [key, value]: [string, HostedInputValidateErrorData[]]) => ({\n ...result,\n [key]: value.map(({ message, type }) => ({ message, type })),\n }),\n {},\n );\n\n throw new PaymentInvalidFormError(details);\n }\n\n return this;\n }\n\n submit(\n threeDSecureData?: ThreeDSecureData,\n shouldSendName = false,\n ): Promise {\n return new Promise((resolve, reject) =>\n this._getBlueSnapSdk().hostedPaymentFieldsSubmitData(\n (data: CallbackResults) =>\n this._isBlueSnapDirectCallbackError(data)\n ? reject(\n new PaymentMethodFailedError(\n data.statusCode === ErrorCode.THREE_DS_AUTH_FAILED\n ? data.error[0].errorDescription\n : `Submission failed with status: ${\n data.statusCode\n } and errors: ${JSON.stringify(data.error)}`,\n ),\n )\n : resolve({\n ...data.cardData,\n ...(shouldSendName\n ? { cardHolderName: this._nameOnCardInput.getValue() }\n : {}),\n }),\n threeDSecureData,\n ),\n );\n }\n\n detach(): void {\n this._nameOnCardInput.detach();\n }\n\n private _isBlueSnapDirectCallbackError(data: CallbackResults): data is CallbackError {\n return 'error' in data;\n }\n\n private _getHostedPaymentFieldsOptions(\n token: string,\n fields: HostedCardFieldOptionsMap | HostedStoredCardFieldOptionsMap,\n {\n onFocus,\n onBlur,\n onValidate,\n onCardTypeChange,\n onEnter,\n styles,\n }: Omit,\n resolve: () => void,\n enable3DS: boolean,\n ): HostedPaymentFieldsOptions {\n return {\n token,\n onFieldEventHandler: {\n setupComplete: () => resolve(),\n onFocus: this._usetUiEventCallback(onFocus),\n onBlur: this._usetUiEventCallback(onBlur),\n onError: this._handleError(onValidate),\n onType: (_tagId: HostedFieldTagId, cardType: CardTypeValues) =>\n onCardTypeChange?.({ cardType: CardType[cardType] }),\n onEnter: this._usetUiEventCallback(onEnter),\n onValid: (tagId: HostedFieldTagId) =>\n onValidate?.(this._hostedInputValidator.validate({ tagId })),\n },\n ...(isHostedCardFieldOptionsMap(fields) && {\n ccnPlaceHolder: fields.cardNumber.placeholder || '',\n cvvPlaceHolder: fields.cardCode?.placeholder || '',\n expPlaceHolder: fields.cardExpiry.placeholder || 'MM / YY',\n }),\n ...(styles && { style: this._mapStyles(styles) }),\n '3DS': enable3DS,\n };\n }\n\n private _mapStyles({\n default: input,\n error,\n focus,\n }: HostedFieldStylesMap): BlueSnapDirectStyle {\n return Object.entries({\n ...(input && { input }),\n ...(error && { '.invalid': error }),\n ...(focus && { ':focus': focus }),\n }).reduce((result, [selector, declaration]) => {\n return {\n ...result,\n [selector]: Object.entries(declaration).reduce(\n (declarationBlock, [property, value]) => ({\n ...declarationBlock,\n [kebabCase(property)]: value,\n }),\n {},\n ),\n };\n }, {});\n }\n\n private _handleError(\n onValidate: HostedFormOptions['onValidate'],\n ): (\n tagId: HostedFieldTagId | undefined,\n errorCode: ErrorCode,\n errorDescription: ErrorDescription | undefined,\n eventOrigin: EventOrigin | undefined,\n ) => void {\n return (tagId, errorCode, errorDescription, eventOrigin) => {\n if (errorCode === ErrorCode.INVALID_OR_EMPTY) {\n if (tagId && isValidationErrorDescription(errorDescription)) {\n return onValidate?.(\n this._hostedInputValidator.validate({ tagId, errorDescription }),\n );\n }\n }\n\n throw new PaymentMethodFailedError(\n `An unexpected error has occurred: ${JSON.stringify({\n tagId,\n errorCode,\n errorDescription,\n eventOrigin,\n })}`,\n );\n };\n }\n\n private _usetUiEventCallback(\n callback?: (\n data: HostedFieldBlurEventData | HostedFieldEnterEventData | HostedFieldFocusEventData,\n ) => void,\n ): (tagId: HostedFieldTagId) => void {\n return (tagId) => {\n if (callback) {\n callback({ fieldType: BlueSnapHostedFieldType[tagId] });\n }\n };\n }\n\n private _getBlueSnapSdk(): BlueSnapDirectSdk {\n return guard(\n this._blueSnapSdk,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n private _setCustomBlueSnapAttributes(fields: HostedCardFieldOptionsMap): void {\n const { cardNumber, cardExpiry, cardCode, cardName } = fields;\n\n const cardNumberContainer = document.getElementById(cardNumber.containerId);\n const cardExpiryContainer = document.getElementById(cardExpiry.containerId);\n const cardCodeContainer = cardCode && document.getElementById(cardCode.containerId);\n const cardNameContainer = document.getElementById(cardName.containerId);\n\n if (\n !cardNumberContainer ||\n !cardExpiryContainer ||\n !cardCodeContainer ||\n !cardNameContainer\n ) {\n throw new InvalidArgumentError(\n 'Unable to create hosted payment fields to invalid HTML container elements.',\n );\n }\n\n cardNumberContainer.dataset.bluesnap = HostedFieldTagId.CardNumber;\n cardExpiryContainer.dataset.bluesnap = HostedFieldTagId.CardExpiry;\n cardCodeContainer.dataset.bluesnap = HostedFieldTagId.CardCode;\n cardNameContainer.dataset.bluesnap = HostedFieldTagId.CardName;\n }\n\n private _setCustomStoredCardsBlueSnapAttributes(fields: HostedStoredCardFieldOptionsMap): void {\n const { cardNumberVerification, cardCodeVerification } = fields;\n\n const cardNumberContainer =\n cardNumberVerification && document.getElementById(cardNumberVerification.containerId);\n const cardCodeContainer =\n cardCodeVerification && document.getElementById(cardCodeVerification.containerId);\n\n if (!cardNumberContainer && !cardCodeContainer) {\n return;\n }\n\n if (cardNumberContainer) {\n cardNumberContainer.dataset.bluesnap = HostedFieldTagId.CardNumber;\n }\n\n if (cardCodeContainer) {\n cardCodeContainer.dataset.bluesnap = HostedFieldTagId.CardCode;\n }\n }\n}\n","import {\n BlueSnapDirectErrorDescription,\n BlueSnapDirectInputValidationErrorDescription,\n} from './types';\n\nexport default function isBlueSnapDirectInputValidationErrorDescription(\n errorDescription?: BlueSnapDirectErrorDescription,\n): errorDescription is BlueSnapDirectInputValidationErrorDescription {\n if (errorDescription === undefined) {\n return false;\n }\n\n return [BlueSnapDirectErrorDescription.EMPTY, BlueSnapDirectErrorDescription.INVALID].includes(\n errorDescription,\n );\n}\n","import {\n HostedInputValidateErrorData,\n HostedInputValidateErrorDataMap,\n HostedInputValidateResults,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BlueSnapHostedFieldType, CREDIT_CARD_ERRORS } from './bluesnap-direct-constants';\nimport {\n BlueSnapDirectInputValidationErrorDescription as ErrorDescription,\n BlueSnapDirectHostedFieldTagId as HostedFieldTagId,\n} from './types';\n\nexport default class BlueSnapHostedInputValidator {\n private _errors: HostedInputValidateErrorDataMap = {};\n\n initialize(): void {\n this._errors = {\n cardNumber: [CREDIT_CARD_ERRORS.empty.cardNumber],\n cardExpiry: [CREDIT_CARD_ERRORS.empty.cardExpiry],\n cardCode: [CREDIT_CARD_ERRORS.empty.cardCode],\n cardName: [CREDIT_CARD_ERRORS.empty.cardName],\n };\n }\n\n initializeValidationFields(): void {\n this._errors = {\n cardNumber: [CREDIT_CARD_ERRORS.empty.cardNumber],\n cardCode: [CREDIT_CARD_ERRORS.empty.cardCode],\n };\n }\n\n initializeValidationCVVFields(): void {\n this._errors = {\n cardCode: [CREDIT_CARD_ERRORS.empty.cardCode],\n };\n }\n\n validate(error?: {\n tagId: HostedFieldTagId;\n errorDescription?: ErrorDescription;\n }): HostedInputValidateResults {\n if (error) {\n this._updateErrors(error.tagId, error.errorDescription);\n }\n\n return {\n isValid: Object.values(this._errors).every(\n (errorData: HostedInputValidateErrorData[]) => errorData.length === 0,\n ),\n errors: this._errors,\n };\n }\n\n private _updateErrors(tagId: HostedFieldTagId, errorDescription?: ErrorDescription): void {\n const fieldType = BlueSnapHostedFieldType[tagId];\n\n this._errors[fieldType] = errorDescription\n ? [CREDIT_CARD_ERRORS[errorDescription][fieldType]]\n : [];\n }\n}\n","import {\n guard,\n NotInitializedError,\n NotInitializedErrorType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport isArrayOfAllowedProps from './is-array-of-allowed-props';\nimport {\n BluesnapDirectNocInputAllowedStyle as AllowedStyle,\n BlueSnapDirectStyle,\n BlueSnapDirectErrorCode as ErrorCode,\n BlueSnapDirectErrorDescription as ErrorDescription,\n BlueSnapDirectEventOrigin as EventOrigin,\n BlueSnapDirectHostedFieldTagId as HostedFieldTagId,\n BlueSnapDirectHostedPaymentFieldsOptions as HostedPaymentFieldsOptions,\n BlueSnapDirectStyleDeclaration as StyleDeclaration,\n} from './types';\n\nexport default class BluesnapDirectNameOnCardInput {\n private _input?: HTMLInputElement;\n private _style?: BlueSnapDirectStyle;\n\n attach(\n {\n style,\n onFieldEventHandler: { onFocus, onBlur, onValid, onError, onEnter } = {},\n }: HostedPaymentFieldsOptions,\n accessibilityLabel?: string,\n placeholder?: string,\n ): void {\n this._style = style;\n\n this._create();\n\n this._getInput().addEventListener('focus', this._handleFocus(onFocus));\n this._getInput().addEventListener('blur', this._handleBlur(onBlur, onValid, onError));\n this._getInput().addEventListener('enter', this._handleEnter(onEnter));\n\n if (accessibilityLabel) {\n this._getInput().setAttribute('aria-label', accessibilityLabel);\n }\n\n if (placeholder) {\n this._getInput().placeholder = placeholder;\n }\n\n document.querySelector('[data-bluesnap=\"noc\"]')?.appendChild(this._getInput());\n }\n\n getValue(): string {\n return this._getInput().value;\n }\n\n detach(): void {\n if (this._input) {\n this._input.remove();\n this._input = undefined;\n }\n }\n\n private _handleFocus(\n onFocus: Required['onFieldEventHandler']['onFocus'],\n ): (event: Event) => void {\n return () => {\n this._applyStyles(this._style?.[':focus']);\n\n onFocus?.(HostedFieldTagId.CardName);\n };\n }\n\n private _handleBlur(\n onBlur: Required['onFieldEventHandler']['onBlur'],\n onValid: Required['onFieldEventHandler']['onValid'],\n onError: Required['onFieldEventHandler']['onError'],\n ): (event: Event) => void {\n return ({ target }) => {\n onBlur?.(HostedFieldTagId.CardName);\n\n if (target instanceof HTMLInputElement) {\n if (/\\w{1,200}/.test(target.value)) {\n this._applyStyles(this._style?.input);\n\n onValid?.(HostedFieldTagId.CardName);\n } else {\n this._applyStyles(this._style?.['.invalid']);\n\n onError?.(\n HostedFieldTagId.CardName,\n ErrorCode.INVALID_OR_EMPTY,\n ErrorDescription.EMPTY,\n EventOrigin.ON_BLUR,\n );\n }\n }\n };\n }\n\n private _handleEnter(\n onEnter: Required['onFieldEventHandler']['onEnter'],\n ): (event: Event) => void {\n return () => onEnter?.(HostedFieldTagId.CardName);\n }\n\n private _applyStyles(styles: StyleDeclaration = {}): void {\n const allowedStyle: AllowedStyle = {\n color: styles.color,\n fontFamily: styles['font-family'],\n fontSize: styles['font-size'],\n fontWeight: styles['font-weight'],\n };\n const styleKeys = Object.keys(allowedStyle);\n\n if (isArrayOfAllowedProps(styleKeys)) {\n styleKeys.forEach((key) => {\n if (!allowedStyle[key]) {\n return;\n }\n\n this._getInput().style[key] = allowedStyle[key] || '';\n });\n }\n }\n\n private _configureInput(): void {\n this._getInput().autocomplete = 'cc-name';\n this._getInput().id = HostedFieldTagId.CardName;\n this._getInput().inputMode = 'text';\n this._getInput().maxLength = 200;\n this._getInput().style.backgroundColor = 'transparent';\n this._getInput().style.border = '0';\n this._getInput().style.height = '100%';\n this._getInput().style.margin = '0';\n this._getInput().style.outline = 'none';\n this._getInput().style.padding = '0';\n this._getInput().style.width = '100%';\n this._getInput().type = 'text';\n }\n\n private _getInput(): HTMLInputElement {\n return guard(\n this._input,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n private _create(): void {\n this._input = document.createElement('input');\n this._configureInput();\n this._applyStyles(this._style?.input);\n }\n}\n","import { BluesnapDirectNocInputAllowedStyle } from './types';\n\nexport default function isArrayOfAllowedProps(\n fields: string[],\n): fields is Array {\n return fields.every((field) =>\n ['color', 'fontFamily', 'fontSize', 'fontWeight'].includes(field),\n );\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BlueSnapDirectHostWindow, BlueSnapDirectSdk } from './types';\n\nexport enum BlueSnapDirectSdkEnv {\n PRODUCTION = 'https://pay.bluesnap.com/web-sdk/5/bluesnap.js',\n SANDBOX = 'https://sandpay.bluesnap.com/web-sdk/5/bluesnap.js',\n}\n\nexport default class BlueSnapDirectScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _window: BlueSnapDirectHostWindow = window,\n ) {}\n\n async load(testMode = false): Promise {\n await this._scriptLoader.loadScript(\n testMode ? BlueSnapDirectSdkEnv.SANDBOX : BlueSnapDirectSdkEnv.PRODUCTION,\n );\n\n if (!this._window.bluesnap) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.bluesnap;\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BlueSnapDirectCreditCardPaymentStrategy from './bluesnap-direct-credit-card-payment-strategy';\nimport BlueSnapDirectHostedForm from './bluesnap-direct-hosted-form';\nimport BlueSnapHostedInputValidator from './bluesnap-direct-hosted-input-validator';\nimport BluesnapDirectNameOnCardInput from './bluesnap-direct-name-on-card-input';\nimport BlueSnapDirectScriptLoader from './bluesnap-direct-script-loader';\n\nconst createBlueSnapDirectCreditCardPaymentStrategy: PaymentStrategyFactory<\n BlueSnapDirectCreditCardPaymentStrategy\n> = (paymentIntegrationService) =>\n new BlueSnapDirectCreditCardPaymentStrategy(\n paymentIntegrationService,\n new BlueSnapDirectHostedForm(\n new BlueSnapDirectScriptLoader(getScriptLoader()),\n new BluesnapDirectNameOnCardInput(),\n new BlueSnapHostedInputValidator(),\n ),\n );\n\nexport default toResolvableModule(createBlueSnapDirectCreditCardPaymentStrategy, [\n { id: 'credit_card', gateway: 'bluesnapdirect' },\n]);\n","import {\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentIntegrationService,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport assertBlueSnapDirectEcpInstrument from './is-bluesnap-direct-ecp-instrument';\n\nexport default class BlueSnapDirectEcpPaymentStrategy implements PaymentStrategy {\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n async execute({ payment }: OrderRequestBody): Promise {\n assertBlueSnapDirectEcpInstrument(payment?.paymentData);\n\n await this._paymentIntegrationService.submitOrder();\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: {\n formattedPayload: {\n ecp: {\n account_number: payment.paymentData.accountNumber,\n account_type: payment.paymentData.accountType,\n shopper_permission: payment.paymentData.shopperPermission,\n routing_number: payment.paymentData.routingNumber,\n },\n },\n },\n });\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n}\n","import {\n BlueSnapDirectEcpInstrument,\n OrderPaymentRequestBody,\n PaymentArgumentInvalidError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nfunction isBlueSnapDirectEcpInstrument(\n data: OrderPaymentRequestBody['paymentData'],\n): data is BlueSnapDirectEcpInstrument {\n if (data === undefined) {\n return false;\n }\n\n return (\n 'accountNumber' in data &&\n 'accountType' in data &&\n 'shopperPermission' in data &&\n 'routingNumber' in data\n );\n}\n\nexport default function assertBlueSnapDirectEcpInstrument(\n data: OrderPaymentRequestBody['paymentData'],\n): asserts data is BlueSnapDirectEcpInstrument {\n if (!isBlueSnapDirectEcpInstrument(data)) {\n throw new PaymentArgumentInvalidError();\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BlueSnapDirectEcpPaymentStrategy from './bluesnap-direct-ecp-payment-strategy';\n\nconst createBlueSnapDirectEcpPaymentStrategy: PaymentStrategyFactory<\n BlueSnapDirectEcpPaymentStrategy\n> = (paymentIntegrationService) => new BlueSnapDirectEcpPaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createBlueSnapDirectEcpPaymentStrategy, [\n { id: 'ecp', gateway: 'bluesnapdirect' },\n]);\n","import { noop } from 'lodash';\n\nimport {\n CancellablePromise,\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { createIframe } from './bluesnap-direct-iframe-creator';\nimport isBlueSnapDirectRedirectResponseProviderData from './is-bluesnap-direct-provider-data';\nimport {\n BlueSnapDirectAPMInitializeOptions,\n BlueSnapDirectRedirectResponse,\n WithBlueSnapDirectAPMPaymentInitializeOptions,\n} from './types';\n\nconst IFRAME_NAME = 'bluesnap_direct_hosted_payment_page';\n\nexport default class BlueSnapDirectAPMPaymentStrategy implements PaymentStrategy {\n private _initializeOptions?: BlueSnapDirectAPMInitializeOptions;\n\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBlueSnapDirectAPMPaymentInitializeOptions,\n ): Promise {\n const { bluesnapdirect } = options;\n\n if (!bluesnapdirect) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bluesnapdirect\" argument is not provided.',\n );\n }\n\n this._initializeOptions = bluesnapdirect;\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentInitializeOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!this._initializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n try {\n await this._paymentIntegrationService.submitPayment({\n methodId: payment.methodId,\n });\n } catch (error) {\n if (this._isBlueSnapDirectRedirectResponse(error)) {\n const providerData: unknown = JSON.parse(error.body.provider_data);\n\n if (isBlueSnapDirectRedirectResponseProviderData(providerData)) {\n const providerDataQuery = new URLSearchParams(providerData).toString();\n\n const frameUrl = `${error.body.additional_action_required.data.redirect_url}&${providerDataQuery}`;\n const { onLoad, style } = this._initializeOptions;\n const frame = createIframe(IFRAME_NAME, frameUrl, style);\n\n const promise = new CancellablePromise(new Promise(noop));\n\n onLoad(frame, () => promise.cancel(new PaymentMethodCancelledError()));\n\n return Promise.reject();\n }\n }\n\n return Promise.reject(error);\n }\n }\n\n async finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private _isBlueSnapDirectRedirectResponse(\n response: unknown,\n ): response is BlueSnapDirectRedirectResponse {\n if (typeof response !== 'object' || response === null) {\n return false;\n }\n\n const partialResponse: Partial = response;\n\n if (!partialResponse.body) {\n return false;\n }\n\n const partialBody: Partial = partialResponse.body;\n\n return (\n partialBody.status === 'additional_action_required' &&\n !!partialBody.additional_action_required?.data.redirect_url &&\n typeof partialBody.provider_data === 'string'\n );\n }\n}\n","import { BlueSnapDirectRedirectResponseProviderData } from './types';\n\nexport default function isBlueSnapDirectRedirectResponseProviderData(\n value: unknown,\n): value is BlueSnapDirectRedirectResponseProviderData {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n\n const partialValue: Partial = value;\n\n if (!partialValue.merchantid) {\n return false;\n }\n\n return typeof partialValue.merchantid === 'string';\n}\n","import { BlueSnapDirectStyleProps } from './types';\n\nexport const createIframe = (\n name: string,\n src: string,\n style?: BlueSnapDirectStyleProps,\n): HTMLIFrameElement => {\n const iframe = document.createElement('iframe');\n\n iframe.setAttribute(\n 'sandbox',\n 'allow-top-navigation allow-scripts allow-forms allow-same-origin',\n );\n\n iframe.src = src;\n\n iframe.name = name;\n\n if (style) {\n const { border, height, width } = style;\n\n iframe.style.border = border || '';\n iframe.style.height = height || '';\n iframe.style.width = width || '';\n }\n\n return iframe;\n};\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BlueSnapDirectAPMPaymentStrategy from './bluesnap-direct-apm-payment-strategy';\n\nconst createBlueSnapDirectAPMPaymentStrategy: PaymentStrategyFactory<\n BlueSnapDirectAPMPaymentStrategy\n> = (paymentIntegrationService) => new BlueSnapDirectAPMPaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createBlueSnapDirectAPMPaymentStrategy, [\n { gateway: 'bluesnapdirect' },\n]);\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"local-storage-fallback\");","import { isObject } from 'lodash';\n\nimport { LineItemMap } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ExtraItemsData } from './extra-items-data';\n\ntype StorageFallback = Pick;\n\nconst ORDER_ITEMS_STORAGE_KEY = 'ORDER_ITEMS';\n\nfunction isExtraItemsData(itemsData: unknown): itemsData is ExtraItemsData {\n if (!isObject(itemsData)) {\n return false;\n }\n\n const hasNotExtraItems = Object.values(itemsData).some(\n (item) => !isObject(item) || !('brand' in item) || !('category' in item),\n );\n\n return Boolean(!hasNotExtraItems);\n}\n\nexport default class AnalyticsExtraItemsManager {\n constructor(private storage: StorageFallback) {}\n\n saveExtraItemsData(id: string, lineItems: LineItemMap): ExtraItemsData {\n const data = [...lineItems.physicalItems, ...lineItems.digitalItems].reduce(\n (result, item) => {\n result[item.productId] = {\n brand: item.brand ? item.brand : '',\n category: item.categoryNames ? item.categoryNames.join(', ') : '',\n };\n\n return result;\n },\n {},\n );\n\n try {\n this.storage.setItem(this.getStorageKey(id), JSON.stringify(data));\n\n return data;\n } catch (err) {\n return {};\n }\n }\n\n readExtraItemsData(id: string): ExtraItemsData | null {\n try {\n const item = this.storage.getItem(this.getStorageKey(id));\n\n if (!item) {\n return null;\n }\n\n const data: unknown = JSON.parse(item);\n\n return isExtraItemsData(data) ? data : null;\n } catch (err) {\n return null;\n }\n }\n\n clearExtraItemData(id: string): void {\n try {\n this.storage.removeItem(this.getStorageKey(id));\n } catch (err) {\n // silently ignore the failure\n }\n }\n\n private getStorageKey(id: string): string {\n return id ? `${ORDER_ITEMS_STORAGE_KEY}_${id}` : '';\n }\n}\n","import AnalyticsTrackerWindow from './analytics-tracker-window';\n\nexport function isAnalyticsTrackerWindow(window: Window): window is AnalyticsTrackerWindow {\n return Boolean(window.hasOwnProperty('analytics'));\n}\n","import { WithAccountCreation } from './payment';\n\nexport default function isWithAccountCreation(\n paymentData: unknown,\n): paymentData is WithAccountCreation {\n return (\n typeof paymentData === 'object' &&\n paymentData !== null &&\n 'shouldCreateAccount' in paymentData\n );\n}\n","import { PaymentErrorData, StandardError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class BoltError extends StandardError {\n body: { errors: PaymentErrorData[] };\n\n constructor(public errorCode: string) {\n super();\n\n this.name = 'BoltPaymentsFieldError';\n this.type = 'bolt_payments_field_error';\n this.body = { errors: [BoltError.getError(errorCode)] };\n }\n\n private static getError(errorCode: string): PaymentErrorData {\n switch (errorCode) {\n case '1000':\n case '2000':\n case '3000':\n return { code: 'invalid_number' };\n\n case '1001':\n case '2001':\n case '3001':\n return { code: 'invalid_expiry_date' };\n\n case '1002':\n case '2002':\n return { code: 'invalid_cvc' };\n\n case '1003':\n return { code: 'invalid_zip' };\n\n case '2003':\n return { code: 'incorrect_zip' };\n\n default:\n return { code: 'general_error' };\n }\n }\n}\n","import {\n AnalyticsExtraItemsManager,\n isAnalyticsTrackerWindow,\n} from '@bigcommerce/checkout-sdk/analytics';\nimport {\n InvalidArgumentError,\n isWithAccountCreation,\n MissingDataError,\n MissingDataErrorType,\n NonceInstrument,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodCancelledError,\n PaymentMethodFailedError,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n WithAccountCreation,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n BoltCheckout,\n BoltEmbedded,\n BoltEmbeddedTokenize,\n BoltEmbededField,\n BoltPaymentMethod,\n BoltTransaction,\n} from './bolt';\nimport BoltError from './bolt-error';\nimport { WithBoltPaymentInitializeOptions } from './bolt-payment-initialize-options';\nimport BoltScriptLoader from './bolt-script-loader';\nimport { isBoltPaymentData } from './is-bolt-payment-data';\n\nexport default class BoltPaymentStrategy implements PaymentStrategy {\n private boltClient?: BoltCheckout;\n private boltEmbedded?: BoltEmbedded;\n private embeddedField?: BoltEmbededField;\n private useBoltClient = false;\n private useBoltEmbedded = false;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private boltScriptLoader: BoltScriptLoader,\n private analyticsExtraItemsManager: AnalyticsExtraItemsManager,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBoltPaymentInitializeOptions,\n ): Promise {\n const { bolt, methodId } = options;\n const { containerId, onPaymentSelect, useBigCommerceCheckout } = bolt || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!useBigCommerceCheckout) {\n // info: calling loadBoltClient method without providing any params is necessary for Bolt Full Checkout and Fraud Protection\n this.boltClient = await this.boltScriptLoader.loadBoltClient();\n\n return;\n }\n\n const paymentMethod: BoltPaymentMethod = this.paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(options.methodId);\n\n const { initializationData, config } = paymentMethod;\n const { publishableKey, developerConfig, embeddedOneClickEnabled } =\n initializationData || {};\n const { testMode } = config;\n\n if (!publishableKey) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this.boltClient = await this.boltScriptLoader.loadBoltClient(\n publishableKey,\n testMode,\n developerConfig,\n );\n\n this.useBoltClient = !embeddedOneClickEnabled;\n this.useBoltEmbedded = !!embeddedOneClickEnabled;\n\n if (this.useBoltEmbedded) {\n if (!containerId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bolt.containerId\" argument is not provided.',\n );\n }\n\n if (!onPaymentSelect) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.bolt.onPaymentSelect\" argument is not provided.',\n );\n }\n\n this.boltEmbedded = await this.boltScriptLoader.loadBoltEmbedded(\n publishableKey,\n testMode,\n developerConfig,\n );\n\n this.mountBoltEmbeddedField(containerId);\n onPaymentSelect(await this.hasBoltAccount());\n }\n }\n\n deinitialize(): Promise {\n this.embeddedField?.unmount();\n\n this.boltClient = undefined;\n this.boltEmbedded = undefined;\n\n return Promise.resolve();\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n this.setExtraItemsForAnalytics();\n\n const { payment, ...order } = payload;\n const { methodId, paymentData } = payment || {};\n let paymentPayload;\n\n if (!payload.payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!methodId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (!paymentData || !isBoltPaymentData(paymentData)) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n await this.paymentIntegrationService.submitOrder(order, options);\n\n if (this.useBoltClient) {\n paymentPayload = await this.getBoltClientPaymentPayload(methodId, paymentData, options);\n } else if (this.useBoltEmbedded) {\n paymentPayload = await this.getBoltEmbeddedPaymentPayload(methodId, paymentData);\n } else {\n paymentPayload = await this.getBoltFullCheckoutPaymentPayload(methodId, paymentData);\n }\n\n await this.paymentIntegrationService.submitPayment(paymentPayload);\n }\n\n private async getBoltClientPaymentPayload(\n methodId: string,\n paymentData: NonceInstrument,\n options?: PaymentRequestOptions,\n ): Promise {\n await this.paymentIntegrationService.loadPaymentMethod(methodId, options);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const orderToken = paymentMethod.clientToken;\n const { isStoreCreditApplied } = state.getCheckoutOrThrow();\n const { shouldSaveInstrument } = paymentData;\n const boltClient = this.getBoltClientOrThrow();\n\n await this.paymentIntegrationService.applyStoreCredit(isStoreCreditApplied);\n\n if (!orderToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const boltTransaction: BoltTransaction = await new Promise((resolve, reject) => {\n const onSuccess = (transaction: BoltTransaction, callback: () => void) => {\n if (!transaction.reference) {\n reject(\n new PaymentMethodFailedError(\n 'Unable to proceed because transaction reference is unavailable. Please try again later.',\n ),\n );\n } else {\n resolve(transaction);\n }\n\n callback();\n };\n\n const onClose = () => {\n reject(new PaymentMethodCancelledError());\n };\n\n const callbacks = {\n success: onSuccess,\n close: onClose,\n };\n\n boltClient.configure({ orderToken }, {}, callbacks).open();\n });\n\n return {\n methodId,\n paymentData: {\n nonce: boltTransaction.reference,\n shouldSaveInstrument,\n },\n };\n }\n\n private async getBoltEmbeddedPaymentPayload(\n methodId: string,\n paymentData: WithAccountCreation,\n ): Promise {\n if (!isWithAccountCreation(paymentData)) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n const tokenizeResult = this.validateTokenizeResultOrThrow(\n await this.embeddedField?.tokenize(),\n );\n\n return {\n methodId,\n paymentData: {\n formattedPayload: {\n credit_card_token: {\n token: tokenizeResult.token,\n last_four_digits: tokenizeResult.last4,\n iin: tokenizeResult.bin,\n expiration_month: +tokenizeResult.expiration.split('-')[1],\n expiration_year: +tokenizeResult.expiration.split('-')[0],\n },\n provider_data: {\n create_account: !!paymentData.shouldCreateAccount,\n embedded_checkout: true,\n },\n },\n },\n };\n }\n\n private async getBoltFullCheckoutPaymentPayload(\n methodId: string,\n paymentData: NonceInstrument,\n ): Promise {\n await this.setBoltOrderId();\n\n const boltClient = this.getBoltClientOrThrow();\n const transactionReference = await boltClient.getTransactionReference();\n\n if (!transactionReference) {\n throw new PaymentMethodInvalidError();\n }\n\n return {\n methodId,\n paymentData: {\n ...paymentData,\n nonce: transactionReference,\n },\n };\n }\n\n private getBoltClientOrThrow(): BoltCheckout {\n if (!this.boltClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.boltClient;\n }\n\n private getBoltEmbeddedOrThrow() {\n if (!this.boltEmbedded) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.boltEmbedded;\n }\n\n private async hasBoltAccount(): Promise {\n const state = this.paymentIntegrationService.getState();\n const customer = state.getCustomer();\n const billingAddress = state.getBillingAddress();\n const email = customer?.email || billingAddress?.email || '';\n const boltClient = this.getBoltClientOrThrow();\n\n try {\n return await boltClient.hasBoltAccount(email);\n } catch {\n throw new PaymentMethodInvalidError();\n }\n }\n\n private async setBoltOrderId() {\n const order = this.paymentIntegrationService.getState().getOrderOrThrow();\n const boltClient = this.getBoltClientOrThrow();\n\n try {\n await boltClient.setOrderId(order.orderId);\n } catch {\n throw new PaymentMethodInvalidError();\n }\n }\n\n private mountBoltEmbeddedField(containerId: string) {\n const boltEmbedded = this.getBoltEmbeddedOrThrow();\n const styles = { backgroundColor: '#fff' };\n const embeddedField = boltEmbedded.create('payment_field', {\n styles,\n renderSeparateFields: true,\n });\n\n embeddedField.mount(`#${containerId}`);\n\n this.embeddedField = embeddedField;\n }\n\n private validateTokenizeResultOrThrow(\n tokenizeResult?: BoltEmbeddedTokenize | Error,\n ): BoltEmbeddedTokenize {\n if (!tokenizeResult) {\n throw new PaymentMethodInvalidError();\n }\n\n if (tokenizeResult instanceof Error) {\n throw new BoltError(tokenizeResult.message);\n }\n\n const { token, last4, bin, expiration } = tokenizeResult;\n const lastFourDigits = +last4;\n const iin = +bin;\n const expirationMonth = +`${expiration}`.split('-')[1];\n const expirationYear = +`${expiration}`.split('-')[0];\n\n if (\n !token ||\n Number.isNaN(lastFourDigits) ||\n Number.isNaN(iin) ||\n Number.isNaN(expirationMonth) ||\n Number.isNaN(expirationYear)\n ) {\n throw new PaymentArgumentInvalidError();\n }\n\n return tokenizeResult;\n }\n\n private setExtraItemsForAnalytics() {\n const state = this.paymentIntegrationService.getState();\n const storeConfig = state.getStoreConfigOrThrow();\n const cart = state.getCartOrThrow();\n\n if (storeConfig.checkoutSettings.isAnalyticsEnabled && isAnalyticsTrackerWindow(window)) {\n const { id, lineItems } = cart;\n\n this.analyticsExtraItemsManager.saveExtraItemsData(id, lineItems);\n }\n }\n}\n","import { isObject } from 'lodash';\n\nimport { isWithAccountCreation } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BoltPaymentData } from './bolt';\n\nexport function isBoltPaymentData(paymentData: unknown): paymentData is BoltPaymentData {\n return Boolean(\n isObject(paymentData) &&\n ('shouldSaveInstrument' in paymentData ||\n 'nonce' in paymentData ||\n isWithAccountCreation(paymentData)),\n );\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\nimport localStorageFallback from 'local-storage-fallback';\n\nimport { AnalyticsExtraItemsManager } from '@bigcommerce/checkout-sdk/analytics';\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BoltPaymentStrategy from './bolt-payment-strategy';\nimport BoltScriptLoader from './bolt-script-loader';\n\nconst createBoltPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new BoltPaymentStrategy(\n paymentIntegrationService,\n new BoltScriptLoader(getScriptLoader()),\n new AnalyticsExtraItemsManager(localStorageFallback),\n );\n};\n\nexport default toResolvableModule(createBoltPaymentStrategy, [{ id: 'bolt' }]);\n","import {\n PaymentInstrument,\n WithBankAccountInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default function isUsBankAccountInstrumentLike(\n instrument?: PaymentInstrument,\n): instrument is WithBankAccountInstrument {\n if (!instrument) {\n return false;\n }\n\n return (\n 'accountNumber' in instrument &&\n 'routingNumber' in instrument &&\n 'ownershipType' in instrument &&\n 'accountType' in instrument\n );\n}\n","import {\n InvalidArgumentError,\n isHostedInstrumentLike,\n isVaultedInstrument,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n Payment,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStrategy,\n WithBankAccountInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BankAccountSuccessPayload, BraintreeBankAccount } from '../braintree';\nimport BraintreeIntegrationService from '../braintree-integration-service';\nimport isBraintreeError from '../is-braintree-error';\nimport isUsBankAccountInstrumentLike from '../is-us-bank-account-instrument-like';\n\nimport { WithBraintreePaypalAchPaymentInitializeOptions } from './braintree-paypal-ach-initialize-options';\n\nexport default class BraintreePaypalAchPaymentStrategy implements PaymentStrategy {\n private usBankAccount?: BraintreeBankAccount;\n private getMandateText?: () => string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeIntegrationService: BraintreeIntegrationService,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreePaypalAchPaymentInitializeOptions,\n ): Promise {\n const { getMandateText } = options.braintreeach || {};\n\n if (!options.methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n this.getMandateText = getMandateText;\n\n await this.paymentIntegrationService.loadPaymentMethod(options.methodId);\n\n const state = this.paymentIntegrationService.getState();\n\n const paymentMethod = state.getPaymentMethodOrThrow(options.methodId);\n\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n try {\n this.braintreeIntegrationService.initialize(paymentMethod.clientToken);\n this.usBankAccount = await this.braintreeIntegrationService.getUsBankAccount();\n } catch (error) {\n this.handleError(error);\n }\n }\n\n async execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const isSubmittingWithVaultingInstrument = isVaultedInstrument(payment.paymentData || {});\n\n const nonce = isSubmittingWithVaultingInstrument\n ? await this.tokenizePaymentForVaultedInstrument(payment)\n : await this.tokenizePayment(payment);\n\n const submitPaymentPayload = isSubmittingWithVaultingInstrument\n ? await this.preparePaymentDataForVaultedInstrument(nonce, payment)\n : await this.preparePaymentData(nonce, payment);\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paymentIntegrationService.submitPayment(submitPaymentPayload);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n this.getMandateText = undefined;\n\n return Promise.resolve();\n }\n\n private async preparePaymentData(\n nonce: string | null,\n payment: OrderPaymentRequestBody,\n ): Promise {\n const { paymentData = {} } = payment;\n\n if (!isUsBankAccountInstrumentLike(paymentData)) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const sessionId = await this.braintreeIntegrationService.getSessionId();\n\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument, routingNumber, accountNumber } =\n paymentData;\n\n const paymentPayload = {\n formattedPayload: {\n vault_payment_instrument: shouldSaveInstrument || null,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n device_info: sessionId || null,\n tokenized_bank_account: {\n issuer: routingNumber,\n masked_account_number: accountNumber.substr(-4),\n token: nonce,\n },\n },\n };\n\n return {\n methodId: payment.methodId,\n paymentData: paymentPayload,\n };\n }\n\n private async preparePaymentDataForVaultedInstrument(\n nonce: string | null,\n payment: OrderPaymentRequestBody,\n ): Promise {\n const { paymentData = {} } = payment;\n\n if (!isVaultedInstrument(paymentData) || !isHostedInstrumentLike(paymentData)) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const sessionId = await this.braintreeIntegrationService.getSessionId();\n\n return {\n methodId: payment.methodId,\n paymentData: {\n deviceSessionId: sessionId,\n instrumentId: paymentData.instrumentId,\n shouldSetAsDefaultInstrument: paymentData.shouldSetAsDefaultInstrument,\n ...(nonce && { nonce }),\n },\n };\n }\n\n private async tokenizePayment({ paymentData }: OrderPaymentRequestBody): Promise {\n const usBankAccount = this.getUsBankAccountOrThrow();\n\n if (!isUsBankAccountInstrumentLike(paymentData)) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const mandateText = isVaultedInstrument(paymentData)\n ? 'The data are used for stored instrument verification'\n : typeof this.getMandateText === 'function' && this.getMandateText();\n\n if (!mandateText) {\n throw new InvalidArgumentError(\n 'Unable to proceed because getMandateText is not provided or returned undefined value.',\n );\n }\n\n try {\n const { nonce } = await usBankAccount.tokenize({\n bankDetails: this.getBankDetails(paymentData),\n mandateText,\n });\n\n return nonce;\n } catch (error) {\n this.handleError(error);\n }\n }\n\n private async tokenizePaymentForVaultedInstrument(\n payment: OrderPaymentRequestBody,\n ): Promise {\n const { methodId, paymentData = {} } = payment;\n\n const state = this.paymentIntegrationService.getState();\n const { config } = state.getPaymentMethodOrThrow(methodId);\n\n if (!config.isVaultingEnabled) {\n throw new InvalidArgumentError(\n 'Vaulting is disabled but a vaulted instrument was being used for this transaction',\n );\n }\n\n const shouldVerifyVaultingInstrument = isUsBankAccountInstrumentLike(paymentData);\n\n return shouldVerifyVaultingInstrument ? this.tokenizePayment(payment) : null;\n }\n\n private getBankDetails(paymentData: WithBankAccountInstrument): BankAccountSuccessPayload {\n const state = this.paymentIntegrationService.getState();\n const billingAddress = state.getBillingAddressOrThrow();\n\n const ownershipType = paymentData.ownershipType.toLowerCase();\n const accountType = paymentData.accountType.toLowerCase();\n\n return {\n accountNumber: paymentData.accountNumber,\n routingNumber: paymentData.routingNumber,\n ownershipType,\n ...(ownershipType === 'personal'\n ? {\n firstName: paymentData.firstName,\n lastName: paymentData.lastName,\n }\n : {\n businessName: paymentData.businessName,\n }),\n accountType,\n billingAddress: {\n streetAddress: billingAddress.address1,\n extendedAddress: billingAddress.address2,\n locality: billingAddress.city,\n region: billingAddress.stateOrProvinceCode,\n postalCode: billingAddress.postalCode,\n },\n };\n }\n\n private getUsBankAccountOrThrow(): BraintreeBankAccount {\n if (!this.usBankAccount) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.usBankAccount;\n }\n\n private handleError(error: unknown): never {\n if (!isBraintreeError(error)) {\n throw error;\n }\n\n throw new PaymentMethodFailedError(error.message);\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { BraintreeHostWindow } from '../braintree';\nimport BraintreeIntegrationService from '../braintree-integration-service';\nimport BraintreeScriptLoader from '../braintree-script-loader';\n\nimport BraintreeAchPaymentStrategy from './braintree-paypal-ach-payment-strategy';\n\nconst createBraintreePaypalAchPaymentStrategy: PaymentStrategyFactory<\n BraintreeAchPaymentStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n braintreeHostWindow,\n );\n\n return new BraintreeAchPaymentStrategy(paymentIntegrationService, braintreeIntegrationService);\n};\n\nexport default toResolvableModule(createBraintreePaypalAchPaymentStrategy, [\n { id: 'braintreeach' },\n]);\n","import {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport BraintreeIntegrationService from '../braintree-integration-service';\nimport {\n BraintreeLocalMethods,\n LocalPaymentInstance,\n LocalPaymentsPayload,\n onPaymentStartData,\n StartPaymentError,\n WithBraintreeLocalMethodsPaymentInitializeOptions,\n} from './braintree-local-methods-options';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nexport default class BraintreeLocalMethodsPaymentStrategy implements PaymentStrategy {\n private orderId?: string;\n private localPaymentInstance?: LocalPaymentInstance;\n private braintreeLocalMethods?: BraintreeLocalMethods;\n private loadingIndicatorContainer?: string;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private braintreeIntegrationService: BraintreeIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithBraintreeLocalMethodsPaymentInitializeOptions,\n ): Promise {\n const { gatewayId, methodId, braintreelocalmethods } = options;\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.gatewayId\" argument is not provided.',\n );\n }\n\n if (!braintreelocalmethods) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreelocalmethods\" argument is not provided.`,\n );\n }\n\n this.braintreeLocalMethods = braintreelocalmethods;\n\n this.loadingIndicatorContainer = braintreelocalmethods.container.split('#')[1];\n\n await this.paymentIntegrationService.loadPaymentMethod(gatewayId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(gatewayId);\n const { merchantId } = paymentMethod.config;\n\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n try {\n this.braintreeIntegrationService.initialize(paymentMethod.clientToken);\n await this.braintreeIntegrationService.loadBraintreeLocalMethods(\n this.getLocalPaymentInstance.bind(this),\n merchantId || '',\n );\n } catch (error: unknown) {\n this.handleError(error);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n this.orderId = undefined;\n this.toggleLoadingIndicator(false);\n\n return Promise.resolve();\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const sessionId = await this.braintreeIntegrationService.getSessionId();\n const billing = state.getBillingAddressOrThrow();\n const { firstName, lastName, countryCode } = billing;\n const { baseAmount, currency, email, lineItems } = cart;\n const isShippingRequired = lineItems.physicalItems.length > 0;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n this.toggleLoadingIndicator(true);\n\n if (!this.localPaymentInstance) {\n throw new PaymentMethodInvalidError();\n }\n\n return new Promise((resolve, reject) => {\n this.localPaymentInstance?.startPayment(\n {\n paymentType: payment.methodId,\n amount: baseAmount,\n fallback: {\n url: 'url-placeholder',\n buttonText: 'button placeholder',\n },\n currencyCode: currency.code,\n shippingAddressRequired: isShippingRequired,\n email,\n givenName: firstName,\n surname: lastName,\n address: {\n countryCode,\n },\n onPaymentStart: (data: onPaymentStartData, start: () => void) => {\n // Call start to initiate the popup\n this.orderId = data.paymentId;\n start();\n },\n },\n async (\n startPaymentError: StartPaymentError | null,\n payloadData: LocalPaymentsPayload,\n ) => {\n if (startPaymentError) {\n if (startPaymentError.code !== 'LOCAL_PAYMENT_WINDOW_CLOSED') {\n reject(() => this.handleError(startPaymentError));\n }\n this.toggleLoadingIndicator(false);\n reject();\n } else {\n if (!this.orderId) {\n throw PaymentMethodInvalidError;\n }\n\n const paymentData = {\n formattedPayload: {\n device_info: sessionId || null,\n method: payment.methodId,\n [`${payment.methodId}_account`]: {\n email: cart.email,\n token: payloadData.nonce,\n order_id: this.orderId,\n },\n vault_payment_instrument: null,\n set_as_default_stored_instrument: null,\n },\n };\n\n try {\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paymentIntegrationService.submitPayment({\n methodId: payment.methodId,\n paymentData,\n });\n resolve();\n } catch (error: unknown) {\n reject(() => this.handleError(error));\n }\n }\n },\n );\n });\n }\n\n private getLocalPaymentInstance(localPaymentInstance: LocalPaymentInstance) {\n if (!this.localPaymentInstance) {\n this.localPaymentInstance = localPaymentInstance;\n }\n }\n\n /**\n *\n * Loading Indicator methods\n *\n * */\n private toggleLoadingIndicator(isLoading: boolean): void {\n if (isLoading && this.loadingIndicatorContainer) {\n this.loadingIndicator.show(this.loadingIndicatorContainer);\n } else {\n this.loadingIndicator.hide();\n }\n }\n\n private handleError(error: unknown) {\n const { onError } = this.braintreeLocalMethods || {};\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n}\n","import { LoadingIndicatorStyles } from './loading-indicator-styles';\n\nconst DEFAULT_STYLES: LoadingIndicatorStyles = {\n size: 70,\n color: '#d9d9d9',\n backgroundColor: '#ffffff',\n};\n\nconst ROTATION_ANIMATION = 'embedded-checkout-loading-indicator-rotation';\n\nexport default class LoadingIndicator {\n private container: HTMLElement;\n private indicator: HTMLElement;\n private styles: LoadingIndicatorStyles;\n\n constructor(options?: { styles?: LoadingIndicatorStyles }) {\n this.styles = { ...DEFAULT_STYLES, ...(options && options.styles) };\n\n this.defineAnimation();\n\n this.container = this.buildContainer();\n this.indicator = this.buildIndicator();\n\n this.container.appendChild(this.indicator);\n }\n\n show(parentId?: string): void {\n if (parentId) {\n const parent = document.getElementById(parentId);\n\n if (!parent) {\n throw new Error(\n 'Unable to attach the loading indicator because the parent ID is not valid.',\n );\n }\n\n parent.appendChild(this.container);\n }\n\n this.container.style.visibility = 'visible';\n this.container.style.opacity = '1';\n }\n\n hide(): void {\n const handleTransitionEnd = () => {\n this.container.style.visibility = 'hidden';\n\n this.container.removeEventListener('transitionend', handleTransitionEnd);\n };\n\n this.container.addEventListener('transitionend', handleTransitionEnd);\n\n this.container.style.opacity = '0';\n }\n\n private buildContainer(): HTMLElement {\n const container = document.createElement('div');\n\n container.style.display = 'block';\n container.style.bottom = '0';\n container.style.left = '0';\n container.style.height = '100%';\n container.style.width = '100%';\n container.style.position = 'absolute';\n container.style.right = '0';\n container.style.top = '0';\n container.style.transition = 'all 250ms ease-out';\n container.style.opacity = '0';\n\n return container;\n }\n\n private buildIndicator(): HTMLElement {\n const indicator = document.createElement('div');\n\n indicator.style.display = 'block';\n indicator.style.width = `${this.styles.size}px`;\n indicator.style.height = `${this.styles.size}px`;\n indicator.style.borderRadius = `${this.styles.size}px`;\n indicator.style.border = 'solid 1px';\n indicator.style.borderColor = `${this.styles.backgroundColor} ${this.styles.backgroundColor} ${this.styles.color} ${this.styles.color}`;\n indicator.style.margin = '0 auto';\n indicator.style.position = 'absolute';\n indicator.style.left = '0';\n indicator.style.right = '0';\n indicator.style.top = '50%';\n indicator.style.transform = 'translateY(-50%) rotate(0deg)';\n indicator.style.transformStyle = 'preserve-3d';\n indicator.style.animation = `${ROTATION_ANIMATION} 500ms infinite cubic-bezier(0.69, 0.31, 0.56, 0.83)`;\n\n return indicator;\n }\n\n private defineAnimation(): void {\n // In order to define CSS animation, we need to insert a stylesheet into the host frame.\n // We only have to do it once.\n if (document.getElementById(ROTATION_ANIMATION)) {\n return;\n }\n\n const style = document.createElement('style');\n\n style.id = ROTATION_ANIMATION;\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n document.head?.appendChild(style);\n\n if (style.sheet instanceof CSSStyleSheet) {\n // We need to provide the 2nd parameter for IE11, even though it is\n // 0 by default for all other browsers.\n style.sheet.insertRule(\n `\n @keyframes ${ROTATION_ANIMATION} {\n 0% { transform: translateY(-50%) rotate(0deg); }\n 100% { transform: translateY(-50%) rotate(360deg); }\n }\n `,\n 0,\n );\n }\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BraintreeLocalMethodsPaymentStrategy from './braintree-local-methods-payment-strategy';\nimport { BraintreeHostWindow } from '../braintree';\nimport BraintreeIntegrationService from '../braintree-integration-service';\nimport BraintreeScriptLoader from '../braintree-script-loader';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nconst createBraintreeLocalMethodsPaymentStrategy: PaymentStrategyFactory<\n BraintreeLocalMethodsPaymentStrategy\n> = (paymentIntegrationService) => {\n const braintreeHostWindow: BraintreeHostWindow = window;\n const braintreeIntegrationService = new BraintreeIntegrationService(\n new BraintreeScriptLoader(getScriptLoader(), braintreeHostWindow),\n braintreeHostWindow,\n );\n\n return new BraintreeLocalMethodsPaymentStrategy(\n paymentIntegrationService,\n braintreeIntegrationService,\n new LoadingIndicator({ styles: { backgroundColor: 'black' } }),\n );\n};\n\nexport default toResolvableModule(createBraintreeLocalMethodsPaymentStrategy, [\n { gateway: 'braintreelocalmethods' },\n]);\n","import { isNil, values } from 'lodash';\n\nimport {\n HostedForm,\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithCreditCardPaymentInitializeOptions } from './credit-card-payment-initialize-options';\n\nexport default class CreditCardPaymentStrategy implements PaymentStrategy {\n protected _hostedForm?: HostedForm;\n protected _shouldRenderHostedForm?: boolean;\n\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n return this._isHostedPaymentFormEnabled(\n payload.payment?.methodId,\n payload.payment?.gatewayId,\n ) && this._shouldRenderHostedForm\n ? this._executeWithHostedForm(payload, options)\n : this._executeWithoutHostedForm(payload, options);\n }\n\n initialize(\n options?: PaymentInitializeOptions & WithCreditCardPaymentInitializeOptions,\n ): Promise {\n if (\n !this._isHostedPaymentFormEnabled(options?.methodId, options?.gatewayId) ||\n !this._isHostedFieldAvailable(options)\n ) {\n this._shouldRenderHostedForm = false;\n\n return Promise.resolve();\n }\n\n const formOptions = options && options.creditCard && options.creditCard.form;\n const state = this._paymentIntegrationService.getState();\n const { paymentSettings: { bigpayBaseUrl: host = '' } = {} } =\n state.getStoreConfigOrThrow();\n\n if (!formOptions) {\n throw new InvalidArgumentError();\n }\n\n const form = this._paymentIntegrationService.createHostedForm(host, formOptions);\n\n return form.attach().then(() => {\n this._shouldRenderHostedForm = true;\n this._hostedForm = form;\n\n return Promise.resolve();\n });\n }\n\n deinitialize(): Promise {\n if (this._hostedForm) {\n this._hostedForm.detach();\n }\n\n return Promise.resolve();\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n protected async _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment && payment.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n await this._paymentIntegrationService.submitPayment({ ...payment, paymentData });\n }\n\n protected async _executeWithHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!payment || !payment.methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n await form.validate().then(() => form.submit(payment));\n }\n\n protected _isHostedPaymentFormEnabled(methodId?: string, gatewayId?: string): boolean {\n if (!methodId) {\n return false;\n }\n\n const state = this._paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId, gatewayId);\n\n return paymentMethod.config.isHostedFormEnabled === true;\n }\n\n private _isHostedFieldAvailable(\n options?: PaymentInitializeOptions & WithCreditCardPaymentInitializeOptions,\n ): boolean {\n return !values(options && options.creditCard && options.creditCard.form.fields).every(\n isNil,\n );\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport CreditCardPaymentStrategy from './credit-card-payment-strategy';\n\nconst createCreditCardPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new CreditCardPaymentStrategy(paymentIntegrationService);\n};\n\nexport default toResolvableModule(createCreditCardPaymentStrategy, [{ default: true }]);\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n isRequestError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { AdditionalActionRequired, isAdditionalActionRequired } from './is-additional-action';\n\nexport default class ExternalPaymentStrategy implements PaymentStrategy {\n constructor(\n private _formPoster: FormPoster,\n private _paymentIntegrationService: PaymentIntegrationService,\n ) {}\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment && payment.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._paymentIntegrationService.submitOrder(order, options);\n\n try {\n await this._paymentIntegrationService.submitPayment({ ...payment, paymentData });\n } catch (error) {\n if (\n !isRequestError(error) ||\n !isAdditionalActionRequired(error.body) ||\n !this._isAdditionalActionRequired(error.body)\n ) {\n return Promise.reject(error);\n }\n\n const {\n body: {\n additional_action_required: {\n data: { redirect_url },\n },\n },\n } = error;\n\n return new Promise(() => this.redirectUrl(redirect_url));\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n protected redirectUrl(redirect_url: string): void {\n return this._formPoster.postForm(redirect_url, {});\n }\n\n private _isAdditionalActionRequired(body: AdditionalActionRequired): boolean {\n const { additional_action_required, status } = body;\n\n return (\n status === 'additional_action_required' &&\n additional_action_required &&\n additional_action_required.type === 'offsite_redirect'\n );\n }\n}\n","export interface AdditionalActionRequired {\n additional_action_required: {\n data: {\n redirect_url: string;\n };\n type: string;\n };\n status: string;\n}\n\nexport function isAdditionalActionRequired(value: unknown): value is AdditionalActionRequired {\n return typeof value === 'object' && value !== null && 'additional_action_required' in value;\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ExternalPaymentStrategy from './external-payment-strategy';\n\nconst createExternalPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => new ExternalPaymentStrategy(createFormPoster(), paymentIntegrationService);\n\nexport default toResolvableModule(createExternalPaymentStrategy, [{ id: 'laybuy' }]);\n","import {\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class LegacyPaymentStrategy implements PaymentStrategy {\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n await this._paymentIntegrationService.submitOrder(payload, options);\n\n return Promise.resolve();\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport LegacyPaymentStrategy from './legacy-payment-strategy';\n\nconst createLegacyPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => new LegacyPaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createLegacyPaymentStrategy, [{ id: 'testgateway' }]);\n","import { omit } from 'lodash';\n\nimport {\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class NoPaymentDataRequiredPaymentStrategy implements PaymentStrategy {\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n await this._paymentIntegrationService.submitOrder(omit(payload, 'payment'), options);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport NoPaymentDataRequiredPaymentStrategy from './no-payment-data-required-strategy';\n\nconst createNoPaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => new NoPaymentDataRequiredPaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createNoPaymentStrategy, [{ id: 'nopaymentdatarequired' }]);\n","import {\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class OfflinePaymentStrategy implements PaymentStrategy {\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n await this._paymentIntegrationService.submitOrder(\n {\n ...payload,\n payment: payload.payment ? { methodId: payload.payment.methodId } : undefined,\n },\n options,\n );\n\n return Promise.resolve();\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport OfflinePaymentStrategy from './offline-payment-strategy';\n\nconst createOfflinePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => new OfflinePaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createOfflinePaymentStrategy, [{ type: 'PAYMENT_TYPE_OFFLINE' }]);\n","enum PaymentStatusTypes {\n ACKNOWLEDGE = 'ACKNOWLEDGE',\n FINALIZE = 'FINALIZE',\n INITIALIZE = 'INITIALIZE',\n}\n\nexport default PaymentStatusTypes;\n","import {\n isHostedInstrumentLike,\n isVaultedInstrument,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentIntegrationService,\n PaymentRequestOptions,\n PaymentStatusTypes,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nexport default class OffsitePaymentStrategy implements PaymentStrategy {\n constructor(private _paymentIntegrationService: PaymentIntegrationService) {}\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const orderPayload = this._shouldSubmitFullPayload(payment) ? payload : order;\n const paymentData = payment && payment.paymentData;\n const instrumentId =\n (paymentData && isVaultedInstrument(paymentData) && paymentData.instrumentId) ||\n undefined;\n const shouldSaveInstrument =\n (paymentData &&\n isHostedInstrumentLike(paymentData) &&\n paymentData.shouldSaveInstrument) ||\n undefined;\n const shouldSetAsDefaultInstrument =\n (paymentData &&\n isHostedInstrumentLike(paymentData) &&\n paymentData.shouldSetAsDefaultInstrument) ||\n undefined;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId, gatewayId } = payment;\n\n await this._paymentIntegrationService.submitOrder(orderPayload, options);\n await this._paymentIntegrationService.initializeOffsitePayment({\n methodId,\n gatewayId,\n instrumentId,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n });\n }\n\n async finalize(options?: PaymentRequestOptions): Promise {\n const state = this._paymentIntegrationService.getState();\n const order = state.getOrder();\n const status = state.getPaymentStatus();\n\n if (\n order &&\n (status === PaymentStatusTypes.ACKNOWLEDGE || status === PaymentStatusTypes.FINALIZE)\n ) {\n await this._paymentIntegrationService.finalizeOrder(options);\n\n return;\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private _shouldSubmitFullPayload(payment?: OrderPaymentRequestBody): boolean {\n // FIXME: A temporary workaround to support offsite payment methods\n // where their return URL needs to be provided by the core app.\n if (!payment) {\n return false;\n }\n\n return (\n payment.gatewayId === 'adyen' ||\n payment.gatewayId === 'barclaycard' ||\n payment.methodId === 'ccavenuemars'\n );\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport OffsitePaymentStrategy from './offsite-payment-strategy';\n\nconst createOffsitePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => new OffsitePaymentStrategy(paymentIntegrationService);\n\nexport default toResolvableModule(createOffsitePaymentStrategy, [{ type: 'PAYMENT_TYPE_HOSTED' }]);\n","import {\n InvalidArgumentError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n ClickCallbackActions,\n PayPalCommerceButtons,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n} from '../paypal-commerce-types';\n\nimport PayPalCommercePaymentInitializeOptions, {\n WithPayPalCommercePaymentInitializeOptions,\n} from './paypal-commerce-payment-initialize-options';\n\nexport default class PayPalCommercePaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: PayPalCommerceButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithPayPalCommercePaymentInitializeOptions,\n ): Promise {\n const { methodId, paypalcommerce } = options || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!paypalcommerce) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerce\" argument is not provided.`,\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n // Info:\n // The PayPal button and fields should not be rendered when shopper was redirected to Checkout page\n // after using smart payment button on PDP or Cart page. In this case backend returns order id if\n // it is available in checkout session. Therefore, it is not necessary to render PayPal button.\n if (paymentMethod.initializationData?.orderId) {\n this.orderId = paymentMethod.initializationData?.orderId;\n\n return;\n }\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.loadingIndicatorContainer = paypalcommerce.container.split('#')[1];\n\n this.renderButton(methodId, paypalcommerce);\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!this.orderId) {\n throw new PaymentMethodInvalidError();\n }\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paypalCommerceIntegrationService.submitPayment(payment.methodId, this.orderId);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.orderId = undefined;\n\n this.paypalButton?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Button methods/callbacks\n *\n * */\n private renderButton(\n methodId: string,\n paypalcommerce: PayPalCommercePaymentInitializeOptions,\n ): void {\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { buttonStyle } = paymentMethod.initializationData || {};\n\n const { container, onError, onRenderButton, onValidate, submitForm } = paypalcommerce;\n\n const buttonOptions: PayPalCommerceButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(buttonStyle),\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder('paypalcommercecheckout'),\n onClick: (_, actions) => this.handleClick(actions, onValidate),\n onApprove: (data) => this.handleApprove(data, submitForm),\n onCancel: () => this.toggleLoadingIndicator(false),\n onError: (error) => this.handleError(error, onError),\n };\n\n this.paypalButton = paypalSdk.Buttons(buttonOptions);\n\n if (!this.paypalButton.isEligible()) {\n return;\n }\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n this.paypalButton.render(container);\n }\n\n private async handleClick(\n actions: ClickCallbackActions,\n onValidate: PayPalCommercePaymentInitializeOptions['onValidate'],\n ): Promise {\n const { resolve, reject } = actions;\n\n const onValidationPassed = () => {\n this.toggleLoadingIndicator(true);\n\n return resolve();\n };\n\n await onValidate(onValidationPassed, reject);\n }\n\n private handleApprove(\n { orderID }: ApproveCallbackPayload,\n submitForm: PayPalCommercePaymentInitializeOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n submitForm();\n this.toggleLoadingIndicator(false);\n }\n\n private handleError(\n error: Error,\n onError: PayPalCommercePaymentInitializeOptions['onError'],\n ): void {\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n\n /**\n *\n * Loading Indicator methods\n *\n * */\n private toggleLoadingIndicator(isLoading: boolean): void {\n if (isLoading && this.loadingIndicatorContainer) {\n this.loadingIndicator.show(this.loadingIndicatorContainer);\n } else {\n this.loadingIndicator.hide();\n }\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommercePaymentStrategy from './paypal-commerce-payment-strategy';\n\nconst createPayPalCommercePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) =>\n new PayPalCommercePaymentStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n new LoadingIndicator({ styles: { backgroundColor: 'black' } }),\n );\n\nexport default toResolvableModule(createPayPalCommercePaymentStrategy, [{ id: 'paypalcommerce' }]);\n","import {\n InvalidArgumentError,\n NotImplementedError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n ClickCallbackActions,\n PayPalCommerceButtons,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceCreditPaymentInitializeOptions, {\n WithPayPalCommerceCreditPaymentInitializeOptions,\n} from './paypal-commerce-credit-payment-initialize-options';\n\nexport default class PayPalCommerceCreditPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: PayPalCommerceButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithPayPalCommerceCreditPaymentInitializeOptions,\n ): Promise {\n const { methodId, paypalcommerce, paypalcommercecredit } = options || {};\n\n const paypalOptions = paypalcommercecredit || paypalcommerce;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (paypalcommerce) {\n console.warn(\n 'The \"options.paypalcommerce\" option is deprecated for this strategy, please use \"options.paypalcommercevenmo\" instead',\n );\n }\n\n if (!paypalOptions) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerce\" argument is not provided.`,\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n // Info:\n // The PayPal button and fields should not be rendered when shopper was redirected to Checkout page\n // after using smart payment button on PDP or Cart page. In this case backend returns order id if\n // it is available in checkout session. Therefore, it is not necessary to render PayPal button.\n if (paymentMethod.initializationData?.orderId) {\n this.orderId = paymentMethod.initializationData?.orderId;\n\n return;\n }\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.loadingIndicatorContainer = paypalOptions.container.split('#')[1];\n\n this.renderButton(methodId, paypalOptions);\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!this.orderId) {\n throw new PaymentMethodInvalidError();\n }\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paypalCommerceIntegrationService.submitPayment(payment.methodId, this.orderId);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.orderId = undefined;\n\n this.paypalButton?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Button methods/callbacks\n *\n * */\n private renderButton(\n methodId: string,\n paypalOptions: PayPalCommerceCreditPaymentInitializeOptions,\n ): void {\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { buttonStyle } = paymentMethod.initializationData || {};\n\n const { container, onError, onRenderButton, onValidate, submitForm } = paypalOptions;\n\n const fundingSources = [paypalSdk.FUNDING.PAYLATER, paypalSdk.FUNDING.CREDIT];\n let hasRenderedSmartButton = false;\n\n fundingSources.forEach((fundingSource) => {\n if (hasRenderedSmartButton) {\n return;\n }\n\n const buttonOptions: PayPalCommerceButtonsOptions = {\n fundingSource,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(buttonStyle),\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder(\n 'paypalcommercecreditcheckout',\n ),\n onClick: (_, actions) => this.handleClick(actions, onValidate),\n onApprove: (data) => this.handleApprove(data, submitForm),\n onCancel: () => this.toggleLoadingIndicator(false),\n onError: (error) => this.handleError(error, onError),\n };\n\n this.paypalButton = paypalSdk.Buttons(buttonOptions);\n\n if (!this.paypalButton.isEligible() && fundingSource === paypalSdk.FUNDING.PAYLATER) {\n return;\n }\n\n if (!this.paypalButton.isEligible() && fundingSource === paypalSdk.FUNDING.CREDIT) {\n throw new NotImplementedError(\n `PayPal ${fundingSource} is not available for your region. Please use PayPal Checkout instead.`,\n );\n }\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n this.paypalButton.render(container);\n hasRenderedSmartButton = true;\n });\n }\n\n private async handleClick(\n actions: ClickCallbackActions,\n onValidate: PayPalCommerceCreditPaymentInitializeOptions['onValidate'],\n ): Promise {\n const { resolve, reject } = actions;\n\n const onValidationPassed = () => {\n this.toggleLoadingIndicator(true);\n\n return resolve();\n };\n\n await onValidate(onValidationPassed, reject);\n }\n\n private handleApprove(\n { orderID }: ApproveCallbackPayload,\n submitForm: PayPalCommerceCreditPaymentInitializeOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n submitForm();\n this.toggleLoadingIndicator(false);\n }\n\n private handleError(\n error: Error,\n onError: PayPalCommerceCreditPaymentInitializeOptions['onError'],\n ): void {\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n\n /**\n *\n * Loading Indicator methods\n *\n * */\n private toggleLoadingIndicator(isLoading: boolean): void {\n if (isLoading && this.loadingIndicatorContainer) {\n this.loadingIndicator.show(this.loadingIndicatorContainer);\n } else {\n this.loadingIndicator.hide();\n }\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceCreditPaymentStrategy from './paypal-commerce-credit-payment-strategy';\n\nconst createPayPalCommerceCreditPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceCreditPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditPaymentStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n new LoadingIndicator({ styles: { backgroundColor: 'black' } }),\n );\n\nexport default toResolvableModule(createPayPalCommerceCreditPaymentStrategy, [\n { id: 'paypalcommercecredit' },\n]);\n","import {\n InvalidArgumentError,\n NotImplementedError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n ClickCallbackActions,\n PayPalCommerceButtons,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceVenmoPaymentInitializeOptions, {\n WithPayPalCommerceVenmoPaymentInitializeOptions,\n} from './paypal-commerce-venmo-payment-initialize-options';\n\nexport default class PayPalCommerceVenmoPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: PayPalCommerceButtons;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n private loadingIndicator: LoadingIndicator,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithPayPalCommerceVenmoPaymentInitializeOptions,\n ): Promise {\n const { methodId, paypalcommerce, paypalcommercevenmo } = options || {};\n\n const paypalOptions = paypalcommercevenmo || paypalcommerce;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (paypalcommerce) {\n console.warn(\n 'The \"options.paypalcommerce\" option is deprecated for this strategy, please use \"options.paypalcommercevenmo\" instead',\n );\n }\n\n if (!paypalOptions) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercevenmo\" argument is not provided.`,\n );\n }\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n\n // Info:\n // The PayPal button and fields should not be rendered when shopper was redirected to Checkout page\n // after using smart payment button on PDP or Cart page. In this case backend returns order id if\n // it is available in checkout session. Therefore, it is not necessary to render PayPal button.\n if (paymentMethod.initializationData?.orderId) {\n this.orderId = paymentMethod.initializationData?.orderId;\n\n return;\n }\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.loadingIndicatorContainer = paypalOptions.container.split('#')[1];\n\n this.renderButton(methodId, paypalOptions);\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!this.orderId) {\n throw new PaymentMethodInvalidError();\n }\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paypalCommerceIntegrationService.submitPayment(payment.methodId, this.orderId);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.orderId = undefined;\n\n this.paypalButton?.close();\n\n return Promise.resolve();\n }\n\n /**\n *\n * Button methods/callbacks\n *\n * */\n private renderButton(\n methodId: string,\n paypalcommercevenmo: PayPalCommerceVenmoPaymentInitializeOptions,\n ): void {\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { buttonStyle } = paymentMethod.initializationData || {};\n\n const { container, onError, onRenderButton, onValidate, submitForm } = paypalcommercevenmo;\n\n const buttonOptions: PayPalCommerceButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.VENMO,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(buttonStyle),\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder('paypalcommercevenmocheckout'),\n onClick: (_, actions) => this.handleClick(actions, onValidate),\n onApprove: (data) => this.handleApprove(data, submitForm),\n onCancel: () => this.toggleLoadingIndicator(false),\n onError: (error) => this.handleError(error, onError),\n };\n\n this.paypalButton = paypalSdk.Buttons(buttonOptions);\n\n if (!this.paypalButton.isEligible()) {\n throw new NotImplementedError(\n `PayPal Venmo is not available for your region. Please use PayPal Checkout instead.`,\n );\n }\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n this.paypalButton.render(container);\n }\n\n private async handleClick(\n actions: ClickCallbackActions,\n onValidate: PayPalCommerceVenmoPaymentInitializeOptions['onValidate'],\n ): Promise {\n const { resolve, reject } = actions;\n\n const onValidationPassed = () => {\n this.toggleLoadingIndicator(true);\n\n return resolve();\n };\n\n await onValidate(onValidationPassed, reject);\n }\n\n private handleApprove(\n { orderID }: ApproveCallbackPayload,\n submitForm: PayPalCommerceVenmoPaymentInitializeOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n submitForm();\n this.toggleLoadingIndicator(false);\n }\n\n private handleError(\n error: Error,\n onError: PayPalCommerceVenmoPaymentInitializeOptions['onError'],\n ): void {\n this.toggleLoadingIndicator(false);\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n\n /**\n *\n * Loading Indicator methods\n *\n * */\n private toggleLoadingIndicator(isLoading: boolean): void {\n if (isLoading && this.loadingIndicatorContainer) {\n this.loadingIndicator.show(this.loadingIndicatorContainer);\n } else {\n this.loadingIndicator.hide();\n }\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceVenmoPaymentStrategy from './paypal-commerce-venmo-payment-strategy';\n\nconst createPayPalCommerceVenmoPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceVenmoPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceVenmoPaymentStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n new LoadingIndicator({ styles: { backgroundColor: 'black' } }),\n );\n\nexport default toResolvableModule(createPayPalCommerceVenmoPaymentStrategy, [\n { id: 'paypalcommercevenmo' },\n]);\n","import { Response } from '@bigcommerce/request-sender';\n\nimport RequestError from './request-error';\n\n/**\n * Throw this error if a request fails to complete within its required timeframe\n * because of a network issue.\n */\nexport default class TimeoutError extends RequestError {\n constructor(response?: Response) {\n super(response, {\n message: 'The request has timed out or aborted.',\n });\n\n this.name = 'TimeoutError';\n this.type = 'timeout';\n }\n}\n","import { noop } from 'lodash';\n\nimport {\n InvalidArgumentError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodInvalidError,\n PaymentRequestOptions,\n PaymentStrategy,\n TimeoutError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n ClickCallbackActions,\n NonInstantAlternativePaymentMethods,\n PayPalCommerceButtons,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n PayPalOrderStatus,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceAlternativeMethodsPaymentOptions, {\n WithPayPalCommerceAlternativeMethodsPaymentInitializeOptions,\n} from './paypal-commerce-alternative-methods-payment-initialize-options';\n\nexport default class PayPalCommerceAlternativeMethodsPaymentStrategy implements PaymentStrategy {\n private loadingIndicatorContainer?: string;\n private orderId?: string;\n private paypalButton?: PayPalCommerceButtons;\n private pollingTimer = 0;\n private stopPolling = noop;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n private loadingIndicator: LoadingIndicator,\n private pollingInterval = 3000,\n private maxPollingTime = 600000,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions &\n WithPayPalCommerceAlternativeMethodsPaymentInitializeOptions,\n ): Promise {\n const {\n gatewayId,\n methodId,\n paypalcommerce, // FIXME: this option is deprecated\n paypalcommercealternativemethods,\n } = options;\n const paypalOptions = paypalcommercealternativemethods || paypalcommerce;\n\n if (paypalcommerce) {\n console.warn(\n 'The \"options.paypalcommerce\" option is deprecated for this strategy, please use \"options.paypalcommercealternativemethods\" instead',\n );\n }\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.gatewayId\" argument is not provided.',\n );\n }\n\n if (!paypalOptions) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercealternativemethods\" argument is not provided.`,\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(\n methodId,\n gatewayId,\n );\n const { orderId, shouldRenderFields } = paymentMethod.initializationData || {};\n\n // Info:\n // The PayPal button and fields should not be rendered when shopper was redirected to Checkout page\n // after using smart payment button on PDP or Cart page. In this case backend returns order id if\n // it is available in checkout session. Therefore, it is not necessary to render PayPal button.\n if (orderId) {\n this.orderId = orderId;\n\n return;\n }\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n this.loadingIndicatorContainer = paypalOptions.container.split('#')[1];\n\n this.renderButton(methodId, gatewayId, paypalOptions);\n\n if (shouldRenderFields) {\n this.renderFields(methodId, paypalOptions);\n }\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!this.orderId) {\n throw new PaymentMethodInvalidError();\n }\n\n if (!this.isNonInstantPaymentMethod(payment.methodId)) {\n await this.paymentIntegrationService.submitOrder(order, options);\n }\n\n await this.paypalCommerceIntegrationService.submitPayment(payment.methodId, this.orderId);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this.deinitializePollingMechanism();\n\n this.orderId = undefined;\n\n this.paypalButton?.close();\n\n return Promise.resolve();\n }\n\n private async reinitializeStrategy(\n options: PaymentInitializeOptions &\n WithPayPalCommerceAlternativeMethodsPaymentInitializeOptions,\n ): Promise {\n await this.deinitialize();\n await this.initialize(options);\n }\n\n /**\n *\n * Button methods/callbacks\n *\n * */\n private renderButton(\n methodId: string,\n gatewayId: string,\n paypalOptions: PayPalCommerceAlternativeMethodsPaymentOptions,\n ): void {\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(\n methodId,\n gatewayId,\n );\n const { buttonStyle } = paymentMethod.initializationData || {};\n\n const { container, onError, onRenderButton, submitForm } = paypalOptions;\n\n const buttonOptions: PayPalCommerceButtonsOptions = {\n fundingSource: methodId,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(buttonStyle),\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder(\n 'paypalcommercealternativemethodscheckout',\n ),\n onClick: (_, actions) => this.handleClick(methodId, gatewayId, paypalOptions, actions),\n onApprove: (data) => this.handleApprove(data, submitForm),\n onCancel: () => this.resetPollingMechanism(),\n onError: (error) => this.handleError(error, onError),\n };\n\n this.paypalButton = paypalSdk.Buttons(buttonOptions);\n\n if (!this.paypalButton.isEligible()) {\n return;\n }\n\n if (onRenderButton && typeof onRenderButton === 'function') {\n onRenderButton();\n }\n\n this.paypalButton.render(container);\n }\n\n private async handleClick(\n methodId: string,\n gatewayId: string,\n paypalOptions: PayPalCommerceAlternativeMethodsPaymentOptions,\n actions: ClickCallbackActions,\n ): Promise {\n const { onValidate } = paypalOptions;\n const { resolve, reject } = actions;\n\n if (!this.isNonInstantPaymentMethod(methodId)) {\n await this.initializePollingMechanism(methodId, gatewayId, paypalOptions);\n }\n\n const onValidationPassed = () => {\n this.toggleLoadingIndicator(true);\n\n return resolve();\n };\n\n await onValidate(onValidationPassed, reject);\n }\n\n private handleApprove(\n { orderID }: ApproveCallbackPayload,\n submitForm: PayPalCommerceAlternativeMethodsPaymentOptions['submitForm'],\n ): void {\n this.orderId = orderID;\n\n this.deinitializePollingMechanism();\n submitForm();\n this.toggleLoadingIndicator(false);\n }\n\n private handleError(\n error: Error,\n onError: PayPalCommerceAlternativeMethodsPaymentOptions['onError'],\n ): void {\n this.resetPollingMechanism();\n\n if (onError && typeof onError === 'function') {\n onError(error);\n }\n }\n\n /**\n *\n * Fields methods\n *\n * */\n private renderFields(\n methodId: string,\n paypalOptions: PayPalCommerceAlternativeMethodsPaymentOptions,\n ): void {\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const { firstName, lastName, email } = state.getBillingAddressOrThrow();\n\n const { apmFieldsContainer, apmFieldsStyles } = paypalOptions;\n\n if (!apmFieldsContainer) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.paypalcommercealternativemethods\" argument should contain \"apmFieldsContainer\".',\n );\n }\n\n const fieldContainerElement = document.querySelector(apmFieldsContainer);\n\n if (fieldContainerElement) {\n fieldContainerElement.innerHTML = '';\n }\n\n const fieldsOptions = {\n fundingSource: methodId,\n style: apmFieldsStyles || {},\n fields: {\n name: {\n value: `${firstName} ${lastName}`,\n },\n email: {\n value: email,\n },\n },\n };\n\n const paypalPaymentFields = paypalSdk.PaymentFields(fieldsOptions);\n\n paypalPaymentFields.render(apmFieldsContainer);\n }\n\n /**\n *\n * Polling mechanism\n *\n *\n * */\n private async initializePollingMechanism(\n methodId: string,\n gatewayId: string,\n paypalOptions: PayPalCommerceAlternativeMethodsPaymentOptions,\n ): Promise {\n const { onError, submitForm } = paypalOptions;\n\n await new Promise((resolve, reject) => {\n const timeout = setTimeout(resolve, this.pollingInterval);\n\n this.stopPolling = () => {\n clearTimeout(timeout);\n reject();\n };\n });\n\n try {\n this.pollingTimer += this.pollingInterval;\n\n const orderStatus = await this.paypalCommerceIntegrationService.getOrderStatus();\n\n const isOrderApproved = orderStatus === PayPalOrderStatus.Approved;\n const isOrderPending =\n orderStatus === PayPalOrderStatus.Created ||\n orderStatus === PayPalOrderStatus.PayerActionRequired;\n\n if (isOrderApproved) {\n this.deinitializePollingMechanism();\n\n return submitForm();\n }\n\n if (isOrderPending && this.pollingTimer < this.maxPollingTime) {\n return await this.initializePollingMechanism(methodId, gatewayId, paypalOptions);\n }\n\n await this.reinitializeStrategy({\n methodId,\n gatewayId,\n paypalcommercealternativemethods: paypalOptions,\n });\n\n throw new TimeoutError();\n } catch (error) {\n this.handleError(error, onError);\n }\n }\n\n private deinitializePollingMechanism(): void {\n this.stopPolling();\n this.pollingTimer = 0;\n }\n\n private resetPollingMechanism(): void {\n this.deinitializePollingMechanism();\n this.toggleLoadingIndicator(false);\n }\n\n /**\n *\n * Loading Indicator methods\n *\n * */\n private toggleLoadingIndicator(isLoading: boolean): void {\n if (isLoading && this.loadingIndicatorContainer) {\n this.loadingIndicator.show(this.loadingIndicatorContainer);\n } else {\n this.loadingIndicator.hide();\n }\n }\n\n /**\n *\n * Utils\n *\n * */\n private isNonInstantPaymentMethod(methodId: string): boolean {\n return methodId.toUpperCase() in NonInstantAlternativePaymentMethods;\n }\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceAlternativeMethodsPaymentStrategy from './paypal-commerce-alternative-methods-payment-strategy';\n\nconst createPayPalCommerceAlternativeMethodsPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceAlternativeMethodsPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceAlternativeMethodsPaymentStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n new LoadingIndicator({ styles: { backgroundColor: 'black' } }),\n );\n\nexport default toResolvableModule(createPayPalCommerceAlternativeMethodsPaymentStrategy, [\n { gateway: 'paypalcommercealternativemethods' },\n]);\n","import HostedFieldType from './hosted-field-type';\nimport { HostedCardFieldOptionsMap, HostedStoredCardFieldOptionsMap } from './hosted-form-options';\n\nexport default function isCreditCardFormFields(\n fields: HostedCardFieldOptionsMap | HostedStoredCardFieldOptionsMap,\n): fields is HostedCardFieldOptionsMap {\n return (\n HostedFieldType.CardNumber in fields &&\n HostedFieldType.CardName in fields &&\n HostedFieldType.CardExpiry in fields\n );\n}\n","import { isNil, omitBy } from 'lodash';\n\nimport {\n HostedCardFieldOptions,\n HostedCardFieldOptionsMap,\n HostedFieldBlurEventData,\n HostedFieldCardTypeChangeEventData,\n HostedFieldEnterEventData,\n HostedFieldFocusEventData,\n HostedFieldStylesMap,\n HostedFieldType,\n HostedFieldValidateEventData,\n HostedFormOptions,\n HostedInputStyles,\n HostedInputValidateErrorData,\n HostedInputValidateErrorDataMap,\n HostedInstrument,\n HostedStoredCardFieldOptionsMap,\n InvalidArgumentError,\n isCreditCardFormFields,\n isHostedInstrumentLike,\n isVaultedInstrument,\n NotInitializedError,\n NotInitializedErrorType,\n objectWithKebabCaseKeys,\n OrderFinalizationNotRequiredError,\n OrderPaymentRequestBody,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n PaymentMethodFailedError,\n PaymentRequestOptions,\n PaymentStrategy,\n VaultedInstrument,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n PayPalCommerceHostedFields,\n PayPalCommerceHostedFieldsRenderOptions,\n PayPalCommerceHostedFieldsState,\n PayPalCommerceHostedFieldsSubmitOptions,\n} from '../paypal-commerce-types';\n\nimport { WithPayPalCommerceCreditCardsPaymentInitializeOptions } from './paypal-commerce-credit-cards-payment-initialize-options';\n\nexport default class PayPalCommerceCreditCardsPaymentStrategy implements PaymentStrategy {\n private executionPaymentData?: OrderPaymentRequestBody['paymentData'];\n private isCreditCardForm?: boolean;\n private hostedFields?: PayPalCommerceHostedFields;\n private hostedFormOptions?: HostedFormOptions;\n private cardNameField?: HTMLInputElement;\n\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: PaymentInitializeOptions & WithPayPalCommerceCreditCardsPaymentInitializeOptions,\n ): Promise {\n const { methodId, paypalcommercecreditcards, paypalcommerce } = options;\n const form = paypalcommercecreditcards?.form || paypalcommerce?.form;\n\n if (paypalcommerce) {\n console.warn(\n 'The \"options.paypalcommerce\" option is deprecated for PayPal Commerce Credit Card form, please use \"options.paypalcommercecreditcards\" instead',\n );\n }\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!form) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"options.paypalcommercecreditcards.form\" argument is not provided.',\n );\n }\n\n this.hostedFormOptions = form;\n this.isCreditCardForm = isCreditCardFormFields(form.fields);\n\n await this.paymentIntegrationService.loadPaymentMethod(methodId);\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId);\n\n await this.renderFields(form);\n }\n\n async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment, ...order } = payload;\n const { methodId, paymentData } = payment || {};\n\n if (!payment || !methodId) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n this.executionPaymentData = paymentData;\n\n this.validateHostedFormOrThrow();\n\n const orderId = await this.submitHostedForm(methodId);\n\n await this.paymentIntegrationService.submitOrder(order, options);\n await this.paypalCommerceIntegrationService.submitPayment(methodId, orderId);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private async renderFields(formOptions: HostedFormOptions): Promise {\n const { fields, styles } = formOptions;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n\n const hostedFieldsOptions = {\n fields: this.mapFieldOptions(fields),\n styles: styles ? this.mapStyleOptions(styles) : {},\n paymentsSDK: true,\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder(\n 'paypalcommercecreditcardscheckout',\n this.getInstrumentParams(),\n ),\n };\n\n if (paypalSdk.HostedFields.isEligible()) {\n this.hostedFields = await paypalSdk.HostedFields.render(hostedFieldsOptions);\n\n this.setFormFieldEvents(this.hostedFields, formOptions);\n\n if (isCreditCardFormFields(fields)) {\n this.renderCardNameField(fields.cardName, styles);\n }\n } else {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n }\n\n /**\n *\n * Card Name field methods\n *\n */\n private renderCardNameField(\n field: HostedCardFieldOptions,\n styles?: HostedFieldStylesMap,\n ): void {\n const container = document.getElementById(field.containerId);\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"options.paypalcommercecreditcards.form.fields.cardName.containerId\" argument is not provided or the item is not defined in the dom.',\n );\n }\n\n const cardNameFiledStylesPreset = {\n backgroundColor: 'transparent',\n border: 0,\n display: 'block',\n height: '100%',\n margin: 0,\n outline: 'none',\n padding: 0,\n width: '100%',\n };\n\n const defaultCardNameFiledStyles = {\n ...cardNameFiledStylesPreset,\n ...styles?.default,\n };\n\n const focusCardNameFiledStyles = {\n ...cardNameFiledStylesPreset,\n ...styles?.focus,\n };\n\n const defaultStyleProperties = this.getValidStyleString(defaultCardNameFiledStyles);\n const focusStyleProperties = this.getValidStyleString(focusCardNameFiledStyles);\n\n this.cardNameField = document.createElement('input');\n\n this.setFieldStyleAttribute(defaultStyleProperties, this.cardNameField);\n\n this.cardNameField.addEventListener('blur', () =>\n this.setFieldStyleAttribute(defaultStyleProperties, this.cardNameField),\n );\n this.cardNameField.addEventListener('focus', () =>\n this.setFieldStyleAttribute(focusStyleProperties, this.cardNameField),\n );\n\n container.appendChild(this.cardNameField);\n }\n\n private setFieldStyleAttribute(style: string, item?: HTMLInputElement): void {\n item?.setAttribute('style', style);\n }\n\n /**\n *\n * Instrument params method\n *\n */\n private getInstrumentParams(): HostedInstrument | VaultedInstrument {\n if (!this.executionPaymentData) {\n return {};\n }\n\n if (isHostedInstrumentLike(this.executionPaymentData)) {\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } =\n this.executionPaymentData;\n\n return {\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n };\n }\n\n if (isVaultedInstrument(this.executionPaymentData)) {\n const { instrumentId } = this.executionPaymentData;\n\n return {\n instrumentId,\n };\n }\n\n return {};\n }\n\n /**\n *\n * Hosted form events\n *\n */\n private setFormFieldEvents(\n hostedFields: PayPalCommerceHostedFields,\n formOptions: HostedFormOptions,\n ): void {\n const eventsData = [\n {\n eventName: 'blur',\n formCallback: formOptions?.onBlur,\n eventHandler: (event: PayPalCommerceHostedFieldsState) =>\n formOptions?.onBlur?.(this.getFieldTypeByEmittedField(event)),\n },\n {\n eventName: 'focus',\n formCallback: formOptions?.onFocus,\n eventHandler: (event: PayPalCommerceHostedFieldsState) =>\n formOptions?.onFocus?.(this.getFieldTypeByEmittedField(event)),\n },\n {\n eventName: 'inputSubmitRequest',\n formCallback: formOptions?.onEnter,\n eventHandler: (event: PayPalCommerceHostedFieldsState) =>\n formOptions?.onEnter?.(this.getFieldTypeByEmittedField(event)),\n },\n {\n eventName: 'cardTypeChange',\n formCallback: formOptions?.onCardTypeChange,\n eventHandler: (event: PayPalCommerceHostedFieldsState) =>\n formOptions?.onCardTypeChange?.(this.getCardTypeByEvent(event)),\n },\n {\n eventName: 'validityChange',\n formCallback: formOptions?.onValidate,\n eventHandler: (event: PayPalCommerceHostedFieldsState) =>\n formOptions?.onValidate?.(this.getValidityData(event)),\n },\n ];\n\n eventsData.forEach(({ eventName, eventHandler, formCallback }) => {\n if (formCallback && typeof formCallback === 'function') {\n hostedFields.on(eventName, eventHandler);\n }\n });\n }\n\n private getFieldTypeByEmittedField({\n emittedBy,\n }: PayPalCommerceHostedFieldsState):\n | HostedFieldBlurEventData\n | HostedFieldEnterEventData\n | HostedFieldFocusEventData {\n return {\n fieldType: this.mapFieldType(emittedBy),\n };\n }\n\n private getCardTypeByEvent({\n cards,\n }: PayPalCommerceHostedFieldsState): HostedFieldCardTypeChangeEventData {\n return {\n cardType: cards?.[0]?.type,\n };\n }\n\n /**\n *\n * Hosted form submit method\n *\n * */\n private async submitHostedForm(methodId: string): Promise {\n const hostedFields = this.getHostedFieldsOrThrow();\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { is3dsEnabled } = paymentMethod.config;\n\n const options: PayPalCommerceHostedFieldsSubmitOptions = {\n ...(this.cardNameField?.value && {\n cardholderName: this.cardNameField.value,\n }),\n ...(is3dsEnabled && {\n contingencies: ['3D_SECURE'],\n }),\n };\n\n const { liabilityShift, orderId } = await hostedFields.submit(options);\n\n if (is3dsEnabled && (liabilityShift === 'NO' || liabilityShift === 'UNKNOWN')) {\n // FIXME: we should throw another error to have an ability to translate it\n throw new PaymentMethodFailedError(\n 'Failed authentication. Please try to authorize again.',\n );\n }\n\n return orderId;\n }\n\n /**\n *\n * Validation and errors\n *\n */\n private validateHostedFormOrThrow(): void {\n const hostedFields = this.getHostedFieldsOrThrow();\n const hostedFieldState = hostedFields.getState();\n const validationData = this.getValidityData(hostedFieldState);\n\n if (validationData.isValid) {\n return;\n }\n\n this.hostedFormOptions?.onValidate?.(validationData);\n\n throw new PaymentInvalidFormError(this.mapValidationErrors(validationData.errors));\n }\n\n private getValidityData({\n fields,\n }: PayPalCommerceHostedFieldsState): HostedFieldValidateEventData {\n const fieldsKeys = Object.keys(fields) as Array<\n keyof PayPalCommerceHostedFieldsState['fields']\n >;\n\n const isValid = fieldsKeys.every((key) => fields[key]?.isValid);\n const errors = fieldsKeys.reduce((fieldsErrors, key) => {\n const fieldType = this.mapFieldType(key);\n\n return {\n ...fieldsErrors,\n [fieldType]: fields[key]?.isValid\n ? undefined\n : [this.getInvalidErrorByFieldType(fieldType)],\n };\n }, {});\n\n return { isValid, errors };\n }\n\n private getInvalidErrorByFieldType(fieldType: string): HostedInputValidateErrorData {\n switch (fieldType) {\n case HostedFieldType.CardCode:\n case HostedFieldType.CardCodeVerification:\n return {\n fieldType,\n message: 'Invalid card code',\n type: 'invalid_card_code',\n };\n\n case HostedFieldType.CardNumber:\n case HostedFieldType.CardNumberVerification:\n return {\n fieldType,\n message: 'Invalid card number',\n type: 'invalid_card_number',\n };\n\n case HostedFieldType.CardExpiry:\n return {\n fieldType,\n message: 'Invalid card expiry',\n type: 'invalid_card_expiry',\n };\n\n default:\n return {\n fieldType,\n message: 'Invalid field',\n type: 'invalid',\n };\n }\n }\n\n private mapValidationErrors(\n validationErrors: HostedInputValidateErrorDataMap = {},\n ): PaymentInvalidFormErrorDetails {\n const errors: PaymentInvalidFormErrorDetails = {};\n const validationErrorsKeys = Object.keys(validationErrors) as Array<\n keyof HostedInputValidateErrorDataMap\n >;\n\n validationErrorsKeys.forEach((key) => {\n errors[key] = [\n {\n message: validationErrors[key]?.[0]?.message || '',\n type: key,\n },\n ];\n });\n\n return errors;\n }\n\n /**\n *\n * Fields mappers\n *\n */\n private mapFieldType(type: string): HostedFieldType {\n switch (type) {\n case 'number':\n return this.isCreditCardForm\n ? HostedFieldType.CardNumber\n : HostedFieldType.CardNumberVerification;\n\n case 'expirationDate':\n return HostedFieldType.CardExpiry;\n\n case 'cvv':\n return this.isCreditCardForm\n ? HostedFieldType.CardCode\n : HostedFieldType.CardCodeVerification;\n\n default:\n throw new Error('Unexpected field type');\n }\n }\n\n private mapFieldOptions(\n fields: HostedCardFieldOptionsMap | HostedStoredCardFieldOptionsMap,\n ): PayPalCommerceHostedFieldsRenderOptions['fields'] {\n if (isCreditCardFormFields(fields)) {\n const { cardNumber, cardExpiry, cardCode } = fields;\n\n return {\n ...(cardNumber && {\n number: {\n selector: `#${cardNumber.containerId}`,\n placeholder: cardNumber.placeholder,\n },\n }),\n ...(cardExpiry && {\n expirationDate: {\n selector: `#${cardExpiry.containerId}`,\n placeholder: cardExpiry.placeholder,\n },\n }),\n ...(cardCode && {\n cvv: {\n selector: `#${cardCode.containerId}`,\n placeholder: cardCode.placeholder,\n },\n }),\n };\n }\n\n const { cardNumberVerification, cardCodeVerification } = fields;\n\n return {\n ...(cardNumberVerification && {\n number: {\n selector: `#${cardNumberVerification.containerId}`,\n placeholder: cardNumberVerification.placeholder,\n },\n }),\n ...(cardCodeVerification && {\n cvv: {\n selector: `#${cardCodeVerification.containerId}`,\n placeholder: cardCodeVerification.placeholder,\n },\n }),\n };\n }\n\n /**\n *\n * Styles mappers\n *\n */\n private mapStyleOptions(\n styles: HostedFieldStylesMap,\n ): PayPalCommerceHostedFieldsRenderOptions['styles'] {\n return {\n input: this.mapStyles(styles.default),\n '.invalid': this.mapStyles(styles.error),\n ':focus': this.mapStyles(styles.focus),\n };\n }\n\n private mapStyles(styles: HostedInputStyles = {}): { [key: string]: string } {\n return omitBy(objectWithKebabCaseKeys(styles), isNil);\n }\n\n private getValidStyleString(styles: HostedInputStyles = {}): string {\n const validStyles = this.mapStyles(styles);\n\n return Object.keys(validStyles)\n .map((key) => `${key}: ${validStyles[key]}`)\n .join(';');\n }\n\n /**\n *\n * Utils\n *\n */\n private getHostedFieldsOrThrow(): PayPalCommerceHostedFields {\n if (!this.hostedFields) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this.hostedFields;\n }\n}\n","import { kebabCase } from 'lodash';\n\nexport default function objectWithKebabCaseKeys(object: { [key: string]: any }) {\n const keys = Object.keys(object);\n\n return keys.reduce(\n (newObject, key) => ({\n ...newObject,\n [kebabCase(key)]: object[key],\n }),\n {},\n );\n}\n","import {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceCreditCardsPaymentStrategy from './paypal-commerce-credit-cards-payment-strategy';\n\nconst createPaypalCommerceCreditCardsPaymentStrategy: PaymentStrategyFactory<\n PayPalCommerceCreditCardsPaymentStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditCardsPaymentStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPaypalCommerceCreditCardsPaymentStrategy, [\n { id: 'paypalcommercecreditcards' },\n]);\n","import { ExternalPaymentStrategy } from '@bigcommerce/checkout-sdk/external-integration';\n\nexport default class SezzlePaymentStrategy extends ExternalPaymentStrategy {\n protected redirectUrl(url: string): void {\n window.location.replace(url);\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\n\nimport {\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport SezzlePaymentStrategy from './sezzle-payment-strategy';\n\nconst createSezzlePaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => new SezzlePaymentStrategy(createFormPoster(), paymentIntegrationService);\n\nexport default toResolvableModule(createSezzlePaymentStrategy, [{ id: 'sezzle' }]);\n","import StandardError from './standard-error';\n\nconst defaultMessage =\n 'Payment cannot be processed for this order, please select another payment method';\n\nexport default class PaymentExecuteError extends StandardError {\n type = 'custom_provider_execute_error';\n subtype: string;\n\n constructor(subtype: string, name: string, message?: string) {\n super(message || defaultMessage);\n\n this.name = name;\n this.subtype = subtype;\n }\n}\n","import { fromEvent, merge, Subscription } from 'rxjs';\nimport { distinctUntilChanged, map } from 'rxjs/operators';\n\nimport {\n BillingAddress,\n guard,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentExecuteError,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport SquareV2PaymentInitializeOptions from './squarev2-payment-initialize-options';\nimport SquareV2ScriptLoader from './squarev2-script-loader';\nimport {\n BillingContact,\n Card,\n CardInputEvent,\n CardInputEventTypes,\n ChargeVerifyBuyerDetails,\n Payments,\n SqEvent,\n} from './types';\n\nexport interface SquareV2PaymentProcessorOptions {\n applicationId: string;\n locationId?: string;\n testMode?: boolean;\n}\n\nexport default class SquareV2PaymentProcessor {\n private _payments?: Payments;\n private _card?: Card;\n private _formValidationSubscription?: Subscription;\n\n constructor(\n private _scriptLoader: SquareV2ScriptLoader,\n private _paymentIntegrationService: PaymentIntegrationService,\n ) {}\n\n async initialize({\n testMode,\n applicationId,\n locationId,\n }: SquareV2PaymentProcessorOptions): Promise {\n const square = await this._scriptLoader.load(testMode);\n\n this._payments = square.payments(applicationId, locationId);\n }\n\n async deinitialize(): Promise {\n if (this._formValidationSubscription) {\n this._formValidationSubscription.unsubscribe();\n }\n\n if (this._card) {\n await this._card.destroy();\n }\n\n this._formValidationSubscription = undefined;\n this._card = undefined;\n this._payments = undefined;\n }\n\n async initializeCard({\n containerId,\n style,\n onValidationChange,\n }: SquareV2PaymentInitializeOptions): Promise {\n const { postalCode } = this._paymentIntegrationService.getState().getBillingAddress() || {};\n\n this._card = await this._getPayments().card();\n await this._card.attach(`#${containerId}`);\n\n try {\n await this._card.configure({ postalCode, style });\n } catch (_error) {\n /* Do nothing: we should not block shoppers from buying. */\n }\n\n if (onValidationChange) {\n this._formValidationSubscription = this._subscribeToFormValidation(\n this._card,\n onValidationChange,\n );\n }\n }\n\n async tokenize(): Promise {\n const result = await this._getCard().tokenize();\n\n if (result.status !== 'OK' || !result.token) {\n let errorMessage = `Tokenization failed with status: ${result.status}`;\n\n if (result.errors) {\n errorMessage += ` and errors: ${JSON.stringify(result.errors)}`;\n }\n\n throw new PaymentExecuteError(\n 'payment.errors.card_error',\n 'SquareV2TokenizationError',\n errorMessage,\n );\n }\n\n return result.token;\n }\n\n async verifyBuyer(token: string): Promise {\n const { getCheckoutOrThrow, getBillingAddressOrThrow } =\n this._paymentIntegrationService.getState();\n const { outstandingBalance, cart } = getCheckoutOrThrow();\n\n const details: ChargeVerifyBuyerDetails = {\n amount: outstandingBalance.toString(),\n billingContact: this._mapToSquareBillingContact(getBillingAddressOrThrow()),\n currencyCode: cart.currency.code,\n intent: 'CHARGE',\n };\n\n const response = await this._getPayments().verifyBuyer(token, details);\n\n return response ? response.token : '';\n }\n\n private _getPayments(): Payments {\n return guard(\n this._payments,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n private _subscribeToFormValidation(\n card: Card,\n observer: Required['onValidationChange'],\n ): Subscription {\n const blacklist = ['cardNumber', 'cvv'];\n const invalidFields = new Set(blacklist);\n const eventObservables = [\n 'focusClassAdded',\n 'focusClassRemoved',\n 'errorClassAdded',\n 'errorClassRemoved',\n 'cardBrandChanged',\n 'postalCodeChanged',\n ].map((eventType) => fromEvent(card, eventType as CardInputEventTypes));\n\n return merge(...eventObservables)\n .pipe(\n map((event: SqEvent): boolean => {\n const {\n detail: {\n field,\n currentState: { isCompletelyValid },\n },\n } = event;\n\n if (blacklist.includes(field)) {\n invalidFields[isCompletelyValid ? 'delete' : 'add'](field);\n }\n\n return invalidFields.size === 0;\n }),\n distinctUntilChanged(),\n )\n .subscribe(observer);\n }\n\n private _getCard(): Card {\n return guard(\n this._card,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n private _mapToSquareBillingContact({\n firstName: givenName,\n lastName: familyName,\n address1,\n address2,\n city,\n stateOrProvinceCode: state,\n postalCode,\n countryCode,\n email,\n phone,\n }: BillingAddress): BillingContact {\n return {\n givenName,\n familyName,\n addressLines: [address1, address2],\n city,\n state,\n postalCode,\n countryCode,\n email,\n phone,\n };\n }\n}\n","import {\n InvalidArgumentError,\n OrderFinalizationNotRequiredError,\n OrderRequestBody,\n PaymentArgumentInvalidError,\n PaymentInitializeOptions,\n PaymentIntegrationService,\n PaymentMethodInvalidError,\n PaymentStrategy,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithSquareV2PaymentInitializeOptions } from './squarev2-payment-initialize-options';\nimport SquareV2PaymentProcessor from './squarev2-payment-processor';\nimport { SquarePaymentMethodInitializationData } from './types';\n\nexport default class SquareV2PaymentStrategy implements PaymentStrategy {\n constructor(\n private _paymentIntegrationService: PaymentIntegrationService,\n private _squareV2PaymentProcessor: SquareV2PaymentProcessor,\n ) {}\n\n async initialize(\n options?: PaymentInitializeOptions & WithSquareV2PaymentInitializeOptions,\n ): Promise {\n if (!options?.squarev2?.containerId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"containerId\" argument is not provided.',\n );\n }\n\n const { methodId, squarev2 } = options;\n const {\n config: { testMode },\n initializationData,\n } = this._paymentIntegrationService\n .getState()\n .getPaymentMethodOrThrow(methodId);\n const { applicationId, locationId } = initializationData || {};\n\n if (!applicationId) {\n throw new PaymentMethodInvalidError();\n }\n\n await this._squareV2PaymentProcessor.initialize({\n applicationId,\n locationId,\n testMode,\n });\n await this._squareV2PaymentProcessor.initializeCard(squarev2);\n }\n\n async execute({ payment }: OrderRequestBody): Promise {\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n let nonce = await this._squareV2PaymentProcessor.tokenize();\n\n if (this._shouldVerify()) {\n nonce = JSON.stringify({\n nonce,\n token: await this._squareV2PaymentProcessor.verifyBuyer(nonce),\n });\n }\n\n await this._paymentIntegrationService.submitOrder();\n await this._paymentIntegrationService.submitPayment({\n ...payment,\n paymentData: { nonce },\n });\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return this._squareV2PaymentProcessor.deinitialize();\n }\n\n private _shouldVerify(): boolean {\n const { features } = this._paymentIntegrationService\n .getState()\n .getStoreConfigOrThrow().checkoutSettings;\n\n return features['PROJECT-3828.add_3ds_support_on_squarev2'];\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport assertSquareV2Window from './is-squarev2-window';\nimport { Square } from './types';\n\nexport enum SquareV2WebPaymentsSdkEnv {\n LIVE = 'https://web.squarecdn.com/v1/square.js',\n SANDBOX = 'https://sandbox.web.squarecdn.com/v1/square.js',\n}\n\nexport default class SquareV2ScriptLoader {\n constructor(private _scriptLoader: ScriptLoader) {}\n\n async load(testMode = false): Promise {\n await this._scriptLoader.loadScript(\n testMode ? SquareV2WebPaymentsSdkEnv.SANDBOX : SquareV2WebPaymentsSdkEnv.LIVE,\n );\n\n assertSquareV2Window(window);\n\n return window.Square;\n }\n}\n","import { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport type { Square } from './types';\n\ninterface SquareV2HostWindow extends Window {\n Square: Square;\n}\n\nfunction isSquareV2Window(window: Window): window is SquareV2HostWindow {\n return 'Square' in window;\n}\n\nexport default function assertSquareV2Window(window: Window): asserts window is SquareV2HostWindow {\n if (!isSquareV2Window(window)) {\n throw new PaymentMethodClientUnavailableError();\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n NotImplementedError,\n PaymentStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport SquareV2PaymentProcessor from './squarev2-payment-processor';\nimport SquareV2PaymentStrategy from './squarev2-payment-strategy';\nimport SquareV2ScriptLoader from './squarev2-script-loader';\n\nconst createSquareV2PaymentStrategy: PaymentStrategyFactory = (\n paymentIntegrationService,\n) => {\n const useV1 = !paymentIntegrationService.getState().getStoreConfig()?.checkoutSettings.features[\n 'PROJECT-4113.squarev2_web_payments_sdk'\n ];\n\n if (useV1) {\n throw new NotImplementedError();\n }\n\n return new SquareV2PaymentStrategy(\n paymentIntegrationService,\n new SquareV2PaymentProcessor(\n new SquareV2ScriptLoader(getScriptLoader()),\n paymentIntegrationService,\n ),\n );\n};\n\nexport default toResolvableModule(createSquareV2PaymentStrategy, [{ id: 'squarev2' }]);\n","import { Action } from '@bigcommerce/data-store';\n\nimport Country from './country';\n\nexport enum CountryActionType {\n LoadCountriesRequested = 'LOAD_COUNTRIES_REQUESTED',\n LoadCountriesSucceeded = 'LOAD_COUNTRIES_SUCCEEDED',\n LoadCountriesFailed = 'LOAD_COUNTRIES_FAILED',\n}\n\nexport type LoadCountriesAction =\n | LoadCountriesRequestedAction\n | LoadCountriesSucceededAction\n | LoadCountriesFailedAction;\n\nexport interface LoadCountriesRequestedAction extends Action {\n type: CountryActionType.LoadCountriesRequested;\n}\n\nexport interface LoadCountriesSucceededAction extends Action {\n type: CountryActionType.LoadCountriesSucceeded;\n}\n\nexport interface LoadCountriesFailedAction extends Action {\n type: CountryActionType.LoadCountriesFailed;\n}\n","import { Action, createAction, createErrorAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { RequestOptions } from '../common/http-request';\n\nimport Country from './country';\nimport { CountryActionType } from './country-actions';\nimport CountryRequestSender from './country-request-sender';\n\nexport default class CountryActionCreator {\n constructor(private _countryRequestSender: CountryRequestSender) {}\n\n loadCountries(options?: RequestOptions): Observable> {\n return Observable.create((observer: Observer>) => {\n observer.next(createAction(CountryActionType.LoadCountriesRequested));\n\n this._countryRequestSender\n .loadCountries(options)\n .then((response) => {\n observer.next(\n createAction(CountryActionType.LoadCountriesSucceeded, response.body.data),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(CountryActionType.LoadCountriesFailed, response),\n );\n });\n });\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\n\nimport { CountryResponseBody } from './country-responses';\n\nexport default class CountryRequestSender {\n constructor(private _requestSender: RequestSender, private _config: { locale?: string }) {}\n\n loadCountries({ timeout }: RequestOptions = {}): Promise> {\n const url = '/internalapi/v1/store/countries';\n const headers = {\n 'Accept-Language': this._config.locale,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.get(url, { headers, timeout });\n }\n}\n","import {\n isResolvableModule,\n PaymentIntegrationService,\n PaymentStrategy,\n PaymentStrategyFactory,\n PaymentStrategyResolveId,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ResolveIdRegistry } from '../common/registry';\nimport * as defaultPaymentStrategyFactories from '../generated/payment-strategies';\n\nexport interface PaymentStrategyFactories {\n [key: string]: PaymentStrategyFactory;\n}\n\nexport default function createPaymentStrategyRegistry(\n paymentIntegrationService: PaymentIntegrationService,\n paymentStrategyFactories: PaymentStrategyFactories = defaultPaymentStrategyFactories,\n options: { useFallback: boolean } = { useFallback: false },\n): ResolveIdRegistry {\n const { useFallback } = options;\n const registry = new ResolveIdRegistry(useFallback);\n\n for (const [, createPaymentStrategy] of Object.entries(paymentStrategyFactories)) {\n if (\n !isResolvableModule, PaymentStrategyResolveId>(\n createPaymentStrategy,\n )\n ) {\n continue;\n }\n\n for (const resolverId of createPaymentStrategy.resolveIds) {\n registry.register(resolverId, () => createPaymentStrategy(paymentIntegrationService));\n }\n }\n\n return registry;\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if we are trying to make an order finalization request for a\n * payment method that does not require such procedure.\n */\nexport default class OrderFinalizationNotRequiredError extends StandardError {\n constructor() {\n super('The current order does not need to be finalized at this stage.');\n\n this.name = 'OrderFinalizationNotRequiredError';\n this.type = 'order_finalization_not_required';\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { LoadOrderPaymentsAction } from '../order';\n\nexport enum PaymentStrategyActionType {\n ExecuteFailed = 'PAYMENT_STRATEGY_EXECUTE_FAILED',\n ExecuteRequested = 'PAYMENT_STRATEGY_EXECUTE_REQUESTED',\n ExecuteSucceeded = 'PAYMENT_STRATEGY_EXECUTE_SUCCEEDED',\n FinalizeFailed = 'PAYMENT_STRATEGY_FINALIZE_FAILED',\n FinalizeRequested = 'PAYMENT_STRATEGY_FINALIZE_REQUESTED',\n FinalizeSucceeded = 'PAYMENT_STRATEGY_FINALIZE_SUCCEEDED',\n InitializeFailed = 'PAYMENT_STRATEGY_INITIALIZE_FAILED',\n InitializeRequested = 'PAYMENT_STRATEGY_INITIALIZE_REQUESTED',\n InitializeSucceeded = 'PAYMENT_STRATEGY_INITIALIZE_SUCCEEDED',\n DeinitializeFailed = 'PAYMENT_STRATEGY_DEINITIALIZE_FAILED',\n DeinitializeRequested = 'PAYMENT_STRATEGY_DEINITIALIZE_REQUESTED',\n DeinitializeSucceeded = 'PAYMENT_STRATEGY_DEINITIALIZE_SUCCEEDED',\n WidgetInteractionStarted = 'PAYMENT_STRATEGY_WIDGET_INTERACTION_STARTED',\n WidgetInteractionFinished = 'PAYMENT_STRATEGY_WIDGET_INTERACTION_FINISHED',\n WidgetInteractionFailed = 'PAYMENT_STRATEGY_WIDGET_INTERACTION_FAILED',\n}\n\nexport type PaymentStrategyAction =\n | PaymentStrategyExecuteAction\n | PaymentStrategyFinalizeAction\n | PaymentStrategyInitializeAction\n | PaymentStrategyDeinitializeAction\n | PaymentStrategyWidgetAction;\n\nexport type PaymentStrategyExecuteAction =\n | ExecuteRequestedAction\n | ExecuteSucceededAction\n | ExecuteFailedAction\n | LoadOrderPaymentsAction;\n\nexport type PaymentStrategyFinalizeAction =\n | FinalizeRequestedAction\n | FinalizeSucceededAction\n | FinalizeFailedAction\n | LoadOrderPaymentsAction;\n\nexport type PaymentStrategyInitializeAction =\n | InitializeRequestedAction\n | InitializeSucceededAction\n | InitializeFailedAction;\n\nexport type PaymentStrategyDeinitializeAction =\n | DeinitializeRequestedAction\n | DeinitializeSucceededAction\n | DeinitializeFailedAction;\n\nexport type PaymentStrategyWidgetAction =\n | WidgetInteractionStartedAction\n | WidgetInteractionFinishedAction\n | WidgetInteractionFailedAction;\n\nexport interface ExecuteRequestedAction extends Action {\n type: PaymentStrategyActionType.ExecuteRequested;\n}\n\nexport interface ExecuteSucceededAction extends Action {\n type: PaymentStrategyActionType.ExecuteSucceeded;\n}\n\nexport interface ExecuteFailedAction extends Action {\n type: PaymentStrategyActionType.ExecuteFailed;\n}\n\nexport interface FinalizeRequestedAction extends Action {\n type: PaymentStrategyActionType.FinalizeRequested;\n}\n\nexport interface FinalizeSucceededAction extends Action {\n type: PaymentStrategyActionType.FinalizeSucceeded;\n}\n\nexport interface FinalizeFailedAction extends Action {\n type: PaymentStrategyActionType.FinalizeFailed;\n}\n\nexport interface InitializeRequestedAction extends Action {\n type: PaymentStrategyActionType.InitializeRequested;\n}\n\nexport interface InitializeSucceededAction extends Action {\n type: PaymentStrategyActionType.InitializeSucceeded;\n}\n\nexport interface InitializeFailedAction extends Action {\n type: PaymentStrategyActionType.InitializeFailed;\n}\n\nexport interface DeinitializeRequestedAction extends Action {\n type: PaymentStrategyActionType.DeinitializeRequested;\n}\n\nexport interface DeinitializeSucceededAction extends Action {\n type: PaymentStrategyActionType.DeinitializeSucceeded;\n}\n\nexport interface DeinitializeFailedAction extends Action {\n type: PaymentStrategyActionType.DeinitializeFailed;\n}\n\nexport interface WidgetInteractionStartedAction extends Action {\n type: PaymentStrategyActionType.WidgetInteractionStarted;\n}\n\nexport interface WidgetInteractionFinishedAction extends Action {\n type: PaymentStrategyActionType.WidgetInteractionFinished;\n}\n\nexport interface WidgetInteractionFailedAction extends Action {\n type: PaymentStrategyActionType.WidgetInteractionFailed;\n}\n","enum PaymentStrategyType {\n ADYENV2 = 'adyenv2',\n ADYENV2_GOOGLEPAY = 'googlepayadyenv2',\n ADYENV3 = 'adyenv3',\n ADYENV3_GOOGLEPAY = 'googlepayadyenv3',\n AFFIRM = 'affirm',\n AFTERPAY = 'afterpay',\n AUTHORIZENET_GOOGLE_PAY = 'googlepayauthorizenet',\n AMAZONPAY = 'amazonpay',\n APPLEPAY = 'applepay',\n BARCLAYS = 'barclays',\n BLUESNAPV2 = 'bluesnapv2',\n BOLT = 'bolt',\n CBA_MPGS = 'cba_mpgs',\n CHECKOUTCOM = 'checkoutcom',\n CHECKOUTCOM_APM = 'checkoutcomapm',\n CHECKOUTCOM_FAWRY = 'checkoutcomfawry',\n CHECKOUTCOM_SEPA = 'checkoutcomsepa',\n CHECKOUTCOM_IDEAL = 'checkoutcomideal',\n CREDIT_CARD = 'creditcard',\n CHECKOUTCOM_GOOGLE_PAY = 'googlepaycheckoutcom',\n CLEARPAY = 'clearpay',\n CONVERGE = 'converge',\n CYBERSOURCE = 'cybersource',\n CYBERSOURCEV2 = 'cybersourcev2',\n BNZ = 'bnz',\n BNZ_GOOGLEPAY = 'googlepaybnz',\n DIGITALRIVER = 'digitalriver',\n CYBERSOURCEV2_GOOGLE_PAY = 'googlepaycybersourcev2',\n HUMM = 'humm',\n KLARNA = 'klarna',\n KLARNAV2 = 'klarnav2',\n LAYBUY = 'laybuy',\n LEGACY = 'legacy',\n MOLLIE = 'mollie',\n MONERIS = 'moneris',\n NO_PAYMENT_DATA_REQUIRED = 'nopaymentdatarequired',\n OFFLINE = 'offline',\n OFFSITE = 'offsite',\n OPY = 'opy',\n ORBITAL_GOOGLE_PAY = 'googlepayorbital',\n PAYPAL = 'paypal',\n PAYPAL_EXPRESS = 'paypalexpress',\n PAYPAL_EXPRESS_CREDIT = 'paypalexpresscredit',\n PAYPAL_COMMERCE = 'paypalcommerce',\n PAYPAL_COMMERCE_CREDIT = 'paypalcommercecredit',\n PAYPAL_COMMERCE_CREDIT_CARD = 'paypalcommercecreditcards',\n PAYPAL_COMMERCE_ALTERNATIVE_METHODS = 'paypalcommercealternativemethods',\n PAYPAL_COMMERCE_VENMO = 'paypalcommercevenmo',\n PPSDK = 'PAYMENT_TYPE_SDK',\n QUADPAY = 'quadpay',\n SAGE_PAY = 'sagepay',\n SQUARE = 'squarev2',\n STRIPEV3 = 'stripev3',\n STRIPE_UPE = 'stripeupe',\n STRIPE_UPE_GOOGLE_PAY = 'googlepaystripeupe',\n BRAINTREE = 'braintree',\n BRAINTREE_PAYPAL = 'braintreepaypal',\n BRAINTREE_VENMO = 'braintreevenmo',\n BRAINTREE_PAYPAL_CREDIT = 'braintreepaypalcredit',\n BRAINTREE_VISA_CHECKOUT = 'braintreevisacheckout',\n BRAINTREE_GOOGLE_PAY = 'googlepaybraintree',\n CHASE_PAY = 'chasepay',\n WE_PAY = 'wepay',\n WORLDPAYACCESS = 'worldpayaccess',\n WORLDPAYACCESS_GOOGLE_PAY = 'googlepayworldpayaccess',\n MASTERPASS = 'masterpass',\n STRIPE_GOOGLE_PAY = 'googlepaystripe',\n SEZZLE = 'sezzle',\n ZIP = 'zip',\n}\n\nexport default PaymentStrategyType;\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, empty, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { PaymentStrategy as PaymentStrategyV2 } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { InternalCheckoutSelectors, ReadableCheckoutStore } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { RequestOptions } from '../common/http-request';\nimport {\n LoadOrderPaymentsAction,\n OrderActionCreator,\n OrderPaymentRequestBody,\n OrderRequestBody,\n} from '../order';\nimport { OrderFinalizationNotRequiredError } from '../order/errors';\nimport { SpamProtectionAction, SpamProtectionActionCreator } from '../spam-protection';\n\nimport PaymentMethod from './payment-method';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from './payment-request-options';\nimport {\n PaymentStrategyActionType,\n PaymentStrategyDeinitializeAction,\n PaymentStrategyExecuteAction,\n PaymentStrategyFinalizeAction,\n PaymentStrategyInitializeAction,\n PaymentStrategyWidgetAction,\n} from './payment-strategy-actions';\nimport PaymentStrategyRegistry from './payment-strategy-registry';\nimport PaymentStrategyRegistryV2 from './payment-strategy-registry-v2';\nimport PaymentStrategyType from './payment-strategy-type';\nimport { PaymentStrategy } from './strategies';\n\nexport default class PaymentStrategyActionCreator {\n constructor(\n private _strategyRegistry: PaymentStrategyRegistry,\n private _strategyRegistryV2: PaymentStrategyRegistryV2,\n private _orderActionCreator: OrderActionCreator,\n private _spamProtectionActionCreator: SpamProtectionActionCreator,\n ) {}\n\n execute(\n payload: OrderRequestBody,\n options?: RequestOptions,\n ): ThunkAction {\n const { payment = {} as OrderPaymentRequestBody, useStoreCredit } = payload;\n const meta = { methodId: payment.methodId };\n\n return (store) => {\n const { checkout } = store.getState();\n const { shouldExecuteSpamCheck } = checkout.getCheckoutOrThrow();\n\n return concat(\n shouldExecuteSpamCheck\n ? this._spamProtectionActionCreator.verifyCheckoutSpamProtection()(store)\n : empty(),\n of(createAction(PaymentStrategyActionType.ExecuteRequested, undefined, meta)),\n defer(() => {\n const state = store.getState();\n\n let strategy: PaymentStrategy | PaymentStrategyV2;\n\n if (state.payment.isPaymentDataRequired(useStoreCredit)) {\n const method = state.paymentMethods.getPaymentMethod(\n payment.methodId,\n payment.gatewayId,\n );\n\n if (!method) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n strategy = this._getStrategy(method);\n } else {\n strategy = this._strategyRegistryV2.get({\n id: PaymentStrategyType.NO_PAYMENT_DATA_REQUIRED,\n });\n }\n\n const promise: Promise = strategy.execute(\n payload,\n {\n ...options,\n methodId: payment.methodId,\n gatewayId: payment.gatewayId,\n },\n );\n\n return promise.then(() =>\n createAction(PaymentStrategyActionType.ExecuteSucceeded, undefined, meta),\n );\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(PaymentStrategyActionType.ExecuteFailed, error, meta),\n ),\n );\n };\n }\n\n finalize(\n options?: RequestOptions,\n ): ThunkAction {\n return (store) =>\n concat(\n of(createAction(PaymentStrategyActionType.FinalizeRequested)),\n this._loadOrderPaymentsIfNeeded(store, options),\n defer(async () => {\n const state = store.getState();\n const { providerId = '', gatewayId = '' } = state.payment.getPaymentId() || {};\n const method = state.paymentMethods.getPaymentMethod(providerId, gatewayId);\n\n if (!method) {\n throw new OrderFinalizationNotRequiredError();\n }\n\n const strategy = this._getStrategy(method);\n\n await strategy.finalize({\n ...options,\n methodId: method.id,\n gatewayId: method.gateway,\n });\n\n return createAction(PaymentStrategyActionType.FinalizeSucceeded, undefined, {\n methodId: method.id,\n });\n }),\n ).pipe(\n catchError((error) => {\n const state = store.getState();\n const payment = state.payment.getPaymentId();\n\n return throwErrorAction(PaymentStrategyActionType.FinalizeFailed, error, {\n methodId: payment && payment.providerId,\n });\n }),\n );\n }\n\n initialize(\n options: PaymentInitializeOptions,\n ): ThunkAction {\n const { methodId, gatewayId } = options;\n\n return (store) =>\n defer(() => {\n const state = store.getState();\n const method = state.paymentMethods.getPaymentMethod(methodId, gatewayId);\n\n if (!method) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (methodId && state.paymentStrategies.isInitialized({ methodId, gatewayId })) {\n return empty();\n }\n\n const strategy = this._getStrategy(method);\n\n const promise: Promise = strategy.initialize({\n ...options,\n methodId,\n gatewayId,\n });\n\n return concat(\n of(\n createAction(PaymentStrategyActionType.InitializeRequested, undefined, {\n methodId,\n gatewayId,\n }),\n ),\n promise.then(() =>\n createAction(PaymentStrategyActionType.InitializeSucceeded, undefined, {\n methodId,\n gatewayId,\n }),\n ),\n );\n }).pipe(\n catchError((error) =>\n throwErrorAction(PaymentStrategyActionType.InitializeFailed, error, {\n methodId,\n gatewayId,\n }),\n ),\n );\n }\n\n deinitialize(\n options: PaymentRequestOptions,\n ): ThunkAction {\n const { methodId, gatewayId } = options;\n\n return (store) =>\n defer(() => {\n const state = store.getState();\n const method = state.paymentMethods.getPaymentMethod(methodId, gatewayId);\n\n if (!method) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (methodId && !state.paymentStrategies.isInitialized({ methodId, gatewayId })) {\n return empty();\n }\n\n const strategy = this._getStrategy(method);\n\n const promise: Promise = strategy.deinitialize({\n ...options,\n methodId,\n gatewayId,\n });\n\n return concat(\n of(\n createAction(PaymentStrategyActionType.DeinitializeRequested, undefined, {\n methodId,\n gatewayId,\n }),\n ),\n promise.then(() =>\n createAction(PaymentStrategyActionType.DeinitializeSucceeded, undefined, {\n methodId,\n gatewayId,\n }),\n ),\n );\n }).pipe(\n catchError((error) =>\n throwErrorAction(PaymentStrategyActionType.DeinitializeFailed, error, {\n methodId,\n gatewayId,\n }),\n ),\n );\n }\n\n widgetInteraction(\n method: () => Promise,\n options?: PaymentRequestOptions,\n ): Observable {\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n return concat(\n of(createAction(PaymentStrategyActionType.WidgetInteractionStarted, undefined, meta)),\n defer(() =>\n method().then(() =>\n createAction(\n PaymentStrategyActionType.WidgetInteractionFinished,\n undefined,\n meta,\n ),\n ),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(PaymentStrategyActionType.WidgetInteractionFailed, error, meta),\n ),\n );\n }\n\n private _getStrategy(method: PaymentMethod): PaymentStrategy | PaymentStrategyV2 {\n let strategy: PaymentStrategy | PaymentStrategyV2;\n\n try {\n strategy = this._strategyRegistry.getByMethod(method);\n } catch {\n strategy = this._strategyRegistryV2.get({\n id: method.id,\n gateway: method.gateway,\n type: method.type,\n });\n }\n\n return strategy;\n }\n\n private _loadOrderPaymentsIfNeeded(\n store: ReadableCheckoutStore,\n options?: RequestOptions,\n ): Observable {\n const state = store.getState();\n const checkout = state.checkout.getCheckout();\n\n if (checkout && checkout.orderId) {\n return this._orderActionCreator.loadOrderPayments(checkout.orderId, options);\n }\n\n return empty();\n }\n}\n","import { default as storage } from 'local-storage-fallback';\n\nexport default class BrowserStorage {\n constructor(private _namespace: string) {}\n\n getItem(key: string): TValue | null {\n const rawValue = storage.getItem(this.withNamespace(key));\n\n if (rawValue === null) {\n return null;\n }\n\n try {\n return JSON.parse(rawValue);\n } catch (error) {\n // Clean up invalid values\n this.removeItem(this.withNamespace(key));\n\n return null;\n }\n }\n\n getItemOnce(key: string): TValue | null {\n const value = this.getItem(key);\n\n this.removeItem(key);\n\n return value;\n }\n\n setItem(key: string, value: TValue): void {\n return storage.setItem(this.withNamespace(key), JSON.stringify(value));\n }\n\n removeItem(key: string): void {\n return storage.removeItem(this.withNamespace(key));\n }\n\n private withNamespace(key: string): string {\n return `${this._namespace}.${key}`;\n }\n}\n","export const HOSTED = 'PAYMENT_TYPE_HOSTED';\nexport const OFFLINE = 'PAYMENT_TYPE_OFFLINE';\n","import PaymentMethod from './payment-method';\nimport PaymentStrategyType from './payment-strategy-type';\n\ntype PPSDKRequiredProperties = 'initializationStrategy';\n\nexport type PPSDKPaymentMethod = PaymentMethod & {\n type: PaymentStrategyType.PPSDK;\n} & Required>;\n\nexport const isPPSDKPaymentMethod = (\n paymentMethod: PaymentMethod,\n): paymentMethod is PPSDKPaymentMethod => {\n const { type, initializationStrategy } = paymentMethod;\n\n return type === PaymentStrategyType.PPSDK && typeof initializationStrategy?.type === 'string';\n};\n","import { ReadableDataStore } from '@bigcommerce/data-store';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { InvalidArgumentError } from '../common/error/errors';\nimport { Registry, RegistryOptions } from '../common/registry';\n\nimport PaymentMethod from './payment-method';\nimport * as paymentMethodTypes from './payment-method-types';\nimport PaymentStrategyType from './payment-strategy-type';\nimport { isPPSDKPaymentMethod } from './ppsdk-payment-method';\nimport { PaymentStrategy } from './strategies';\n\nconst checkoutcomStrategies: {\n [key: string]: PaymentStrategyType;\n} = {\n card: PaymentStrategyType.CHECKOUTCOM,\n credit_card: PaymentStrategyType.CHECKOUTCOM,\n sepa: PaymentStrategyType.CHECKOUTCOM_SEPA,\n ideal: PaymentStrategyType.CHECKOUTCOM_IDEAL,\n fawry: PaymentStrategyType.CHECKOUTCOM_FAWRY,\n};\n\nexport default class PaymentStrategyRegistry extends Registry<\n PaymentStrategy,\n PaymentStrategyType\n> {\n constructor(\n private _store: ReadableDataStore,\n options?: PaymentStrategyRegistryOptions,\n ) {\n super(options);\n }\n\n getByMethod(paymentMethod?: PaymentMethod): PaymentStrategy {\n if (!paymentMethod) {\n return this.get();\n }\n\n const token = this._getToken(paymentMethod);\n\n const cacheToken = [paymentMethod.gateway, paymentMethod.id]\n .filter((value) => value !== undefined && value !== null)\n .join('-');\n\n return this.get(token, cacheToken);\n }\n\n private _getToken(paymentMethod: PaymentMethod): PaymentStrategyType {\n const features = this._store.getState().config.getStoreConfig()?.checkoutSettings.features;\n\n if (\n paymentMethod.id === 'squarev2' &&\n features &&\n features['PROJECT-4113.squarev2_web_payments_sdk']\n ) {\n throw new Error('SquareV2 requires using registryV2');\n }\n\n if (isPPSDKPaymentMethod(paymentMethod)) {\n return PaymentStrategyType.PPSDK;\n }\n\n if (paymentMethod.gateway === 'klarna') {\n return PaymentStrategyType.KLARNAV2;\n }\n\n if (paymentMethod.gateway === PaymentStrategyType.CHECKOUTCOM) {\n return paymentMethod.id in checkoutcomStrategies\n ? checkoutcomStrategies[paymentMethod.id]\n : PaymentStrategyType.CHECKOUTCOM_APM;\n }\n\n const methodId = paymentMethod.gateway || paymentMethod.id;\n\n if (this._hasFactoryForMethod(methodId)) {\n return methodId;\n }\n\n if (paymentMethod.type === paymentMethodTypes.OFFLINE) {\n return PaymentStrategyType.OFFLINE;\n }\n\n throw new InvalidArgumentError(`'${methodId}' is not registered.`);\n }\n\n private _hasFactoryForMethod(methodId: string): methodId is PaymentStrategyType {\n return this._hasFactory(methodId);\n }\n}\n\nexport interface PaymentStrategyRegistryOptions extends RegistryOptions {\n clientSidePaymentProviders?: string[];\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { ContentType, INTERNAL_USE_ONLY, SDK_VERSION_HEADERS } from '../common/http-request';\n\nexport default class StorefrontPaymentRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n async saveExternalId(methodId: string, token: string): Promise {\n const url = `/api/storefront/payment/${methodId}/save-external-id`;\n const options = {\n headers: {\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n body: {\n externalId: token,\n provider: methodId,\n },\n };\n\n await this._requestSender.post(url, options);\n }\n}\n","import { ScriptLoader, StylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { AdyenClient, AdyenConfiguration, AdyenHostWindow } from './adyenv2';\n\nexport default class AdyenV2ScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _stylesheetLoader: StylesheetLoader,\n private _window: AdyenHostWindow = window,\n ) {}\n\n async load(configuration: AdyenConfiguration): Promise {\n await Promise.all([\n this._stylesheetLoader.loadStylesheet(\n `https://checkoutshopper-${configuration.environment}.adyen.com/checkoutshopper/sdk/3.10.1/adyen.css`,\n ),\n this._scriptLoader.loadScript(\n `https://checkoutshopper-${configuration.environment}.adyen.com/checkoutshopper/sdk/3.10.1/adyen.js`,\n ),\n ]);\n\n if (!this._window.AdyenCheckout) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return new this._window.AdyenCheckout(configuration);\n }\n}\n","import { ScriptLoader, StylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { AdyenClient, AdyenConfiguration, AdyenHostWindow } from './adyenv3';\n\nexport default class AdyenV3ScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _stylesheetLoader: StylesheetLoader,\n private _window: AdyenHostWindow = window,\n ) {}\n\n async load(configuration: AdyenConfiguration): Promise {\n await Promise.all([\n this._stylesheetLoader.loadStylesheet(\n `https://checkoutshopper-${configuration.environment}.adyen.com/checkoutshopper/sdk/5.24.0/adyen.css`,\n ),\n this._scriptLoader.loadScript(\n `https://checkoutshopper-${configuration.environment}.adyen.com/checkoutshopper/sdk/5.24.0/adyen.js`,\n ),\n ]);\n\n if (!this._window.AdyenCheckout) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n const checkout = await this._window.AdyenCheckout(configuration);\n\n return checkout;\n }\n}\n","import { InvalidArgumentError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when we are unable to submit a payment because\n * the caller has not provided all the required fields, i.e.: if an argument is\n * missing or it is not the expected data type.\n */\nexport default class PaymentArgumentInvalidError extends InvalidArgumentError {\n constructor(invalidFields?: string[]) {\n let message = 'Unable to submit payment for the order because the payload is invalid.';\n\n if (invalidFields) {\n message = `${message} Make sure the following fields are provided correctly: ${invalidFields.join(\n ', ',\n )}.`;\n }\n\n super(message);\n\n this.name = 'PaymentArgumentInvalidError';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when the payment flow is cancelled. It could be\n * due to a deliberate user interaction, i.e.: the user clicks on a cancel\n * button which dismisses the payment modal.\n */\nexport default class PaymentMethodCancelledError extends StandardError {\n constructor(message?: string) {\n super(message || 'Payment process was cancelled.');\n\n this.name = 'PaymentMethodCancelledError';\n this.type = 'payment_cancelled';\n }\n}\n","import { PaymentMethodInvalidError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { LineItemCategory } from '../../../cart';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { AmountTransformer } from '../../../common/utility';\nimport { Order, OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { Consignment } from '../../../shipping';\nimport { PaymentArgumentInvalidError, PaymentMethodCancelledError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport {\n Affirm,\n AffirmAddress,\n AffirmDiscount,\n AffirmFailResponse,\n AffirmItem,\n AffirmRequestData,\n AffirmSuccessResponse,\n} from './affirm';\nimport AffirmScriptLoader from './affirm-script-loader';\n\nexport default class AffirmPaymentStrategy implements PaymentStrategy {\n private _affirm?: Affirm;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _affirmScriptLoader: AffirmScriptLoader,\n ) {}\n\n initialize(options: PaymentInitializeOptions): Promise {\n return this._store\n .dispatch(this._paymentMethodActionCreator.loadPaymentMethod(options.methodId))\n .then((state) => {\n const paymentMethod = state.paymentMethods.getPaymentMethod(options.methodId);\n\n if (!paymentMethod || !paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n config: { testMode },\n clientToken: publicKey,\n } = paymentMethod;\n\n return this._affirmScriptLoader.load(publicKey, testMode);\n })\n .then((affirm) => {\n this._affirm = affirm;\n\n return this._store.getState();\n });\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const methodId = payload.payment && payload.payment.methodId;\n const { useStoreCredit } = payload;\n const { _affirm } = this;\n\n if (!_affirm) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n return this._store\n .dispatch(this._orderActionCreator.submitOrder({ useStoreCredit }, options))\n .then(() => {\n _affirm.checkout(this._getCheckoutInformation());\n\n return new Promise((resolve, reject) => {\n _affirm.checkout.open({\n onFail: (failObject: AffirmFailResponse) => {\n failObject.reason === 'canceled'\n ? reject(new PaymentMethodCancelledError())\n : reject(new PaymentMethodInvalidError());\n },\n onSuccess: (successObject) => {\n resolve(successObject);\n },\n });\n _affirm.ui.error.on('close', () => {\n reject(new PaymentMethodCancelledError());\n });\n });\n })\n .then((result) => {\n const paymentPayload = {\n methodId,\n paymentData: { nonce: result.checkout_token },\n };\n\n return this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentPayload),\n );\n });\n }\n\n deinitialize(): Promise {\n if (this._affirm) {\n this._affirm = undefined;\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private _getCheckoutInformation(): AffirmRequestData {\n const state = this._store.getState();\n const config = state.config.getStoreConfig();\n const consignments = state.consignments.getConsignments();\n const order = state.order.getOrder();\n\n if (!config) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n if (!order) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const amountTransformer = new AmountTransformer(order.currency.decimalPlaces);\n const billingAddress = this._getBillingAddress();\n\n return {\n merchant: {\n user_confirmation_url: config.links.checkoutLink,\n user_cancel_url: config.links.checkoutLink,\n user_confirmation_url_action: 'POST',\n },\n shipping: this._getShippingAddress() || billingAddress,\n billing: billingAddress,\n items: this._getItems(amountTransformer, order),\n metadata: {\n shipping_type: this._getShippingType(consignments),\n mode: 'modal',\n platform_type: 'BigCommerce',\n platform_version: '',\n platform_affirm: '',\n },\n discounts: this._getDiscounts(amountTransformer, order),\n order_id: order.orderId ? order.orderId.toString() : '',\n shipping_amount: amountTransformer.toInteger(order.shippingCostTotal),\n tax_amount: amountTransformer.toInteger(order.taxTotal),\n total: amountTransformer.toInteger(order.orderAmount),\n };\n }\n\n private _getShippingType(consignments?: Consignment[]): string {\n if (!consignments) {\n return '';\n }\n\n const consignment = consignments[0];\n\n return consignment && consignment.selectedShippingOption\n ? consignment.selectedShippingOption.type\n : '';\n }\n\n private _getBillingAddress(): AffirmAddress {\n const state = this._store.getState();\n const billingAddress = state.billingAddress.getBillingAddress();\n\n if (!billingAddress) {\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n\n const billingInformation = {\n name: {\n first: billingAddress.firstName,\n last: billingAddress.lastName,\n full: `${billingAddress.firstName} ${billingAddress.lastName}`,\n },\n address: {\n line1: billingAddress.address1,\n line2: billingAddress.address2,\n city: billingAddress.city,\n state: billingAddress.stateOrProvinceCode,\n zipcode: billingAddress.postalCode,\n country: billingAddress.countryCode,\n },\n phone_number: billingAddress.phone,\n email: billingAddress.email,\n };\n\n return billingInformation;\n }\n\n private _getShippingAddress(): AffirmAddress | undefined {\n const state = this._store.getState();\n const shippingAddress = state.shippingAddress.getShippingAddress();\n\n if (!shippingAddress) {\n return;\n }\n\n const shippingInformation = {\n name: {\n first: shippingAddress.firstName,\n last: shippingAddress.lastName,\n full: `${shippingAddress.firstName} ${shippingAddress.lastName}`,\n },\n address: {\n line1: shippingAddress.address1,\n line2: shippingAddress.address2,\n city: shippingAddress.city,\n state: shippingAddress.stateOrProvinceCode,\n zipcode: shippingAddress.postalCode,\n country: shippingAddress.countryCode,\n },\n phone_number: shippingAddress.phone,\n };\n\n return shippingInformation;\n }\n\n private _getItems(amountTransformer: AmountTransformer, order: Order): AffirmItem[] {\n const items: AffirmItem[] = [];\n\n for (const item of order.lineItems.physicalItems) {\n items.push({\n display_name: item.name,\n sku: item.sku,\n unit_price: amountTransformer.toInteger(item.salePrice),\n qty: item.quantity,\n item_image_url: item.imageUrl,\n item_url: item.url,\n categories: this._getCategories(item.categories),\n });\n }\n\n for (const item of order.lineItems.digitalItems) {\n items.push({\n display_name: item.name,\n sku: item.sku,\n unit_price: amountTransformer.toInteger(item.salePrice),\n qty: item.quantity,\n item_image_url: item.imageUrl,\n item_url: item.url,\n categories: this._getCategories(item.categories),\n });\n }\n\n for (const item of order.lineItems.giftCertificates) {\n items.push({\n display_name: item.name,\n sku: '',\n unit_price: amountTransformer.toInteger(item.amount),\n qty: 1,\n item_image_url: '',\n item_url: '',\n });\n }\n\n if (order.lineItems.customItems) {\n for (const item of order.lineItems.customItems) {\n items.push({\n display_name: item.name,\n sku: item.sku,\n unit_price: amountTransformer.toInteger(item.listPrice),\n qty: item.quantity,\n item_image_url: '',\n item_url: '',\n });\n }\n }\n\n return items;\n }\n\n private _getDiscounts(amountTransformer: AmountTransformer, order: Order): AffirmDiscount {\n const discounts: AffirmDiscount = {};\n\n for (const line of order.coupons) {\n if (line.discountedAmount > 0) {\n discounts[line.code] = {\n discount_amount: amountTransformer.toInteger(line.discountedAmount),\n discount_display_name: line.displayName,\n };\n }\n }\n\n if (order.discountAmount > 0) {\n discounts.DISCOUNTED_AMOUNT = {\n discount_amount: amountTransformer.toInteger(order.discountAmount),\n discount_display_name: 'discount',\n };\n }\n\n return discounts;\n }\n\n private _getCategories(categories?: LineItemCategory[][]): string[][] {\n if (!categories) {\n return [[]];\n }\n\n return categories.map((categoryTree) => categoryTree.map((category) => category.name));\n }\n}\n","import { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { Affirm, AffirmHostWindow, AffirmScripts } from './affirm';\nimport loadAffirmJS from './affirmJs';\n\nexport default class AffirmScriptLoader {\n constructor(public _window: AffirmHostWindow = window) {}\n\n load(apikey = '', testMode?: boolean): Promise {\n const scriptURI = this._getScriptURI(testMode);\n\n loadAffirmJS(apikey, scriptURI);\n\n if (!this._window.affirm) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return Promise.resolve(this._window.affirm);\n }\n\n private _getScriptURI(testMode = false): string {\n const SCRIPTS_DEFAULT: AffirmScripts = {\n PROD: '//cdn1.affirm.com/js/v2/affirm.js',\n SANDBOX: '//cdn1-sandbox.affirm.com/js/v2/affirm.js',\n };\n\n return testMode ? SCRIPTS_DEFAULT.SANDBOX : SCRIPTS_DEFAULT.PROD;\n }\n}\n","/**\n * Used this approach as Affirm uses snipped for initializing. Please refer to Affirm documentation in: https://docs.affirm.com/Integrate_Affirm/Direct_API#1._Add_Affirm.js\n */\nimport { Affirm, AffirmHostWindow } from './affirm';\n\ninterface AffirmConfig {\n public_api_key: string;\n script: string;\n}\n\nexport default function loadAffirmJS(apiKey: string, scriptURL: string) {\n const _AFFIRM_CONFIG: AffirmConfig = {\n public_api_key: apiKey,\n script: scriptURL,\n };\n\n (function foo(\n m: AffirmHostWindow | any,\n g: AffirmConfig,\n n: 'affirm',\n d: 'checkout',\n a: 'ui',\n e: 'script',\n h: 'ready',\n c: 'jsReady',\n ) {\n const b = m[n] || {};\n const k = document.createElement(e);\n const p = document.getElementsByTagName(e)[0];\n const l = function bar(a: Affirm | any, b: keyof Affirm, c: string) {\n return function baz() {\n a[b]._.push([c, arguments]); /* eslint-disable-line */\n };\n };\n\n b[d] = l(b, d, 'set');\n\n const f = b[d];\n\n b[a] = {};\n b[a]._ = [];\n f._ = [];\n b._ = [];\n b[a][h] = l(b, a, h);\n\n b[c] = function qux() {\n b._.push([h, arguments]); /* eslint-disable-line */\n };\n\n let a1 = 0;\n\n for (\n const c1 = 'set add save post open empty reset on off trigger ready setProduct'.split(\n ' ',\n );\n a1 < c1.length;\n a1++\n ) {\n f[c1[a1]] = l(b, d, c1[a1]);\n }\n\n let a2 = 0;\n\n for (const c2 = ['get', 'token', 'url', 'items']; a2 < c2.length; a2++) {\n f[c2[a2]] = function foobar() {};\n }\n\n k.async = !0;\n k.src = g[e];\n\n if (p.parentNode) {\n p.parentNode.insertBefore(k, p);\n }\n\n delete (g as Partial)[e];\n f(g);\n m[n] = b;\n })(window, _AFFIRM_CONFIG, 'affirm', 'checkout', 'ui', 'script', 'ready', 'jsReady');\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if the order finalization request\n * was not completed successfully.\n */\nexport default class OrderFinalizationNotCompletedError extends StandardError {\n constructor(message?: string) {\n super(message || 'The current order could not be finalized successfully');\n\n this.name = 'OrderFinalizationNotCompletedError';\n this.type = 'order_finalization_not_completed';\n }\n}\n","import { CheckoutStore, CheckoutValidator, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { RequestOptions } from '../../../common/http-request';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotCompletedError } from '../../../order/errors';\nimport { RemoteCheckoutRequestSender } from '../../../remote-checkout';\nimport { StoreCreditActionCreator } from '../../../store-credit';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport AfterpayScriptLoader from './afterpay-script-loader';\nimport AfterpaySdk from './afterpay-sdk';\n\nexport default class AfterpayPaymentStrategy implements PaymentStrategy {\n private _afterpaySdk?: AfterpaySdk;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutValidator: CheckoutValidator,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _remoteCheckoutRequestSender: RemoteCheckoutRequestSender,\n private _storeCreditActionCreator: StoreCreditActionCreator,\n private _afterpayScriptLoader: AfterpayScriptLoader,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const state = this._store.getState();\n const paymentMethod = state.paymentMethods.getPaymentMethod(\n options.methodId,\n options.gatewayId,\n );\n const currencyCode = state.cart.getCart()?.currency.code || '';\n const countryCode = this._mapCurrencyToISO2(currencyCode);\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._afterpaySdk = await this._afterpayScriptLoader.load(paymentMethod, countryCode);\n\n return this._store.getState();\n }\n\n deinitialize(): Promise {\n if (this._afterpaySdk) {\n this._afterpaySdk = undefined;\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n if (!payload.payment) {\n throw new PaymentArgumentInvalidError(['payment.gatewayId', 'payment.methodId']);\n }\n\n const { gatewayId, methodId } = payload.payment;\n\n if (!gatewayId || !methodId) {\n throw new PaymentArgumentInvalidError(['payment.gatewayId', 'payment.methodId']);\n }\n\n let state = this._store.getState();\n const currencyCode = state.cart.getCart()?.currency.code || '';\n const countryCode = this._mapCurrencyToISO2(currencyCode);\n const { useStoreCredit } = payload;\n\n if (useStoreCredit !== undefined) {\n state = await this._store.dispatch(\n this._storeCreditActionCreator.applyStoreCredit(useStoreCredit),\n );\n }\n\n await this._checkoutValidator.validate(state.checkout.getCheckout(), options);\n\n state = await this._loadPaymentMethod(gatewayId, methodId, options);\n\n await this._redirectToAfterpay(\n countryCode,\n state.paymentMethods.getPaymentMethod(methodId, gatewayId),\n );\n\n // Afterpay will handle the rest of the flow so return a promise that doesn't really resolve\n return new Promise(() => {});\n }\n\n async finalize(options: PaymentRequestOptions): Promise {\n const state = this._store.getState();\n const payment = state.payment.getPaymentId();\n const config = state.config.getContextConfig();\n\n if (!payment) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!config || !config.payment.token) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const paymentPayload = {\n methodId: payment.providerId,\n paymentData: { nonce: config.payment.token },\n };\n\n await this._store.dispatch(this._orderActionCreator.submitOrder({}, options));\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentPayload),\n );\n } catch (error) {\n await this._remoteCheckoutRequestSender.forgetCheckout();\n await this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethods());\n\n throw new OrderFinalizationNotCompletedError(error.body?.errors?.[0]?.message);\n }\n }\n\n private _redirectToAfterpay(countryCode: string, paymentMethod?: PaymentMethod): void {\n if (!this._afterpaySdk || !paymentMethod || !paymentMethod.clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._afterpaySdk.initialize({ countryCode });\n this._afterpaySdk.redirect({ token: paymentMethod.clientToken });\n }\n\n private _mapCurrencyToISO2(currencyCode: string): string {\n const countryByCurrency: { [key: string]: string } = {\n AUD: 'AU',\n NZD: 'NZ',\n CAD: 'CA',\n USD: 'US',\n };\n\n return countryByCurrency[currencyCode] || 'AU';\n }\n\n private async _loadPaymentMethod(\n gatewayId: string,\n methodId: string,\n options?: RequestOptions,\n ): Promise {\n try {\n return await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(gatewayId, {\n ...options,\n params: { ...options?.params, method: methodId },\n }),\n );\n } catch (error) {\n if (error instanceof RequestError && error.body?.status === 422) {\n throw new InvalidArgumentError(\n \"Afterpay can't process your payment for this order, please try another payment method\",\n );\n }\n\n throw error;\n }\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport PaymentMethod from '../../payment-method';\n\nimport AfterpaySdk from './afterpay-sdk';\nimport AfterpayWindow from './afterpay-window';\n\ninterface AfterpayScripts {\n PROD: string;\n SANDBOX: string;\n}\n\nconst SCRIPTS_DEFAULT: AfterpayScripts = {\n PROD: '//portal.afterpay.com/afterpay-async.js',\n SANDBOX: '//portal-sandbox.afterpay.com/afterpay-async.js',\n};\n\nconst SCRIPTS_US: AfterpayScripts = {\n PROD: '//portal.afterpay.com/afterpay-async.js',\n SANDBOX: '//portal.sandbox.afterpay.com/afterpay-async.js',\n};\n\n/** Class responsible for loading the Afterpay SDK */\nexport default class AfterpayScriptLoader {\n constructor(private _scriptLoader: ScriptLoader) {}\n\n /**\n * Loads the appropriate Afterpay SDK depending on the payment method data.\n *\n * @param method the payment method data\n */\n load(method: PaymentMethod, countryCode: string): Promise {\n const testMode = method.config.testMode || false;\n const scriptURI = this._getScriptURI(countryCode, testMode);\n\n return this._scriptLoader\n .loadScript(scriptURI)\n .then(() => (window as unknown as AfterpayWindow).AfterPay);\n }\n\n private _getScriptURI(countryCode: string, testMode: boolean): string {\n if (countryCode === 'US') {\n return testMode ? SCRIPTS_US.SANDBOX : SCRIPTS_US.PROD;\n }\n\n return testMode ? SCRIPTS_DEFAULT.SANDBOX : SCRIPTS_DEFAULT.PROD;\n }\n}\n","import { noop } from 'lodash';\n\nimport { CheckoutSettings } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { guard } from '../../../../src/common/utility';\nimport { StoreProfile } from '../../../../src/config';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError, PaymentMethodCancelledError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategyActionCreator from '../../payment-strategy-action-creator';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { AmazonPayV2ChangeActionType, AmazonPayV2Placement } from './amazon-pay-v2';\nimport AmazonPayV2PaymentProcessor from './amazon-pay-v2-payment-processor';\n\nexport default class AmazonPayV2PaymentStrategy implements PaymentStrategy {\n private _amazonPayButton?: HTMLDivElement;\n\n constructor(\n private _store: CheckoutStore,\n private _paymentStrategyActionCreator: PaymentStrategyActionCreator,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _amazonPayV2PaymentProcessor: AmazonPayV2PaymentProcessor,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const { methodId, amazonpay } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" argument is not provided.',\n );\n }\n\n const { features } = this._store.getState().config.getStoreConfigOrThrow().checkoutSettings;\n const paymentMethod = this._store\n .getState()\n .paymentMethods.getPaymentMethodOrThrow(methodId);\n const {\n initializationData: { paymentToken, region },\n } = paymentMethod;\n\n await this._amazonPayV2PaymentProcessor.initialize(paymentMethod);\n\n if (this._isReadyToPay(paymentToken)) {\n if (amazonpay?.editButtonId) {\n this._bindEditButton(\n amazonpay.editButtonId,\n paymentToken,\n 'changePayment',\n this._isModalFlow(region),\n );\n }\n } else {\n const { id: containerId } = this._createContainer();\n\n this._amazonPayButton = this._amazonPayV2PaymentProcessor.renderAmazonPayButton({\n checkoutState: this._store.getState(),\n containerId,\n decoupleCheckoutInitiation: this._isOneTimeTransaction(\n features,\n region.toUpperCase(),\n ),\n methodId,\n placement: AmazonPayV2Placement.Checkout,\n });\n }\n\n return this._store.getState();\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId } = payment;\n\n const { features } = this._store.getState().config.getStoreConfigOrThrow().checkoutSettings;\n const { region, paymentToken } = this._store\n .getState()\n .paymentMethods.getPaymentMethodOrThrow(methodId).initializationData;\n\n if (\n this._isReadyToPay(paymentToken) ||\n this._isOneTimeTransaction(features, region.toUpperCase())\n ) {\n const paymentPayload = {\n methodId,\n paymentData: { nonce: paymentToken || 'apb' },\n };\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(payload, options));\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentPayload),\n );\n } catch (error) {\n if (\n error instanceof RequestError &&\n error.body.status === 'additional_action_required'\n ) {\n if (paymentToken) {\n return new Promise(() =>\n window.location.assign(\n error.body.additional_action_required.data.redirect_url,\n ),\n );\n }\n\n this._amazonPayV2PaymentProcessor.prepareCheckout(\n JSON.parse(error.body.additional_action_required.data.redirect_url),\n );\n } else {\n throw error;\n }\n }\n }\n\n this._getAmazonPayButton().click();\n\n // Focus of parent window used to try and detect the user cancelling the Amazon log in modal\n // Should be refactored if/when Amazon add a modal close hook to their SDK\n if (this._isModalFlow(region)) {\n return new Promise((_, reject) => {\n const onFocus = () => {\n window.removeEventListener('focus', onFocus);\n reject(\n new PaymentMethodCancelledError(\n 'Shopper needs to login to Amazonpay to continue',\n ),\n );\n };\n\n window.addEventListener('focus', onFocus);\n });\n }\n\n return new Promise(noop);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n await this._amazonPayV2PaymentProcessor.deinitialize();\n\n this._amazonPayButton = undefined;\n\n return this._store.getState();\n }\n\n private _bindEditButton(\n buttonId: string,\n sessionId: string,\n changeAction: AmazonPayV2ChangeActionType,\n isModalFlow: boolean,\n ): void {\n const button = document.getElementById(buttonId);\n\n if (!button || !button.parentNode) {\n return;\n }\n\n if (!isModalFlow) {\n const clone = button.cloneNode(true);\n\n button.parentNode.replaceChild(clone, button);\n\n clone.addEventListener('click', () => this._showLoadingSpinner());\n }\n\n this._amazonPayV2PaymentProcessor.bindButton(buttonId, sessionId, changeAction);\n }\n\n private _isModalFlow(region: string) {\n return region === 'us';\n }\n\n private _showLoadingSpinner(): Promise {\n return this._store.dispatch(\n this._paymentStrategyActionCreator.widgetInteraction(() => new Promise(noop)),\n { queueId: 'widgetInteraction' },\n );\n }\n\n private _createContainer(): HTMLDivElement {\n let container = document.getElementById('AmazonPayButton') as HTMLDivElement;\n\n if (container) {\n return container;\n }\n\n container = document.createElement('div');\n container.id = 'AmazonPayButton';\n container.style.display = 'none';\n\n return document.body.appendChild(container);\n }\n\n private _getAmazonPayButton() {\n return guard(\n this._amazonPayButton,\n () => new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n private _isOneTimeTransaction(\n features: CheckoutSettings['features'],\n storeCountryCode: StoreProfile['storeCountryCode'],\n ): boolean {\n return (\n this._amazonPayV2PaymentProcessor.isPh4Enabled(features, storeCountryCode) &&\n features['INT-6399.amazon_pay_apb']\n );\n }\n\n private _isReadyToPay(paymentToken?: string): boolean {\n return !!paymentToken;\n }\n}\n","import { isNil, values } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { HostedForm, HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nexport default class CreditCardPaymentStrategy implements PaymentStrategy {\n protected _hostedForm?: HostedForm;\n protected _shouldRenderHostedForm?: boolean;\n\n constructor(\n protected _store: CheckoutStore,\n protected _orderActionCreator: OrderActionCreator,\n protected _paymentActionCreator: PaymentActionCreator,\n protected _hostedFormFactory: HostedFormFactory,\n ) {}\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n return this._isHostedPaymentFormEnabled(\n payload.payment?.methodId,\n payload.payment?.gatewayId,\n ) && this._shouldRenderHostedForm\n ? this._executeWithHostedForm(payload, options)\n : this._executeWithoutHostedForm(payload, options);\n }\n\n finalize(_options?: PaymentRequestOptions): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(options?: PaymentInitializeOptions): Promise {\n if (\n !this._isHostedPaymentFormEnabled(options?.methodId, options?.gatewayId) ||\n !this._isHostedFieldAvailable(options)\n ) {\n this._shouldRenderHostedForm = false;\n\n return Promise.resolve(this._store.getState());\n }\n\n const formOptions = options && options.creditCard && options.creditCard.form;\n const { config } = this._store.getState();\n const { paymentSettings: { bigpayBaseUrl: host = '' } = {} } =\n config.getStoreConfig() || {};\n\n if (!formOptions) {\n throw new InvalidArgumentError();\n }\n\n const form = this._hostedFormFactory.create(host, formOptions);\n\n return form.attach().then(() => {\n this._shouldRenderHostedForm = true;\n this._hostedForm = form;\n\n return this._store.getState();\n });\n }\n\n deinitialize(_options?: PaymentRequestOptions): Promise {\n if (this._hostedForm) {\n this._hostedForm.detach();\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n protected _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment && payment.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n return this._store\n .dispatch(this._orderActionCreator.submitOrder(order, options))\n .then(() =>\n this._store.dispatch(\n this._paymentActionCreator.submitPayment({ ...payment, paymentData }),\n ),\n );\n }\n\n protected _executeWithHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!payment || !payment.methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n return form\n .validate()\n .then(() => this._store.dispatch(this._orderActionCreator.submitOrder(order, options)))\n .then(() => form.submit(payment))\n .then(() => this._store.dispatch(this._orderActionCreator.loadCurrentOrder()));\n }\n\n protected _isHostedPaymentFormEnabled(methodId?: string, gatewayId?: string): boolean {\n if (!methodId) {\n return false;\n }\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(methodId, gatewayId);\n\n return paymentMethod.config.isHostedFormEnabled === true;\n }\n\n private _isHostedFieldAvailable(options?: PaymentInitializeOptions): boolean {\n return !values(options && options.creditCard && options.creditCard.form.fields).every(\n isNil,\n );\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { CardinalThreeDSecureFlowV2 } from '../cardinal';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class BarclaysPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _threeDSecureFlow: CardinalThreeDSecureFlowV2,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(options.methodId);\n\n if (paymentMethod.config.is3dsEnabled) {\n await this._threeDSecureFlow.prepare(paymentMethod);\n }\n\n return this._store.getState();\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment: { methodId = '' } = {} } = payload;\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n\n if (getPaymentMethodOrThrow(methodId).config.is3dsEnabled) {\n return this._threeDSecureFlow.start(\n super.execute.bind(this),\n payload,\n options,\n this._hostedForm,\n );\n }\n\n return super.execute(payload, options);\n }\n}\n","export const ACKNOWLEDGE = 'ACKNOWLEDGE';\nexport const FINALIZE = 'FINALIZE';\nexport const INITIALIZE = 'INITIALIZE';\n","import { noop } from 'lodash';\n\nimport { CancellablePromise } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError, PaymentMethodCancelledError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { BlueSnapV2StyleProps } from './bluesnapv2';\nimport { BlueSnapV2PaymentInitializeOptions } from './bluesnapv2-payment-options';\n\nconst IFRAME_NAME = 'bluesnapv2_hosted_payment_page';\n\nexport default class BlueSnapV2PaymentStrategy implements PaymentStrategy {\n private _initializeOptions?: BlueSnapV2PaymentInitializeOptions;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n ) {}\n\n async execute(\n orderRequest: OrderRequestBody,\n options?: PaymentInitializeOptions,\n ): Promise {\n const { payment } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n if (!this._initializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { onLoad, style } = this._initializeOptions;\n const frame = this._createIframe(IFRAME_NAME, style);\n const promise = new CancellablePromise(new Promise(noop));\n\n onLoad(frame, () => promise.cancel(new PaymentMethodCancelledError()));\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(orderRequest, options));\n\n return this._store.dispatch(\n this._paymentActionCreator.initializeOffsitePayment({\n methodId: payment.methodId,\n gatewayId: payment.gatewayId,\n shouldSaveInstrument: false,\n target: frame.name,\n promise: promise.promise,\n }),\n );\n }\n\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this._store.getState();\n const order = state.order.getOrder();\n const status = state.payment.getPaymentStatus();\n\n if (\n order &&\n (status === paymentStatusTypes.ACKNOWLEDGE || status === paymentStatusTypes.FINALIZE)\n ) {\n return this._store.dispatch(\n this._orderActionCreator.finalizeOrder(order.orderId, options),\n );\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(options?: PaymentInitializeOptions): Promise {\n this._initializeOptions = options && options.bluesnapv2;\n\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n private _createIframe(name: string, style?: BlueSnapV2StyleProps): HTMLIFrameElement {\n const iframe = document.createElement('iframe');\n\n iframe.setAttribute(\n 'sandbox',\n 'allow-top-navigation allow-scripts allow-forms allow-same-origin',\n );\n\n iframe.name = name;\n\n if (style) {\n const { border, height, width } = style;\n\n iframe.style.border = border as string;\n iframe.style.height = height as string;\n iframe.style.width = width as string;\n }\n\n return iframe;\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { CardinalThreeDSecureFlowV2 } from '../cardinal';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class BNZPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _threeDSecureFlow: CardinalThreeDSecureFlowV2,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(options.methodId);\n\n if (paymentMethod.config.is3dsEnabled) {\n await this._threeDSecureFlow.prepare(paymentMethod);\n }\n\n return this._store.getState();\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n if (!payload.payment) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n const { methodId } = payload.payment;\n\n if (!methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n\n if (getPaymentMethodOrThrow(methodId).config.is3dsEnabled) {\n return this._threeDSecureFlow.start(\n super.execute.bind(this),\n payload,\n options,\n this._hostedForm,\n );\n }\n\n return super.execute(payload, options);\n }\n}\n","import getOverlayStyle from './overlay-style';\n\nexport interface OverlayOptions {\n background?: string;\n id?: string;\n transitionDuration?: number;\n hasCloseButton?: boolean;\n innerHtml?: HTMLElement | DocumentFragment;\n}\n\nexport interface OverlayShowOptions {\n onClick?(event: MouseEvent): void;\n onClickClose?(event: MouseEvent): void;\n}\n\nexport interface Elements {\n element: HTMLElement;\n mainElement: HTMLElement;\n closeElement?: HTMLElement;\n}\n\nexport default class Overlay {\n private _element: HTMLElement;\n private _mainElement: HTMLElement;\n private _closeElement?: HTMLElement;\n private _unregisterClick?: () => void;\n\n constructor(options?: OverlayOptions) {\n const { element, closeElement, mainElement } = this._createElements(options);\n\n this._element = element;\n this._closeElement = closeElement;\n this._mainElement = mainElement;\n }\n\n show(options?: OverlayShowOptions): void {\n if (this._mainElement.parentElement) {\n return;\n }\n\n this._registerClick(options);\n\n document.body.appendChild(this._mainElement);\n\n // Fade In\n setTimeout(() => (this._element.style.opacity = '1'));\n }\n\n remove(): void {\n if (!this._mainElement.parentElement) {\n return;\n }\n\n if (this._unregisterClick) {\n this._unregisterClick();\n }\n\n this._removeAfterTransition();\n\n setTimeout(() => (this._element.style.opacity = '0'));\n }\n\n private _createElements(options?: OverlayOptions): Elements {\n const element = document.createElement('div');\n const {\n background = 'rgba(0, 0, 0, 0.8)',\n id = 'checkoutOverlay',\n transitionDuration = 400,\n hasCloseButton = false,\n innerHtml = null,\n } = options || {};\n let mainElement = element;\n let closeElement: HTMLElement | undefined;\n let classLayout: string | undefined;\n let classClose: string | undefined;\n let classOverlayText: string | undefined;\n\n if (id) {\n element.id = id;\n }\n\n if (innerHtml) {\n const overlayText = document.createElement('div');\n\n classOverlayText = `${id}--overlayText`;\n overlayText.className = classOverlayText;\n overlayText.appendChild(innerHtml);\n\n element.appendChild(overlayText);\n }\n\n if (hasCloseButton) {\n classClose = `${id}--close`;\n closeElement = document.createElement('div');\n closeElement.className = classClose;\n\n classLayout = `${id}--layout`;\n mainElement = document.createElement('div');\n mainElement.className = classLayout;\n\n mainElement.appendChild(element);\n mainElement.appendChild(closeElement);\n }\n\n mainElement.appendChild(\n getOverlayStyle({\n id,\n background,\n transitionDuration,\n classLayout,\n classOverlayText,\n classClose,\n }),\n );\n\n return { element, closeElement, mainElement };\n }\n\n private _addEventListener(element?: HTMLElement, onClick?: (event: MouseEvent) => void): void {\n if (!element || !onClick) {\n return;\n }\n\n element.addEventListener('click', onClick);\n }\n\n private _removeEventListener(\n element?: HTMLElement,\n onClick?: (event: MouseEvent) => void,\n ): void {\n if (!element || !onClick) {\n return;\n }\n\n element.removeEventListener('click', onClick);\n }\n\n private _registerClick(options?: OverlayShowOptions): void {\n if (this._unregisterClick) {\n this._unregisterClick();\n }\n\n if (options) {\n const { onClick, onClickClose } = options;\n\n this._addEventListener(this._element, onClick);\n this._addEventListener(this._closeElement, onClickClose);\n\n this._unregisterClick = () => {\n this._removeEventListener(this._element, onClick);\n this._removeEventListener(this._closeElement, onClickClose);\n this._unregisterClick = undefined;\n };\n }\n }\n\n private _removeAfterTransition(): void {\n const handleTransition: (event: Event) => void = (event) => {\n // NOTE: `event` is not correctly typed in this version of TS\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n if ((event as TransitionEvent).propertyName !== 'opacity') {\n return;\n }\n\n if (this._mainElement.parentElement) {\n this._mainElement.remove();\n }\n\n this._element.removeEventListener('transitionend', handleTransition);\n };\n\n this._element.addEventListener('transitionend', handleTransition);\n }\n}\n","interface OverlayStyleOptions {\n background?: string;\n id?: string;\n transitionDuration?: number;\n classLayout?: string;\n classOverlayText?: string;\n classClose?: string;\n}\n\nexport default function getOverlayStyle(options: OverlayStyleOptions): HTMLElement {\n const { id, background, transitionDuration, classLayout, classOverlayText, classClose } =\n options;\n const styles = document.createElement('style');\n const addClassLayout = classLayout ? `, .${classLayout}` : '';\n\n styles.id = `${id}--styles`;\n styles.type = 'text/css';\n styles.innerText = `\n #${id}${addClassLayout} {\n display: block;\n height: 100%;\n width: 100%;\n left: 0;\n top: 0;\n position: fixed;\n z-index: 2147483647;\n }\n #${id} {\n transition: opacity ${transitionDuration}ms ease-out;\n background: ${background};\n opacity: 0;\n }\n `;\n\n if (classOverlayText) {\n styles.innerText += `\n #${id} {\n display: flex;\n align-items: center;\n justify-content: center;\n }\n #${id} .${classOverlayText} {\n color: white;\n max-width: 330px;\n font-size: 1.2em;\n text-align: center;\n }\n `;\n }\n\n if (classClose) {\n styles.innerText += `\n #${id} {\n opacity: 1;\n }\n .${classLayout} .${classClose} {\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 .${classLayout} .${classClose}::after, .${classLayout} .${classClose}::before {\n position: absolute;\n left: 8px;\n content: '';\n height: 16px;\n width: 2px;\n background-color: #fff;\n }\n .${classLayout} .${classClose}::after {\n transform: rotate(-45deg);\n }\n .${classLayout} .${classClose}::before {\n transform: rotate(45deg);\n }\n `;\n }\n\n return styles;\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport interface PaymentInvalidFormErrorDetails {\n [key: string]: Array<{ message: string; type: string }>;\n}\n\nexport default class PaymentInvalidFormError extends StandardError {\n constructor(public details: PaymentInvalidFormErrorDetails, message?: string) {\n super(message || 'Unable to proceed because the payment form contains invalid data.');\n\n this.name = 'PaymentInvalidFormError';\n this.type = 'payment_invalid_form';\n }\n}\n","import { BraintreeFormErrorsData, BraintreeVerifyPayload } from './braintree';\n\n/**\n * A set of options that are required to initialize the Braintree payment\n * method. You need to provide the options if you want to support 3D Secure\n * authentication flow.\n *\n * ```html\n * \n *
\n *
\n *
\n *
\n * ```\n *\n * ```js\n * service.initializePayment({\n * methodId: 'braintree',\n * braintree: {\n * form: {\n * fields: {\n * cardNumber: { containerId: 'card-number' },\n * cardName: { containerId: 'card-name' },\n * cardExpiry: { containerId: 'card-expiry' },\n * cardCode: { containerId: 'card-code' },\n * },\n * },\n * },\n * });\n * ```\n *\n * Additional options can be passed in to customize the fields and register\n * event callbacks.\n *\n * ```js\n * service.initializePayment({\n * methodId: 'braintree',\n * creditCard: {\n * form: {\n * fields: {\n * cardNumber: { containerId: 'card-number' },\n * cardName: { containerId: 'card-name' },\n * cardExpiry: { containerId: 'card-expiry' },\n * cardCode: { containerId: 'card-code' },\n * },\n * styles: {\n * default: {\n * color: '#000',\n * },\n * error: {\n * color: '#f00',\n * },\n * focus: {\n * color: '#0f0',\n * },\n * },\n * onBlur({ fieldType }) {\n * console.log(fieldType);\n * },\n * onFocus({ fieldType }) {\n * console.log(fieldType);\n * },\n * onEnter({ fieldType }) {\n * console.log(fieldType);\n * },\n * onCardTypeChange({ cardType }) {\n * console.log(cardType);\n * },\n * onValidate({ errors, isValid }) {\n * console.log(errors);\n * console.log(isValid);\n * },\n * },\n * },\n * });\n * ```\n */\nexport interface BraintreePaymentInitializeOptions {\n threeDSecure?: BraintreeThreeDSecureOptions;\n\n /**\n * @alpha\n * Please note that this option is currently in an early stage of\n * development. Therefore the API is unstable and not ready for public\n * consumption.\n */\n form?: BraintreeFormOptions;\n}\n\n/**\n * A set of options that are required to support 3D Secure authentication flow.\n *\n * If the customer uses a credit card that has 3D Secure enabled, they will be\n * asked to verify their identity when they pay. The verification is done\n * through a web page via an iframe provided by the card issuer.\n */\nexport interface BraintreeThreeDSecureOptions {\n /**\n * A callback that gets called when the iframe is ready to be added to the\n * current page. It is responsible for determining where the iframe should\n * be inserted in the DOM.\n *\n * @param error - Any error raised during the verification process;\n * undefined if there is none.\n * @param iframe - The iframe element containing the verification web page\n * provided by the card issuer.\n * @param cancel - A function, when called, will cancel the verification\n * process and remove the iframe.\n */\n addFrame(\n error: Error | undefined,\n iframe: HTMLIFrameElement,\n cancel: () => Promise | undefined,\n ): void;\n\n /**\n * A callback that gets called when the iframe is about to be removed from\n * the current page.\n */\n removeFrame(): void;\n}\n\nexport interface BraintreeFormOptions {\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap;\n styles?: BraintreeFormFieldStylesMap;\n onBlur?(data: BraintreeFormFieldBlurEventData): void;\n onCardTypeChange?(data: BraintreeFormFieldCardTypeChangeEventData): void;\n onFocus?(data: BraintreeFormFieldFocusEventData): void;\n onValidate?(data: BraintreeFormFieldValidateEventData): void;\n onEnter?(data: BraintreeFormFieldEnterEventData): void;\n}\n\nexport enum BraintreeFormFieldType {\n CardCode = 'cardCode',\n CardCodeVerification = 'cardCodeVerification',\n CardExpiry = 'cardExpiry',\n CardName = 'cardName',\n CardNumber = 'cardNumber',\n CardNumberVerification = 'cardNumberVerification',\n}\n\nexport interface BraintreeFormFieldsMap {\n [BraintreeFormFieldType.CardCode]?: BraintreeFormFieldOptions;\n [BraintreeFormFieldType.CardExpiry]: BraintreeFormFieldOptions;\n [BraintreeFormFieldType.CardName]: BraintreeFormFieldOptions;\n [BraintreeFormFieldType.CardNumber]: BraintreeFormFieldOptions;\n}\n\nexport interface BraintreeStoredCardFieldsMap {\n [BraintreeFormFieldType.CardCodeVerification]?: BraintreeStoredCardFieldOptions;\n [BraintreeFormFieldType.CardNumberVerification]?: BraintreeStoredCardFieldOptions;\n}\n\nexport interface BraintreeFormFieldOptions {\n accessibilityLabel?: string;\n containerId: string;\n placeholder?: string;\n}\n\nexport interface BraintreeStoredCardFieldOptions extends BraintreeFormFieldOptions {\n instrumentId: string;\n}\n\nexport interface BraintreeFormFieldStylesMap {\n default?: BraintreeFormFieldStyles;\n error?: BraintreeFormFieldStyles;\n focus?: BraintreeFormFieldStyles;\n}\n\nexport type BraintreeFormFieldStyles = Partial<\n Pick\n>;\n\nexport interface BraintreeFormFieldKeyboardEventData {\n fieldType: string;\n errors?: BraintreeFormErrorsData;\n}\n\nexport type BraintreeFormFieldBlurEventData = BraintreeFormFieldKeyboardEventData;\nexport type BraintreeFormFieldEnterEventData = BraintreeFormFieldKeyboardEventData;\nexport type BraintreeFormFieldFocusEventData = BraintreeFormFieldKeyboardEventData;\n\nexport interface BraintreeFormFieldCardTypeChangeEventData {\n cardType?: string;\n}\n\nexport interface BraintreeFormFieldValidateEventData {\n errors: {\n [BraintreeFormFieldType.CardCode]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardExpiry]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardName]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardNumber]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardCodeVerification]?: BraintreeFormFieldValidateErrorData[];\n [BraintreeFormFieldType.CardNumberVerification]?: BraintreeFormFieldValidateErrorData[];\n };\n isValid: boolean;\n}\n\nexport interface BraintreeFormFieldValidateErrorData {\n fieldType: string;\n message: string;\n type: string;\n}\n","import { InvalidArgumentError } from '../../../common/error/errors';\n\nimport {\n BraintreeFormFieldOptions,\n BraintreeFormFieldStyles,\n BraintreeFormFieldStylesMap,\n} from './braintree-payment-options';\n\nexport default class BraintreeRegularField {\n private _input: HTMLInputElement;\n\n constructor(\n private _options: BraintreeFormFieldOptions,\n private _styles?: BraintreeFormFieldStylesMap,\n ) {\n this._input = document.createElement('input');\n this._input.style.backgroundColor = 'transparent';\n this._input.style.border = '0';\n this._input.style.display = 'block';\n this._input.style.height = '100%';\n this._input.style.margin = '0';\n this._input.style.outline = 'none';\n this._input.style.padding = '0';\n this._input.style.width = '100%';\n this._input.placeholder = this._options.placeholder || '';\n\n this._input.setAttribute('aria-label', this._options.accessibilityLabel || '');\n\n this._input.addEventListener('blur', this._handleBlur);\n this._input.addEventListener('focus', this._handleFocus);\n\n this._applyStyles(this._styles?.default);\n }\n\n getValue(): string {\n return this._input.value;\n }\n\n attach(): void {\n const container = document.getElementById(this._options.containerId);\n\n if (!container) {\n throw new InvalidArgumentError();\n }\n\n container.appendChild(this._input);\n }\n\n detach(): void {\n this._input.parentNode?.removeChild(this._input);\n }\n\n on(event: string, callback: () => void): void {\n this._input.addEventListener(event, callback);\n }\n\n off(event: string, callback: () => void): void {\n this._input.removeEventListener(event, callback);\n }\n\n private _applyStyles(styles?: BraintreeFormFieldStyles): void {\n if (!styles) {\n return;\n }\n\n const styleKeys = Object.keys(styles) as Array;\n\n styleKeys.forEach((key) => {\n this._input.style[key] = styles[key] || '';\n });\n }\n\n private _handleBlur: (event: Event) => void = () => {\n this._applyStyles(this._styles?.default);\n };\n\n private _handleFocus: (event: Event) => void = () => {\n this._applyStyles(this._styles?.focus);\n };\n}\n","import { BraintreeFormFieldsMap, BraintreeStoredCardFieldsMap } from './braintree-payment-options';\n\nexport function isBraintreeFormFieldsMap(\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap,\n): fields is BraintreeFormFieldsMap {\n return !!(fields as BraintreeFormFieldsMap).cardNumber;\n}\n\nexport function isBraintreeStoredCardFieldsMap(\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap,\n): fields is BraintreeStoredCardFieldsMap {\n return !!(\n (fields as BraintreeStoredCardFieldsMap).cardCodeVerification ||\n (fields as BraintreeStoredCardFieldsMap).cardNumberVerification\n );\n}\n","import { Dictionary, isEmpty, isNil, omitBy } from 'lodash';\n\nimport { Address } from '../../../address';\nimport { NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { PaymentInvalidFormError, PaymentInvalidFormErrorDetails } from '../../errors';\nimport { NonceInstrument } from '../../payment';\n\nimport {\n BraintreeBillingAddressRequestData,\n BraintreeFormErrorDataKeys,\n BraintreeFormErrorsData,\n BraintreeHostedFields,\n BraintreeHostedFieldsCreatorConfig,\n BraintreeHostedFieldsState,\n BraintreeHostedFormError,\n} from './braintree';\nimport {\n BraintreeFormFieldsMap,\n BraintreeFormFieldStyles,\n BraintreeFormFieldStylesMap,\n BraintreeFormFieldType,\n BraintreeFormFieldValidateErrorData,\n BraintreeFormFieldValidateEventData,\n BraintreeFormOptions,\n BraintreeStoredCardFieldsMap,\n} from './braintree-payment-options';\nimport BraintreeRegularField from './braintree-regular-field';\nimport BraintreeSDKCreator from './braintree-sdk-creator';\nimport { isBraintreeFormFieldsMap } from './is-braintree-form-fields-map';\n\nenum BraintreeHostedFormType {\n CreditCard,\n StoredCardVerification,\n}\n\nexport default class BraintreeHostedForm {\n private _cardFields?: BraintreeHostedFields;\n private _cardNameField?: BraintreeRegularField;\n private _formOptions?: BraintreeFormOptions;\n private _type?: BraintreeHostedFormType;\n private _isInitializedHostedForm = false;\n\n constructor(private _braintreeSDKCreator: BraintreeSDKCreator) {}\n\n async initialize(options: BraintreeFormOptions): Promise {\n this._formOptions = options;\n\n this._type = isBraintreeFormFieldsMap(options.fields)\n ? BraintreeHostedFormType.CreditCard\n : BraintreeHostedFormType.StoredCardVerification;\n\n const fields = this._mapFieldOptions(options.fields);\n\n if (isEmpty(fields)) {\n this._isInitializedHostedForm = false;\n\n return;\n }\n\n this._cardFields = await this._braintreeSDKCreator.createHostedFields({\n fields,\n styles: options.styles && this._mapStyleOptions(options.styles),\n });\n\n this._cardFields.on('blur', this._handleBlur);\n this._cardFields.on('focus', this._handleFocus);\n this._cardFields.on('cardTypeChange', this._handleCardTypeChange);\n this._cardFields.on('validityChange', this._handleValidityChange);\n this._cardFields.on('inputSubmitRequest', this._handleInputSubmitRequest);\n\n if (isBraintreeFormFieldsMap(options.fields)) {\n this._cardNameField = new BraintreeRegularField(\n options.fields.cardName,\n options.styles,\n );\n this._cardNameField.on('blur', this._handleNameBlur);\n this._cardNameField.on('focus', this._handleNameFocus);\n this._cardNameField.attach();\n }\n\n this._isInitializedHostedForm = true;\n }\n\n isInitialized(): boolean {\n return !!this._isInitializedHostedForm;\n }\n\n async deinitialize(): Promise {\n this._isInitializedHostedForm = false;\n\n await this._cardFields?.teardown();\n this._cardNameField?.detach();\n }\n\n async tokenize(billingAddress: Address): Promise {\n if (!this._cardFields) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n try {\n const { nonce } = await this._cardFields.tokenize(\n omitBy(\n {\n billingAddress: billingAddress && this._mapBillingAddress(billingAddress),\n cardholderName: this._cardNameField?.getValue(),\n },\n isNil,\n ),\n );\n\n this._formOptions?.onValidate?.({\n isValid: true,\n errors: {},\n });\n\n return { nonce };\n } catch (error) {\n const errors = this._mapTokenizeError(error);\n\n if (errors) {\n this._formOptions?.onValidate?.({\n isValid: false,\n errors,\n });\n\n throw new PaymentInvalidFormError(errors as PaymentInvalidFormErrorDetails);\n }\n\n throw error;\n }\n }\n\n async tokenizeForStoredCardVerification(): Promise {\n if (!this._cardFields) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n try {\n const { nonce } = await this._cardFields.tokenize(\n omitBy(\n {\n cardholderName: this._cardNameField?.getValue(),\n },\n isNil,\n ),\n );\n\n this._formOptions?.onValidate?.({\n isValid: true,\n errors: {},\n });\n\n return { nonce };\n } catch (error) {\n const errors = this._mapTokenizeError(error, true);\n\n if (errors) {\n this._formOptions?.onValidate?.({\n isValid: false,\n errors,\n });\n\n throw new PaymentInvalidFormError(errors as PaymentInvalidFormErrorDetails);\n }\n\n throw error;\n }\n }\n\n private _mapBillingAddress(billingAddress: Address): BraintreeBillingAddressRequestData {\n return {\n countryName: billingAddress.country,\n postalCode: billingAddress.postalCode,\n streetAddress: billingAddress.address2\n ? `${billingAddress.address1} ${billingAddress.address2}`\n : billingAddress.address1,\n };\n }\n\n private _mapFieldOptions(\n fields: BraintreeFormFieldsMap | BraintreeStoredCardFieldsMap,\n ): BraintreeHostedFieldsCreatorConfig['fields'] {\n if (isBraintreeFormFieldsMap(fields)) {\n return omitBy(\n {\n number: {\n container: `#${fields.cardNumber.containerId}`,\n placeholder: fields.cardNumber.placeholder,\n internalLabel: fields.cardNumber.accessibilityLabel,\n },\n expirationDate: {\n container: `#${fields.cardExpiry.containerId}`,\n placeholder: fields.cardExpiry.placeholder,\n internalLabel: fields.cardExpiry.accessibilityLabel,\n },\n cvv: fields.cardCode && {\n container: `#${fields.cardCode.containerId}`,\n placeholder: fields.cardCode.placeholder,\n internalLabel: fields.cardCode.accessibilityLabel,\n },\n },\n isNil,\n );\n }\n\n return omitBy(\n {\n number: fields.cardNumberVerification && {\n container: `#${fields.cardNumberVerification.containerId}`,\n placeholder: fields.cardNumberVerification.placeholder,\n },\n cvv: fields.cardCodeVerification && {\n container: `#${fields.cardCodeVerification.containerId}`,\n placeholder: fields.cardCodeVerification.placeholder,\n },\n },\n isNil,\n );\n }\n\n private _mapStyleOptions(\n options: BraintreeFormFieldStylesMap,\n ): BraintreeHostedFieldsCreatorConfig['styles'] {\n const mapStyles = (styles: BraintreeFormFieldStyles = {}) =>\n omitBy(\n {\n color: styles.color,\n 'font-family': styles.fontFamily,\n 'font-size': styles.fontSize,\n 'font-weight': styles.fontWeight,\n },\n isNil,\n ) as Dictionary;\n\n return {\n input: mapStyles(options.default),\n '.invalid': mapStyles(options.error),\n ':focus': mapStyles(options.focus),\n };\n }\n\n private _mapFieldType(type: string): BraintreeFormFieldType {\n switch (type) {\n case 'number':\n return this._type === BraintreeHostedFormType.StoredCardVerification\n ? BraintreeFormFieldType.CardNumberVerification\n : BraintreeFormFieldType.CardNumber;\n\n case 'expirationDate':\n return BraintreeFormFieldType.CardExpiry;\n\n case 'cvv':\n return this._type === BraintreeHostedFormType.StoredCardVerification\n ? BraintreeFormFieldType.CardCodeVerification\n : BraintreeFormFieldType.CardCode;\n\n default:\n throw new Error('Unexpected field type');\n }\n }\n\n private _mapErrors(fields: BraintreeHostedFieldsState['fields']): BraintreeFormErrorsData {\n const errors: BraintreeFormErrorsData = {};\n\n if (fields) {\n for (const [key, value] of Object.entries(fields)) {\n if (value && this._isValidParam(key)) {\n const { isValid, isEmpty, isPotentiallyValid } = value;\n\n errors[key] = {\n isValid,\n isEmpty,\n isPotentiallyValid,\n };\n }\n }\n }\n\n return errors;\n }\n\n private _mapValidationErrors(\n fields: BraintreeHostedFieldsState['fields'],\n ): BraintreeFormFieldValidateEventData['errors'] {\n return (Object.keys(fields) as Array).reduce(\n (result, fieldKey) => ({\n ...result,\n [this._mapFieldType(fieldKey)]: fields[fieldKey]?.isValid\n ? undefined\n : [this._createInvalidError(this._mapFieldType(fieldKey))],\n }),\n {},\n );\n }\n\n private _mapTokenizeError(\n error: BraintreeHostedFormError,\n isStoredCard = false,\n ): BraintreeFormFieldValidateEventData['errors'] | undefined {\n if (error.code === 'HOSTED_FIELDS_FIELDS_EMPTY') {\n const cvvValidation = {\n [this._mapFieldType('cvv')]: [this._createRequiredError(this._mapFieldType('cvv'))],\n };\n\n const expirationDateValidation = {\n [this._mapFieldType('expirationDate')]: [\n this._createRequiredError(this._mapFieldType('expirationDate')),\n ],\n };\n\n const cardNumberValidation = {\n [this._mapFieldType('number')]: [\n this._createRequiredError(this._mapFieldType('number')),\n ],\n };\n\n return isStoredCard\n ? cvvValidation\n : {\n ...cvvValidation,\n ...expirationDateValidation,\n ...cardNumberValidation,\n };\n }\n\n return error.details?.invalidFieldKeys?.reduce(\n (result, fieldKey) => ({\n ...result,\n [this._mapFieldType(fieldKey)]: [\n this._createInvalidError(this._mapFieldType(fieldKey)),\n ],\n }),\n {},\n );\n }\n\n private _createRequiredError(\n fieldType: BraintreeFormFieldType,\n ): BraintreeFormFieldValidateErrorData {\n switch (fieldType) {\n case BraintreeFormFieldType.CardCodeVerification:\n case BraintreeFormFieldType.CardCode:\n return {\n fieldType,\n message: 'CVV is required',\n type: 'required',\n };\n\n case BraintreeFormFieldType.CardNumberVerification:\n case BraintreeFormFieldType.CardNumber:\n return {\n fieldType,\n message: 'Credit card number is required',\n type: 'required',\n };\n\n case BraintreeFormFieldType.CardExpiry:\n return {\n fieldType,\n message: 'Expiration date is required',\n type: 'required',\n };\n\n case BraintreeFormFieldType.CardName:\n return {\n fieldType,\n message: 'Full name is required',\n type: 'required',\n };\n\n default:\n return {\n fieldType,\n message: 'Field is required',\n type: 'required',\n };\n }\n }\n\n private _createInvalidError(\n fieldType: BraintreeFormFieldType,\n ): BraintreeFormFieldValidateErrorData {\n switch (fieldType) {\n case BraintreeFormFieldType.CardCodeVerification:\n return {\n fieldType,\n message: 'Invalid card code',\n type: 'invalid_card_code',\n };\n\n case BraintreeFormFieldType.CardNumberVerification:\n return {\n fieldType,\n message: 'Invalid card number',\n type: 'invalid_card_number',\n };\n\n case BraintreeFormFieldType.CardCode:\n return {\n fieldType,\n message: 'Invalid card code',\n type: 'invalid_card_code',\n };\n\n case BraintreeFormFieldType.CardExpiry:\n return {\n fieldType,\n message: 'Invalid card expiry',\n type: 'invalid_card_expiry',\n };\n\n case BraintreeFormFieldType.CardNumber:\n return {\n fieldType,\n message: 'Invalid card number',\n type: 'invalid_card_number',\n };\n\n default:\n return {\n fieldType,\n message: 'Invalid field',\n type: 'invalid',\n };\n }\n }\n\n private _handleBlur: (event: BraintreeHostedFieldsState) => void = (event) => {\n this._formOptions?.onBlur?.({\n fieldType: this._mapFieldType(event.emittedBy),\n errors: this._mapErrors(event.fields),\n });\n };\n\n private _handleNameBlur: () => void = () => {\n this._formOptions?.onBlur?.({\n fieldType: BraintreeFormFieldType.CardName,\n });\n };\n\n private _handleFocus: (event: BraintreeHostedFieldsState) => void = (event) => {\n this._formOptions?.onFocus?.({\n fieldType: this._mapFieldType(event.emittedBy),\n });\n };\n\n private _handleNameFocus: () => void = () => {\n this._formOptions?.onFocus?.({\n fieldType: BraintreeFormFieldType.CardName,\n });\n };\n\n private _handleCardTypeChange: (event: BraintreeHostedFieldsState) => void = (event) => {\n this._formOptions?.onCardTypeChange?.({\n cardType:\n event.cards.length === 1\n ? event.cards[0].type.replace(/^master\\-card$/, 'mastercard',) /* eslint-disable-line */\n : undefined,\n });\n };\n\n private _handleInputSubmitRequest: (event: BraintreeHostedFieldsState) => void = (event) => {\n this._formOptions?.onEnter?.({\n fieldType: this._mapFieldType(event.emittedBy),\n });\n };\n\n private _handleValidityChange: (event: BraintreeHostedFieldsState) => void = (event) => {\n this._formOptions?.onValidate?.({\n isValid: (\n Object.keys(event.fields) as Array\n ).every((key) => event.fields[key]?.isValid),\n errors: this._mapValidationErrors(event.fields),\n });\n };\n\n private _isValidParam(\n formErrorDataKey: string,\n ): formErrorDataKey is BraintreeFormErrorDataKeys {\n switch (formErrorDataKey) {\n case 'number':\n case 'cvv':\n case 'expirationDate':\n case 'postalCode':\n case 'cardholderName':\n case 'cardType':\n return true;\n\n default:\n return false;\n }\n }\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"@braintree/browser-detection\");","import { supportsPopups } from '@braintree/browser-detection';\nimport { isEmpty } from 'lodash';\n\nimport { CancellablePromise } from '@bigcommerce/checkout-sdk/payment-integration-api';\nimport { Overlay } from '@bigcommerce/checkout-sdk/ui';\n\nimport { Address } from '../../../address';\nimport { NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\nimport { OrderPaymentRequestBody } from '../../../order';\nimport {\n PaymentArgumentInvalidError,\n PaymentInvalidFormError,\n PaymentInvalidFormErrorDetails,\n PaymentMethodCancelledError,\n} from '../../errors';\nimport { CreditCardInstrument, NonceInstrument } from '../../payment';\n\nimport {\n BraintreePaypal,\n BraintreeRequestData,\n BraintreeShippingAddressOverride,\n BraintreeThreeDSecure,\n BraintreeTokenizePayload,\n BraintreeVenmoCheckout,\n BraintreeVerifyPayload,\n} from './braintree';\nimport BraintreeHostedForm from './braintree-hosted-form';\nimport {\n BraintreeFormOptions,\n BraintreePaymentInitializeOptions,\n BraintreeThreeDSecureOptions,\n} from './braintree-payment-options';\nimport BraintreeSDKCreator from './braintree-sdk-creator';\nimport isCreditCardInstrumentLike from './is-credit-card-instrument-like';\n\nexport interface PaypalConfig {\n amount: number;\n currency: string;\n locale: string;\n offerCredit?: boolean;\n shippingAddressEditable?: boolean;\n shippingAddressOverride?: BraintreeShippingAddressOverride;\n shouldSaveInstrument?: boolean;\n}\n\nexport default class BraintreePaymentProcessor {\n private _threeDSecureOptions?: BraintreeThreeDSecureOptions;\n\n constructor(\n private _braintreeSDKCreator: BraintreeSDKCreator,\n private _braintreeHostedForm: BraintreeHostedForm,\n private _overlay: Overlay,\n ) {}\n\n initialize(clientToken: string, options?: BraintreePaymentInitializeOptions): void {\n this._braintreeSDKCreator.initialize(clientToken);\n this._threeDSecureOptions = options?.threeDSecure;\n }\n\n deinitialize(): Promise {\n return this._braintreeSDKCreator.teardown();\n }\n\n preloadPaypal(): Promise {\n return this._braintreeSDKCreator.getPaypal();\n }\n\n async tokenizeCard(\n payment: OrderPaymentRequestBody,\n billingAddress: Address,\n ): Promise {\n const { paymentData } = payment;\n\n if (!isCreditCardInstrumentLike(paymentData)) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const errors = this._getErrorsRequiredFields(paymentData);\n\n if (!isEmpty(errors)) {\n throw new PaymentInvalidFormError(errors);\n }\n\n const requestData = this._mapToCreditCard(paymentData, billingAddress);\n const client = await this._braintreeSDKCreator.getClient();\n const { creditCards } = await client.request(requestData);\n\n return { nonce: creditCards[0].nonce };\n }\n\n async verifyCard(\n payment: OrderPaymentRequestBody,\n billingAddress: Address,\n amount: number,\n ): Promise {\n const { nonce } = await this.tokenizeCard(payment, billingAddress);\n\n return this.challenge3DSVerification(nonce, amount);\n }\n\n paypal({ shouldSaveInstrument, ...config }: PaypalConfig): Promise {\n const newWindowFlow = supportsPopups();\n\n return this._braintreeSDKCreator\n .getPaypal()\n .then((paypal) => {\n if (newWindowFlow) {\n this._overlay.show({\n onClick: () => paypal.focusWindow(),\n });\n }\n\n return paypal.tokenize({\n enableShippingAddress: true,\n flow: shouldSaveInstrument ? 'vault' : 'checkout',\n useraction: 'commit',\n ...config,\n });\n })\n .then((response) => {\n this._overlay.remove();\n\n return response;\n })\n .catch((error) => {\n this._overlay.remove();\n\n throw error;\n });\n }\n\n getSessionId(): Promise {\n return this._braintreeSDKCreator.getDataCollector().then(({ deviceData }) => deviceData);\n }\n\n /**\n * @deprecated Use getSessionId() and combine them in the consumer.\n */\n appendSessionId(processedPayment: Promise): Promise {\n return processedPayment\n .then((paymentData) =>\n Promise.all([paymentData, this._braintreeSDKCreator.getDataCollector()]),\n )\n .then(([paymentData, { deviceData }]) => ({\n ...paymentData,\n deviceSessionId: deviceData,\n }));\n }\n\n async initializeHostedForm(options: BraintreeFormOptions): Promise {\n return this._braintreeHostedForm.initialize(options);\n }\n\n isInitializedHostedForm(): boolean {\n return this._braintreeHostedForm.isInitialized();\n }\n\n async deinitializeHostedForm(): Promise {\n await this._braintreeHostedForm.deinitialize();\n }\n\n tokenizeHostedForm(billingAddress: Address): Promise {\n return this._braintreeHostedForm.tokenize(billingAddress);\n }\n\n tokenizeHostedFormForStoredCardVerification(): Promise {\n return this._braintreeHostedForm.tokenizeForStoredCardVerification();\n }\n\n async verifyCardWithHostedForm(\n billingAddress: Address,\n amount: number,\n ): Promise {\n const { nonce } = await this._braintreeHostedForm.tokenize(billingAddress);\n\n return this.challenge3DSVerification(nonce, amount);\n }\n\n async challenge3DSVerification(nonce: string, amount: number): Promise {\n const threeDSecure = await this._braintreeSDKCreator.get3DS();\n\n return this._present3DSChallenge(threeDSecure, amount, nonce);\n }\n\n async getVenmoCheckout(): Promise {\n return new Promise((resolve, reject) => {\n this._braintreeSDKCreator.getVenmoCheckout(resolve, reject);\n });\n }\n\n private _getErrorsRequiredFields(\n paymentData: CreditCardInstrument,\n ): PaymentInvalidFormErrorDetails {\n const { ccNumber, ccExpiry } = paymentData;\n const errors: PaymentInvalidFormErrorDetails = {};\n\n if (!ccNumber) {\n errors.ccNumber = [\n {\n message: 'Credit card number is required',\n type: 'required',\n },\n ];\n }\n\n if (!ccExpiry) {\n errors.ccExpiry = [\n {\n message: 'Expiration date is required',\n type: 'required',\n },\n ];\n }\n\n return errors;\n }\n\n private _present3DSChallenge(\n threeDSecure: BraintreeThreeDSecure,\n amount: number,\n nonce: string,\n ): Promise {\n if (!this._threeDSecureOptions || !nonce) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { addFrame, removeFrame } = this._threeDSecureOptions;\n const cancelVerifyCard = async () => {\n const response = await threeDSecure.cancelVerifyCard();\n\n verification.cancel(new PaymentMethodCancelledError());\n\n return response;\n };\n\n const roundedAmount = amount.toFixed(2);\n\n const verification = new CancellablePromise(\n threeDSecure.verifyCard({\n addFrame: (error, iframe) => {\n addFrame(error, iframe, cancelVerifyCard);\n },\n amount: Number(roundedAmount),\n challengeRequested: true,\n nonce,\n removeFrame,\n onLookupComplete: (_data, next) => {\n next();\n },\n }),\n );\n\n return verification.promise;\n }\n\n private _mapToCreditCard(\n creditCard: CreditCardInstrument,\n billingAddress?: Address,\n ): BraintreeRequestData {\n return {\n data: {\n creditCard: {\n cardholderName: creditCard.ccName,\n number: creditCard.ccNumber,\n cvv: creditCard.ccCvv,\n expirationDate: `${creditCard.ccExpiry.month}/${creditCard.ccExpiry.year}`,\n options: {\n validate: false,\n },\n billingAddress: billingAddress && {\n countryCodeAlpha2: billingAddress.countryCode,\n locality: billingAddress.city,\n countryName: billingAddress.country,\n postalCode: billingAddress.postalCode,\n streetAddress: billingAddress.address2\n ? `${billingAddress.address1} ${billingAddress.address2}`\n : billingAddress.address1,\n },\n },\n },\n endpoint: 'payment_methods/credit_cards',\n method: 'post',\n };\n }\n}\n","import { CreditCardInstrument } from '../../payment';\n\nexport default function isCreditCardInstrumentLike(\n instrument: any,\n): instrument is CreditCardInstrument {\n return (\n instrument &&\n typeof instrument.ccExpiry === 'object' &&\n typeof instrument.ccNumber === 'string' &&\n typeof instrument.ccName === 'string'\n );\n}\n","import { HostedInstrument } from './payment';\n\nexport default function isHostedInstrumentLike(\n instrument: unknown,\n): instrument is HostedInstrument {\n return (\n typeof instrument === 'object' &&\n instrument !== null &&\n (typeof (instrument as HostedInstrument).shouldSaveInstrument === 'undefined' ||\n typeof (instrument as HostedInstrument).shouldSaveInstrument === 'boolean') &&\n (typeof (instrument as HostedInstrument).shouldSetAsDefaultInstrument === 'undefined' ||\n typeof (instrument as HostedInstrument).shouldSetAsDefaultInstrument === 'boolean')\n );\n}\n","import { some } from 'lodash';\n\nimport { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Address } from '../../../address';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { MissingDataError, MissingDataErrorType, RequestError } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport { isHostedInstrumentLike, PaymentMethod } from '../../index';\nimport isVaultedInstrument from '../../is-vaulted-instrument';\nimport {\n CreditCardInstrument,\n NonceInstrument,\n PaymentInstrument,\n PaymentInstrumentMeta,\n} from '../../payment';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport BraintreePaymentProcessor from './braintree-payment-processor';\n\nexport default class BraintreeCreditCardPaymentStrategy implements PaymentStrategy {\n private _is3dsEnabled?: boolean;\n private _isHostedFormInitialized?: boolean;\n private _deviceSessionId?: string;\n private _paymentMethod?: PaymentMethod;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _braintreePaymentProcessor: BraintreePaymentProcessor,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(options.methodId),\n );\n\n this._paymentMethod = state.paymentMethods.getPaymentMethod(options.methodId);\n\n if (!this._paymentMethod?.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n try {\n this._braintreePaymentProcessor.initialize(\n this._paymentMethod.clientToken,\n options.braintree,\n );\n\n if (\n this._isHostedPaymentFormEnabled(options.methodId, options.gatewayId) &&\n options.braintree?.form\n ) {\n await this._braintreePaymentProcessor.initializeHostedForm(options.braintree.form);\n this._isHostedFormInitialized =\n this._braintreePaymentProcessor.isInitializedHostedForm();\n }\n\n this._is3dsEnabled = this._paymentMethod.config.is3dsEnabled;\n this._deviceSessionId = await this._braintreePaymentProcessor.getSessionId();\n } catch (error) {\n this._handleError(error);\n }\n\n return this._store.getState();\n }\n\n async execute(\n orderRequest: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const state = await this._store.dispatch(\n this._orderActionCreator.submitOrder(order, options),\n );\n\n const {\n billingAddress: { getBillingAddressOrThrow },\n order: { getOrderOrThrow },\n payment: { isPaymentDataRequired },\n } = state;\n\n if (!isPaymentDataRequired(order.useStoreCredit)) {\n return state;\n }\n\n const billingAddress = getBillingAddressOrThrow();\n const orderAmount = getOrderOrThrow().orderAmount;\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n ...payment,\n paymentData: this._isHostedFormInitialized\n ? await this._prepareHostedPaymentData(payment, billingAddress, orderAmount)\n : await this._preparePaymentData(payment, billingAddress, orderAmount),\n }),\n );\n } catch (error) {\n return this._processAdditionalAction(error, payment, orderAmount);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n this._isHostedFormInitialized = false;\n\n await Promise.all([\n this._braintreePaymentProcessor.deinitialize(),\n this._braintreePaymentProcessor.deinitializeHostedForm(),\n ]);\n\n return this._store.getState();\n }\n\n private _handleError(error: Error): never {\n if (error.name === 'BraintreeError') {\n throw new PaymentMethodFailedError(error.message);\n }\n\n throw error;\n }\n\n private async _preparePaymentData(\n payment: OrderPaymentRequestBody,\n billingAddress: Address,\n orderAmount: number,\n ): Promise {\n const { paymentData } = payment;\n const commonPaymentData = { deviceSessionId: this._deviceSessionId };\n\n if (this._isSubmittingWithStoredCard(payment) || this._isStoringNewCard(payment)) {\n return {\n ...commonPaymentData,\n ...paymentData,\n };\n }\n\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n\n const { nonce } = this._shouldPerform3DSVerification(payment)\n ? await this._braintreePaymentProcessor.verifyCard(payment, billingAddress, orderAmount)\n : await this._braintreePaymentProcessor.tokenizeCard(payment, billingAddress);\n\n return {\n ...commonPaymentData,\n nonce,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n };\n }\n\n private async _prepareHostedPaymentData(\n payment: OrderPaymentRequestBody,\n billingAddress: Address,\n orderAmount: number,\n ): Promise {\n const { paymentData } = payment;\n const commonPaymentData = { deviceSessionId: this._deviceSessionId };\n\n if (this._isSubmittingWithStoredCard(payment)) {\n const { nonce } =\n await this._braintreePaymentProcessor.tokenizeHostedFormForStoredCardVerification();\n\n return {\n ...commonPaymentData,\n ...paymentData,\n nonce,\n };\n }\n\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n\n const { nonce } = this._shouldPerform3DSVerification(payment)\n ? await this._braintreePaymentProcessor.verifyCardWithHostedForm(\n billingAddress,\n orderAmount,\n )\n : await this._braintreePaymentProcessor.tokenizeHostedForm(billingAddress);\n\n return {\n ...commonPaymentData,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n nonce,\n };\n }\n\n private async _processAdditionalAction(\n error: Error,\n payment: OrderPaymentRequestBody,\n orderAmount: number,\n ): Promise {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return this._handleError(error);\n }\n\n try {\n const { payer_auth_request: storedCreditCardNonce } = error.body.three_ds_result || {};\n const { nonce } = await this._braintreePaymentProcessor.challenge3DSVerification(\n storedCreditCardNonce,\n orderAmount,\n );\n\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n ...payment,\n paymentData: {\n deviceSessionId: this._deviceSessionId,\n nonce,\n },\n }),\n );\n } catch (error) {\n return this._handleError(error);\n }\n }\n\n private _isHostedPaymentFormEnabled(methodId?: string, gatewayId?: string): boolean {\n if (!methodId) {\n return false;\n }\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(methodId, gatewayId);\n\n return paymentMethod.config.isHostedFormEnabled === true;\n }\n\n private _isSubmittingWithStoredCard(payment: OrderPaymentRequestBody): boolean {\n return !!(payment.paymentData && isVaultedInstrument(payment.paymentData));\n }\n\n private _isStoringNewCard(payment: OrderPaymentRequestBody): boolean {\n return !!(\n payment.paymentData &&\n (payment.paymentData as CreditCardInstrument | NonceInstrument).shouldSaveInstrument\n );\n }\n\n private _shouldPerform3DSVerification(payment: OrderPaymentRequestBody): boolean {\n return !!(this._is3dsEnabled && !this._isSubmittingWithStoredCard(payment));\n }\n}\n","import { BraintreeError } from './braintree';\n\nexport default function isBraintreeError(error: BraintreeError | Error): error is BraintreeError {\n return error.name === 'BraintreeError';\n}\n","import { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError, PaymentMethodCancelledError } from '../../errors';\nimport { isHostedInstrumentLike } from '../../index';\nimport isVaultedInstrument, { isHostedVaultedInstrument } from '../../is-vaulted-instrument';\nimport Payment, { FormattedPayload, PaypalInstrument } from '../../payment';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { BraintreePaymentInitializeOptions } from '../../strategies/braintree';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { BraintreeError } from './braintree';\nimport BraintreePaymentProcessor from './braintree-payment-processor';\nimport isBraintreeError from './is-braintree-error';\nimport mapToBraintreeShippingAddressOverride from './map-to-braintree-shipping-address-override';\n\nexport default class BraintreePaypalPaymentStrategy implements PaymentStrategy {\n private _paymentMethod?: PaymentMethod;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _braintreePaymentProcessor: BraintreePaymentProcessor,\n private _credit: boolean = false,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const { braintree: braintreeOptions, methodId } = options;\n\n if (!this._paymentMethod || !this._paymentMethod.nonce) {\n this._paymentMethod = this._store\n .getState()\n .paymentMethods.getPaymentMethodOrThrow(methodId);\n }\n\n if (this._paymentMethod.clientToken) {\n return this._loadPaypal(braintreeOptions);\n }\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n\n this._paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n if (!this._paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n return this._loadPaypal(braintreeOptions);\n }\n\n execute(\n orderRequest: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n return (\n payment\n ? this._preparePaymentData(payment, order.useStoreCredit)\n : Promise.resolve(payment)\n )\n .then((payment) =>\n Promise.all([\n payment,\n this._store.dispatch(this._orderActionCreator.submitOrder(order, options)),\n ]),\n )\n .then(([payment]) =>\n this._store.dispatch(this._paymentActionCreator.submitPayment(payment)),\n )\n .catch((error: Error) => this._handleError(error));\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return this._braintreePaymentProcessor.deinitialize().then(() => this._store.getState());\n }\n\n private _handleError(error: BraintreeError | Error): never {\n if (!isBraintreeError(error)) {\n throw error;\n }\n\n if (error.code === 'PAYPAL_POPUP_CLOSED') {\n throw new PaymentMethodCancelledError(error.message);\n }\n\n throw new PaymentMethodFailedError(error.message);\n }\n\n private async _preparePaymentData(\n payment: OrderPaymentRequestBody,\n useStoreCredit?: boolean,\n ): Promise {\n const state = this._store.getState();\n\n const grandTotal = state.checkout.getOutstandingBalance(useStoreCredit);\n const config = state.config.getStoreConfig();\n\n if (!grandTotal) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!config) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n if (!this._paymentMethod) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const {\n currency,\n storeProfile: { storeLanguage },\n } = config;\n const {\n nonce,\n config: { isVaultingEnabled },\n } = this._paymentMethod;\n const { methodId, paymentData = {} } = payment;\n\n if (nonce) {\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n\n this._paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n return Promise.resolve({ ...payment, paymentData: this._formattedPayload(nonce) });\n }\n\n if (isVaultedInstrument(paymentData) || isHostedVaultedInstrument(paymentData)) {\n if (!isVaultingEnabled) {\n throw new InvalidArgumentError(\n 'Vaulting is disabled but a vaulted instrument was being used for this transaction',\n );\n }\n\n return Promise.resolve(payment);\n }\n\n if (!isHostedInstrumentLike(paymentData)) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = paymentData;\n\n if (shouldSaveInstrument && !isVaultingEnabled) {\n throw new InvalidArgumentError(\n 'Vaulting is disabled but shouldSaveInstrument is set to true',\n );\n }\n\n const shippingAddress = state.shippingAddress.getShippingAddress();\n\n const shippingAddressOverride = shippingAddress\n ? mapToBraintreeShippingAddressOverride(shippingAddress)\n : undefined;\n\n return Promise.all([\n this._braintreePaymentProcessor.paypal({\n amount: grandTotal,\n locale: storeLanguage,\n currency: currency.code,\n offerCredit: this._credit,\n shippingAddressOverride,\n shouldSaveInstrument: shouldSaveInstrument || false,\n shippingAddressEditable: false,\n }),\n this._braintreePaymentProcessor.getSessionId(),\n ]).then(([{ nonce, details } = {} as any, sessionId]) => ({\n ...payment,\n paymentData: this._formattedPayload(\n nonce,\n details && details.email,\n sessionId,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n ),\n }));\n }\n\n private _formattedPayload(\n token: string,\n email?: string,\n sessionId?: string,\n vaultPaymentInstrument?: boolean,\n shouldSetAsDefaultInstrument?: boolean,\n ): FormattedPayload {\n return {\n formattedPayload: {\n vault_payment_instrument: vaultPaymentInstrument || null,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n device_info: sessionId || null,\n paypal_account: {\n token,\n email: email || null,\n },\n },\n };\n }\n\n private _loadPaypal(\n braintreeOptions?: BraintreePaymentInitializeOptions,\n ): Promise {\n if (!this._paymentMethod || !this._paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n try {\n this._braintreePaymentProcessor.initialize(\n this._paymentMethod.clientToken,\n braintreeOptions,\n );\n\n this._braintreePaymentProcessor.preloadPaypal();\n } catch (error) {\n this._handleError(error);\n }\n\n return Promise.resolve(this._store.getState());\n }\n}\n","import { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError, PaymentMethodCancelledError } from '../../errors';\nimport Payment, { FormattedPayload, PaypalInstrument } from '../../payment';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { BraintreeError, BraintreeTokenizePayload, BraintreeVenmoCheckout } from './braintree';\nimport BraintreePaymentProcessor from './braintree-payment-processor';\nimport isBraintreeError from './is-braintree-error';\n\nexport default class BraintreeVenmoPaymentStrategy implements PaymentStrategy {\n private _braintreeVenmoCheckout?: BraintreeVenmoCheckout;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _braintreePaymentProcessor: BraintreePaymentProcessor,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const { methodId } = options;\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n\n const { clientToken } = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n await this._initializeBraintreeVenmo(clientToken);\n\n return this._store.getState();\n }\n\n async execute(\n orderRequest: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n try {\n const paymentData = await this._preparePaymentData(payment);\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentData),\n );\n } catch (error) {\n this._handleError(error);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n async deinitialize(): Promise {\n await this._braintreePaymentProcessor.deinitialize();\n\n return this._store.getState();\n }\n\n private _handleError(error: BraintreeError | Error): never {\n if (!isBraintreeError(error)) {\n throw error;\n }\n\n if (error.code === 'PAYPAL_POPUP_CLOSED') {\n throw new PaymentMethodCancelledError(error.message);\n }\n\n throw new PaymentMethodFailedError(error.message);\n }\n\n private async _initializeBraintreeVenmo(clientToken?: string): Promise {\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n try {\n this._braintreePaymentProcessor.initialize(clientToken);\n this._braintreeVenmoCheckout = await this._braintreePaymentProcessor.getVenmoCheckout();\n } catch (error) {\n this._handleError(error);\n }\n }\n\n private async _preparePaymentData(payment: OrderPaymentRequestBody): Promise {\n const { nonce } = this._store\n .getState()\n .paymentMethods.getPaymentMethodOrThrow(payment.methodId);\n\n if (nonce) {\n return { ...payment, paymentData: this._formattedPayload(nonce) };\n }\n\n const tokenizeResult = await this._braintreeVenmoTokenize();\n const sessionId = await this._braintreePaymentProcessor.getSessionId();\n\n return {\n ...payment,\n paymentData: this._formattedPayload(\n tokenizeResult.nonce,\n tokenizeResult.details.email,\n sessionId,\n ),\n };\n }\n\n private _formattedPayload(\n token: string,\n email?: string,\n sessionId?: string,\n ): FormattedPayload {\n return {\n formattedPayload: {\n vault_payment_instrument: null,\n set_as_default_stored_instrument: null,\n device_info: sessionId || null,\n paypal_account: {\n token,\n email: email || null,\n },\n },\n };\n }\n\n private _braintreeVenmoTokenize(): Promise {\n return new Promise((resolve, reject) => {\n this._braintreeVenmoCheckout?.tokenize(\n (error: BraintreeError, payload: BraintreeTokenizePayload) => {\n if (error) {\n return reject(error);\n }\n\n resolve(payload);\n },\n );\n });\n }\n}\n","import { noop } from 'lodash';\n\nimport { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategyActionCreator from '../../payment-strategy-action-creator';\nimport PaymentStrategy from '../payment-strategy';\n\nimport BraintreeVisaCheckoutPaymentProcessor from './braintree-visacheckout-payment-processor';\nimport { VisaCheckoutPaymentSuccessPayload } from './visacheckout';\nimport VisaCheckoutScriptLoader from './visacheckout-script-loader';\n\nexport default class BraintreeVisaCheckoutPaymentStrategy implements PaymentStrategy {\n private _paymentMethod?: PaymentMethod;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentStrategyActionCreator: PaymentStrategyActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _orderActionCreator: OrderActionCreator,\n private _braintreeVisaCheckoutPaymentProcessor: BraintreeVisaCheckoutPaymentProcessor,\n private _visaCheckoutScriptLoader: VisaCheckoutScriptLoader,\n ) {}\n\n initialize(options: PaymentInitializeOptions): Promise {\n const { braintreevisacheckout: visaCheckoutOptions, methodId } = options;\n\n if (!visaCheckoutOptions) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.braintreevisacheckout\" argument is not provided.',\n );\n }\n\n return this._store\n .dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId))\n .then((state) => {\n this._paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n const checkout = state.checkout.getCheckout();\n const storeConfig = state.config.getStoreConfig();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n if (!this._paymentMethod || !this._paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { onError = noop, onPaymentSelect = noop } = visaCheckoutOptions;\n\n const initOptions = {\n locale: storeConfig.storeProfile.storeLanguage,\n collectShipping: false,\n subtotal: checkout.subtotal,\n currencyCode: storeConfig.currency.code,\n };\n\n return Promise.all([\n this._visaCheckoutScriptLoader.load(this._paymentMethod.config.testMode),\n this._braintreeVisaCheckoutPaymentProcessor.initialize(\n this._paymentMethod.clientToken,\n initOptions,\n ),\n ]).then(([visaCheckout, visaInitOptions]) => {\n visaCheckout.init(visaInitOptions);\n visaCheckout.on(\n 'payment.success',\n (paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) =>\n this._paymentInstrumentSelected(paymentSuccessPayload)\n .then(() => onPaymentSelect())\n .catch((error) => onError(error)),\n );\n visaCheckout.on('payment.error', (_, error) => onError(error));\n });\n })\n .then(() => this._store.getState());\n }\n\n execute(\n orderRequest: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment) {\n throw new InvalidArgumentError(\n 'Unable to submit payment because \"payload.payment\" argument is not provided.',\n );\n }\n\n if (\n !this._paymentMethod ||\n !this._paymentMethod.initializationData ||\n !this._paymentMethod.initializationData.nonce\n ) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { nonce } = this._paymentMethod.initializationData;\n\n return this._store\n .dispatch(this._orderActionCreator.submitOrder(order, options))\n .then(() =>\n this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n ...payment,\n paymentData: { nonce },\n }),\n ),\n )\n .catch((error: Error) => this._handleError(error));\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return this._braintreeVisaCheckoutPaymentProcessor\n .deinitialize()\n .then(() => this._store.getState());\n }\n\n private _paymentInstrumentSelected(paymentSuccessPayload: VisaCheckoutPaymentSuccessPayload) {\n const state = this._store.getState();\n\n if (!this._paymentMethod) {\n throw new Error('Payment method not initialized');\n }\n\n const { id: methodId } = this._paymentMethod;\n\n return this._store.dispatch(\n this._paymentStrategyActionCreator.widgetInteraction(\n () => {\n return this._braintreeVisaCheckoutPaymentProcessor\n .handleSuccess(\n paymentSuccessPayload,\n state.shippingAddress.getShippingAddress(),\n state.billingAddress.getBillingAddress(),\n )\n .then(() =>\n Promise.all([\n this._store.dispatch(\n this._checkoutActionCreator.loadCurrentCheckout(),\n ),\n this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n ),\n ]),\n );\n },\n { methodId },\n ),\n { queueId: 'widgetInteraction' },\n );\n }\n\n private _handleError(error: Error): never {\n if (error.name === 'BraintreeError') {\n throw new PaymentMethodFailedError(error.message);\n }\n\n throw error;\n }\n}\n","import { merge, some } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { RequestError } from '../../../common/error/errors';\nimport { HostedForm } from '../../../hosted-form';\nimport { OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { InstrumentSelector } from '../../instrument';\nimport isCreditCardLike from '../../is-credit-card-like';\nimport isVaultedInstrument from '../../is-vaulted-instrument';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { CardinalThreeDSecureToken } from './cardinal';\nimport CardinalClient, { CardinalOrderData } from './cardinal-client';\n\nexport default class CardinalThreeDSecureFlowV2 {\n constructor(\n private _store: CheckoutStore,\n private _paymentActionCreator: PaymentActionCreator,\n private _cardinalClient: CardinalClient,\n ) {}\n\n async prepare(method: PaymentMethod): Promise {\n await this._cardinalClient.load(method.id, method.config.testMode);\n }\n\n async start(\n execute: PaymentStrategy['execute'],\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n hostedForm?: HostedForm,\n ): Promise {\n const {\n instruments: { getCardInstrument },\n } = this._store.getState();\n const { payment = { methodId: '' } } = payload;\n const { paymentData = {} } = payment;\n\n try {\n return await execute(payload, options);\n } catch (error) {\n if (\n error instanceof RequestError &&\n error.body.status === 'additional_action_required'\n ) {\n const token = error.body.additional_action_required?.data?.token;\n const xid = error.body.three_ds_result?.payer_auth_request;\n\n await this._cardinalClient.configure(token);\n\n const bin = this._getBin(paymentData, getCardInstrument, hostedForm);\n\n if (bin) {\n await this._cardinalClient.runBinProcess(bin);\n }\n\n try {\n return await this._submitPayment(payment, { xid }, hostedForm);\n } catch (error) {\n if (\n error instanceof RequestError &&\n some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n const threeDsResult = error.body.three_ds_result;\n const token = threeDsResult?.payer_auth_request;\n\n await this._cardinalClient.getThreeDSecureData(\n threeDsResult,\n this._getOrderData(),\n );\n\n return await this._submitPayment(payment, { token }, hostedForm);\n }\n\n throw error;\n }\n }\n\n throw error;\n }\n }\n\n private _getOrderData(): CardinalOrderData {\n const store = this._store.getState();\n const billingAddress = store.billingAddress.getBillingAddressOrThrow();\n const shippingAddress = store.shippingAddress.getShippingAddress();\n const {\n cart: {\n currency: { code: currencyCode },\n cartAmount: amount,\n },\n } = store.checkout.getCheckoutOrThrow();\n const id = store.order.getOrderOrThrow().orderId.toString();\n\n return { billingAddress, shippingAddress, currencyCode, id, amount };\n }\n\n private async _submitPayment(\n payment: OrderPaymentRequestBody,\n threeDSecure: CardinalThreeDSecureToken,\n hostedForm?: HostedForm,\n ): Promise {\n const paymentPayload = merge({}, payment, { paymentData: { threeDSecure } });\n\n if (!hostedForm) {\n return this._store.dispatch(this._paymentActionCreator.submitPayment(paymentPayload));\n }\n\n await hostedForm.submit(paymentPayload);\n\n return this._store.getState();\n }\n\n private _getBin(\n paymentData: NonNullable,\n getCardInstrument: InstrumentSelector['getCardInstrument'],\n hostedForm?: HostedForm,\n ): string {\n const instrument =\n isVaultedInstrument(paymentData) && getCardInstrument(paymentData.instrumentId);\n const ccNumber = isCreditCardLike(paymentData) && paymentData.ccNumber;\n const bin = instrument ? instrument.iin : hostedForm ? hostedForm.getBin() : ccNumber;\n\n return bin || '';\n }\n}\n","import isVaultedInstrument from './is-vaulted-instrument';\nimport { CreditCardInstrument, PaymentInstrument } from './payment';\n\nexport default function isCreditCardLike(\n instrument: PaymentInstrument,\n): instrument is CreditCardInstrument {\n const card = instrument as CreditCardInstrument;\n\n return (\n !isVaultedInstrument(card) &&\n typeof card.ccName === 'string' &&\n typeof card.ccNumber === 'string' &&\n typeof card.ccExpiry === 'object' &&\n typeof card.ccExpiry.month === 'string' &&\n typeof card.ccExpiry.year === 'string'\n );\n}\n","import { ThreeDSecure, ThreeDSecureToken } from '../../payment';\n\nexport const CardinalSignatureValidationErrors = [100004, 1010, 1011, 1020];\n\nexport interface CardinalSDK {\n configure(params: CardinalConfiguration): void;\n on(params: CardinalEventType, callback: CardinalEventMap[CardinalEventType]): void;\n off(params: CardinalEventType): void;\n setup(\n initializationType: K,\n initializationData: CardinalInitializationDataMap[K],\n ): void;\n trigger(\n event: CardinalTriggerEvents,\n data?: string,\n ): Promise;\n continue(\n paymentBrand: CardinalPaymentBrand,\n continueObject: CardinalContinue,\n order: CardinalPartialOrder,\n ): void;\n start(paymentBrand: CardinalPaymentBrand, order: CardinalPartialOrder, jwt?: string): void;\n}\n\nexport interface CardinalWindow extends Window {\n Cardinal?: CardinalSDK;\n}\n\nexport interface CardinalEventMap {\n [CardinalEventType.SetupCompleted](setupCompleteData: CardinalSetupCompletedData): void;\n [CardinalEventType.Validated](data: CardinalValidatedData, jwt?: string): void;\n}\n\nexport type CardinalConfiguration = Partial<{\n logging: {\n level: string;\n };\n payment: {\n view: string;\n framework: string;\n displayLoading: boolean;\n };\n}>;\n\nexport interface CardinalSetupCompletedData {\n sessionId: string;\n modules: CardinalModuleState[];\n}\n\nexport interface CardinalModuleState {\n loaded: boolean;\n module: string;\n}\n\nexport enum CardinalInitializationType {\n Init = 'init',\n Complete = 'complete',\n Confirm = 'confirm',\n}\n\nexport interface CardinalInitializationDataMap {\n [CardinalInitializationType.Init]: CardinalInitTypeData;\n [CardinalInitializationType.Complete]: CardinalCompleteTypeData;\n [CardinalInitializationType.Confirm]: CardinalConfirmTypeData;\n}\n\nexport interface CardinalInitTypeData {\n jwt: string;\n}\n\nexport interface CardinalCompleteTypeData {\n Status: string;\n}\n\nexport interface CardinalConfirmTypeData {\n jwt: string;\n cardinalResponseJwt: string;\n}\n\nexport interface CardinalValidatedData {\n ActionCode?: CardinalValidatedAction;\n ErrorDescription: string;\n ErrorNumber: number;\n Validated?: boolean;\n Payment?: CardinalPayment;\n}\n\nexport interface CardinalPayment {\n ExtendedData?: CardinalCCAExtendedData;\n ProcessorTransactionId: string;\n Type: CardinalPaymentType;\n}\n\nexport interface CardinalBinProcessResponse {\n Status: boolean;\n}\n\nexport interface CardinalContinue {\n AcsUrl: string;\n Payload: string;\n}\n\nexport interface CardinalPartialOrder {\n OrderDetails: CardinalOrderDetails;\n Consumer?: CardinalConsumer;\n}\n\nexport interface CardinalConsumer {\n Email1?: string;\n Email2?: string;\n ShippingAddress?: CardinalAddress;\n BillingAddress?: CardinalAddress;\n Account?: CardinalAccount;\n}\n\nexport interface CardinalAccount {\n AccountNumber: number;\n ExpirationMonth: number;\n ExpirationYear: number;\n NameOnAccount: string;\n CardCode: number;\n}\n\nexport interface CardinalAddress {\n FullName?: string;\n FirstName: string;\n MiddleName?: string;\n LastName: string;\n Address1: string;\n Address2?: string;\n Address3?: string;\n City: string;\n State: string;\n PostalCode: string;\n CountryCode: string;\n Phone1?: string;\n Phone2?: string;\n}\n\nexport interface CardinalOrderDetails {\n OrderNumber: string;\n Amount: number;\n CurrencyCode: string;\n OrderDescription?: string;\n OrderChannel: string;\n TransactionId?: string;\n}\n\nexport type CardinalCCAExtendedData = Partial<{\n CAVV: string;\n ECIFlag: string;\n PAResStatus: string;\n SignatureVerification: string;\n XID: string;\n UCAFIndicator: string;\n ChallengeCancel: string;\n}>;\n\nexport enum CardinalEventType {\n SetupCompleted = 'payments.setupComplete',\n Validated = 'payments.validated',\n}\n\nexport enum CardinalValidatedAction {\n Success = 'SUCCESS',\n NoAction = 'NOACTION',\n Failure = 'FAILURE',\n Error = 'ERROR',\n}\n\nexport enum CardinalPaymentType {\n CCA = 'CCA',\n Paypal = 'Paypal',\n Wallet = 'Wallet',\n VisaCheckout = 'VisaCheckout',\n ApplePay = 'ApplePay',\n DiscoverWallet = 'DiscoverWallet',\n}\n\nexport enum CardinalTriggerEvents {\n BinProcess = 'bin.process',\n}\n\nexport enum CardinalPaymentBrand {\n CCA = 'cca',\n}\n\nexport enum CardinalSignatureVerification {\n Yes = 'Y',\n No = 'N',\n}\n\nexport type CardinalThreeDSecureToken = Pick | ThreeDSecureToken;\n","import { includes } from 'lodash';\n\nimport { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Address } from '../../../address';\nimport { BillingAddress } from '../../../billing';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { CreditCardInstrument, ThreeDSecureToken, VaultedInstrument } from '../../payment';\nimport { ThreeDsResult } from '../../payment-response-body';\n\nimport {\n CardinalAccount,\n CardinalAddress,\n CardinalConsumer,\n CardinalEventType,\n CardinalInitializationType,\n CardinalPartialOrder,\n CardinalPaymentBrand,\n CardinalSDK,\n CardinalSignatureValidationErrors,\n CardinalSignatureVerification,\n CardinalTriggerEvents,\n CardinalValidatedAction,\n CardinalValidatedData,\n} from './cardinal';\nimport CardinalScriptLoader from './cardinal-script-loader';\n\nexport type CardinalSupportedPaymentInstrument = CreditCardInstrument | VaultedInstrument;\n\nexport interface CardinalOrderData {\n billingAddress: BillingAddress;\n shippingAddress?: Address;\n currencyCode: string;\n id: string;\n amount: number;\n paymentData?: CreditCardInstrument;\n}\n\nexport default class CardinalClient {\n private _provider = '';\n private _testMode = false;\n private _sdk?: Promise;\n private _configurationToken = '';\n\n constructor(private _scriptLoader: CardinalScriptLoader) {}\n\n load(provider: string, testMode = false): Promise {\n this._provider = provider;\n this._testMode = testMode;\n\n if (!this._sdk) {\n this._sdk = this._scriptLoader.load(provider, testMode);\n }\n\n return this._sdk.then(() => {});\n }\n\n configure(clientToken: string): Promise {\n if (this._configurationToken) {\n if (this._configurationToken === clientToken) {\n return Promise.resolve();\n }\n\n this._sdk = this._scriptLoader.load(`${this._provider}.${Date.now()}`, this._testMode);\n }\n\n return this._getClientSDK().then(\n (client) =>\n new Promise((resolve, reject) => {\n client.on(CardinalEventType.SetupCompleted, () => {\n client.off(CardinalEventType.SetupCompleted);\n client.off(CardinalEventType.Validated);\n\n this._configurationToken = clientToken;\n\n resolve();\n });\n\n client.on(CardinalEventType.Validated, (data: CardinalValidatedData) => {\n client.off(CardinalEventType.SetupCompleted);\n client.off(CardinalEventType.Validated);\n\n switch (data.ActionCode) {\n case CardinalValidatedAction.Error:\n if (includes(CardinalSignatureValidationErrors, data.ErrorNumber)) {\n reject(\n new MissingDataError(\n MissingDataErrorType.MissingPaymentMethod,\n ),\n );\n }\n\n reject(new PaymentMethodFailedError(data.ErrorDescription));\n break;\n }\n });\n\n client.setup(CardinalInitializationType.Init, {\n jwt: clientToken,\n });\n }),\n );\n }\n\n runBinProcess(binNumber: string): Promise {\n return this._getClientSDK()\n .then((client) =>\n client.trigger(CardinalTriggerEvents.BinProcess, binNumber).catch(() => {}),\n )\n .then((result) => {\n if (!result || !result.Status) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n });\n }\n\n getThreeDSecureData(\n threeDSecureData: ThreeDsResult,\n orderData: CardinalOrderData,\n ): Promise {\n return this._getClientSDK().then((client) => {\n return new Promise((resolve, reject) => {\n client.on(\n CardinalEventType.Validated,\n (data: CardinalValidatedData, jwt?: string) => {\n client.off(CardinalEventType.Validated);\n\n if (!jwt) {\n return reject(\n new PaymentMethodFailedError(\n data.ErrorDescription\n ? data.ErrorDescription\n : 'An error was encountered while processing the transaction.',\n ),\n );\n }\n\n if (!data.ActionCode) {\n return resolve({ token: jwt });\n }\n\n switch (data.ActionCode) {\n case CardinalValidatedAction.Success:\n return resolve({ token: jwt });\n\n case CardinalValidatedAction.NoAction:\n if (data.ErrorNumber > 0) {\n return reject(\n new PaymentMethodFailedError(data.ErrorDescription),\n );\n } else if (\n !data.Payment ||\n !data.Payment.ExtendedData ||\n data.Payment.ExtendedData.SignatureVerification !==\n CardinalSignatureVerification.Yes\n ) {\n return reject(\n new PaymentMethodFailedError(\n 'Transaction signature could not be validated.',\n ),\n );\n }\n\n return resolve({ token: jwt });\n\n case CardinalValidatedAction.Failure:\n return reject(\n new PaymentMethodFailedError(\n 'User failed authentication or an error was encountered while processing the transaction.',\n ),\n );\n\n case CardinalValidatedAction.Error:\n return reject(new PaymentMethodFailedError(data.ErrorDescription));\n }\n },\n );\n\n const continueObject = {\n AcsUrl: threeDSecureData.acs_url,\n Payload: threeDSecureData.merchant_data,\n };\n\n const partialOrder = this._mapToPartialOrder(\n orderData,\n threeDSecureData.payer_auth_request,\n );\n\n client.continue(CardinalPaymentBrand.CCA, continueObject, partialOrder);\n });\n });\n }\n\n private _mapToPartialOrder(\n orderData: CardinalOrderData,\n transactionId: string,\n ): CardinalPartialOrder {\n const consumer: CardinalConsumer = {\n BillingAddress: this._mapToCardinalAddress(orderData.billingAddress),\n };\n\n if (orderData.paymentData) {\n consumer.Account = this._mapToCardinalAccount(orderData.paymentData);\n }\n\n if (orderData.billingAddress.email) {\n consumer.Email1 = orderData.billingAddress.email;\n }\n\n if (orderData.shippingAddress) {\n consumer.ShippingAddress = this._mapToCardinalAddress(orderData.shippingAddress);\n }\n\n return {\n Consumer: consumer,\n OrderDetails: {\n OrderNumber: orderData.id,\n Amount: orderData.amount,\n CurrencyCode: orderData.currencyCode,\n OrderChannel: 'S',\n TransactionId: transactionId,\n },\n };\n }\n\n private _mapToCardinalAccount(paymentData: CreditCardInstrument): CardinalAccount {\n return {\n AccountNumber: Number(paymentData.ccNumber),\n ExpirationMonth: Number(paymentData.ccExpiry.month),\n ExpirationYear: Number(paymentData.ccExpiry.year),\n NameOnAccount: paymentData.ccName,\n CardCode: Number(paymentData.ccCvv),\n };\n }\n\n private _mapToCardinalAddress(address: Address): CardinalAddress {\n const cardinalAddress: CardinalAddress = {\n FirstName: address.firstName,\n LastName: address.lastName,\n Address1: address.address1,\n City: address.city,\n State: address.stateOrProvince,\n PostalCode: address.postalCode,\n CountryCode: address.countryCode,\n };\n\n if (address.address2) {\n cardinalAddress.Address2 = address.address2;\n }\n\n if (address.phone) {\n cardinalAddress.Phone1 = address.phone;\n }\n\n return cardinalAddress;\n }\n\n private _getClientSDK(): Promise {\n if (!this._sdk) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._sdk;\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { CardinalSDK, CardinalWindow } from './cardinal';\n\nconst SDK_TEST_URL = 'https://songbirdstag.cardinalcommerce.com/edge/v1/songbird.js';\nconst SDK_PROD_URL = 'https://songbird.cardinalcommerce.com/edge/v1/songbird.js';\n\nexport default class CardinalScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, private _window: CardinalWindow = window) {}\n\n load(provider: string, testMode?: boolean): Promise {\n const url = testMode ? SDK_TEST_URL : SDK_PROD_URL;\n\n return this._scriptLoader.loadScript(`${url}?v=${provider}`).then(() => {\n if (!this._window.Cardinal) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.Cardinal;\n });\n }\n}\n","import { merge, some } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { RequestError } from '../../../common/error/errors';\nimport { HostedForm } from '../../../hosted-form';\nimport { OrderRequestBody } from '../../../order';\nimport isVaultedInstrument from '../../is-vaulted-instrument';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport CardinalClient, { CardinalOrderData } from './cardinal-client';\n\nexport default class CardinalThreeDSecureFlow {\n constructor(\n private _store: CheckoutStore,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _cardinalClient: CardinalClient,\n ) {}\n\n async prepare(method: PaymentMethod): Promise {\n await this._cardinalClient.load(method.id, method.config.testMode);\n await this._cardinalClient.configure(await this._getClientToken(method));\n }\n\n async start(\n execute: PaymentStrategy['execute'],\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n hostedForm?: HostedForm,\n ): Promise {\n const {\n instruments: { getCardInstrument },\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const { payment: { methodId = '', paymentData = {} } = {} } = payload;\n const instrument =\n isVaultedInstrument(paymentData) && getCardInstrument(paymentData.instrumentId);\n const bin = instrument ? instrument.iin : hostedForm && hostedForm.getBin();\n\n if (bin) {\n await this._cardinalClient.runBinProcess(bin);\n }\n\n try {\n return await execute(\n merge(payload, {\n payment: {\n paymentData: {\n threeDSecure: { token: getPaymentMethodOrThrow(methodId).clientToken },\n },\n },\n }),\n options,\n );\n } catch (error) {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n throw error;\n }\n\n const threeDSecure = await this._cardinalClient.getThreeDSecureData(\n error.body.three_ds_result,\n this._getOrderData(),\n );\n\n if (!hostedForm) {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment(\n merge(payload.payment, {\n paymentData: { threeDSecure },\n }),\n ),\n );\n }\n\n await hostedForm.submit(\n merge(payload.payment, {\n paymentData: { threeDSecure },\n }),\n );\n\n return this._store.getState();\n }\n }\n\n private async _getClientToken(method: PaymentMethod): Promise {\n if (method.clientToken) {\n return method.clientToken;\n }\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(method.id),\n );\n\n return getPaymentMethodOrThrow(method.id).clientToken || '';\n }\n\n private _getOrderData(): CardinalOrderData {\n const state = this._store.getState();\n const billingAddress = state.billingAddress.getBillingAddressOrThrow();\n const shippingAddress = state.shippingAddress.getShippingAddress();\n const checkout = state.checkout.getCheckoutOrThrow();\n const order = state.order.getOrderOrThrow();\n\n return {\n billingAddress,\n shippingAddress,\n currencyCode: checkout.cart.currency.code,\n id: order.orderId.toString(),\n amount: checkout.cart.cartAmount,\n };\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * Throw this error if a payment method explicitly returns a declined error and\n * the shopper has to choose a different payment method if they wish to continue\n * their checkout process.\n */\nexport default class PaymentMethodDeclinedError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'The selected payment method was declined. Please select another payment method.',\n );\n\n this.name = 'PaymentMethodDeclinedError';\n this.type = 'payment_declined';\n }\n}\n","export const THREE_D_SECURE_PROCEED = 'PROCEED';\nexport const THREE_D_SECURE_BUSY = 'SERVER_BUSY';\nexport const THREE_D_SECURE_AVAILABLE = 'AUTHENTICATION_AVAILABLE';\n\nexport interface CBAMPGSHostWindow extends Window {\n ThreeDS?: ThreeDSjs;\n}\n\nexport interface ThreeDSjs {\n // Configuration method for initializing the API.\n configure(config: ThreeDSConfiguration): Promise;\n // Convenience method to check if the API has been configured successfully.\n isConfigured(): boolean;\n // Authentication for the arguments passed.\n initiateAuthentication(\n orderId: string,\n transactionId: string,\n callback: (data: ThreeDSAuthenticationResponse) => void,\n ): void;\n authenticatePayer(\n orderId: string,\n transactionId: string,\n callback: (data: ThreeDSAuthenticationResponse) => void,\n optionalParams?: AuthenticatePayerOptionalParams,\n ): void;\n}\n\nexport interface RestApiResponse {\n transaction: {\n authenticationStatus: string;\n };\n}\n\n// Configuration required to configure ThreeDS\nexport interface ThreeDSConfiguration {\n merchantId: string;\n sessionId: string;\n configuration: ThreeDSAPIConfiguration;\n callback(): void;\n}\n\nexport interface ThreeDSAuthenticationResponse {\n error?: ThreeDSAuthenticationError;\n restApiResponse: RestApiResponse;\n gatewayRecommendation: string;\n}\n\nexport interface AuthenticatePayerOptionalParams {\n fullScreenRedirect: boolean;\n}\n\nexport interface ThreeDSAuthenticationError {\n code: string;\n msg: string;\n cause?: string;\n}\n\n// JSON value supporting data elements like userLanguage, REST API version (wsVersion)\nexport interface ThreeDSAPIConfiguration {\n // A language identifier or IETF language tag to control the language of the payment page displayed to the payer.\n // For example, \"en_US\", es, \"fr-CA\". By default, the language is \"en_US\".\n userLanguage: string;\n // The Web Services API version that you submitted the request in. IE: 62\n wsVersion: number;\n}\n","import { noop, some } from 'lodash';\n\nimport { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError, PaymentMethodDeclinedError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nimport {\n RestApiResponse,\n THREE_D_SECURE_AVAILABLE,\n THREE_D_SECURE_BUSY,\n THREE_D_SECURE_PROCEED,\n ThreeDSjs,\n} from './cba-mpgs';\nimport CBAMPGSScriptLoader from './cba-mpgs-script-loader';\n\nexport default class CBAMPGSPaymentStrategy extends CreditCardPaymentStrategy {\n private _threeDSjs?: ThreeDSjs;\n private _sessionId = '';\n\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _CBAMGPSScriptLoader: CBAMPGSScriptLoader,\n private _locale: string,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const { methodId } = options;\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n const {\n clientToken,\n initializationData: { isTestModeFlagEnabled = false, merchantId },\n config: { is3dsEnabled },\n } = paymentMethod;\n\n if (is3dsEnabled) {\n this._threeDSjs = await this._CBAMGPSScriptLoader.load(isTestModeFlagEnabled);\n\n if (!this._threeDSjs) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!clientToken || !merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._sessionId = clientToken;\n\n await this._threeDSjs.configure({\n merchantId,\n sessionId: this._sessionId,\n callback: () => {\n if (this._threeDSjs?.isConfigured()) {\n return this._store.getState();\n }\n\n throw new PaymentMethodFailedError('Failed to configure 3DS API.');\n },\n configuration: {\n userLanguage: this._locale,\n wsVersion: 62,\n },\n });\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment } = payload;\n const paymentData = payment && payment.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(payment.methodId);\n\n const { is3dsEnabled } = paymentMethod.config;\n\n if (is3dsEnabled) {\n const newPaymentData = {\n ...paymentData,\n threeDSecure: { token: this._sessionId },\n };\n\n if (payload.payment) {\n payload.payment.paymentData = newPaymentData;\n }\n }\n\n return super.execute(payload, options).catch((error) => {\n if (\n !is3dsEnabled ||\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return Promise.reject(error);\n }\n\n const state = this._store.getState();\n const order = state.order.getOrder();\n const {\n storeProfile: { storeId },\n } = state.config.getStoreConfigOrThrow();\n\n if (!order || !this._sessionId) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n const orderId = `${storeId}_${order.orderId}`;\n\n const {\n three_ds_result: { token: transactionId },\n } = error.body;\n\n if (!transactionId) {\n return Promise.reject(error);\n }\n\n return this._initiateAuthentication(orderId, transactionId);\n });\n }\n\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this._store.getState();\n const order = state.order.getOrder();\n\n if (order && state.payment.getPaymentStatus() === paymentStatusTypes.FINALIZE) {\n return this._store.dispatch(\n this._orderActionCreator.finalizeOrder(order.orderId, options),\n );\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n this._threeDSjs = undefined;\n this._sessionId = '';\n\n return super.deinitialize();\n }\n\n private async _initiateAuthentication(\n orderId: string,\n transactionId: string,\n ): Promise {\n const response: RestApiResponse = await new Promise((resolve, reject) => {\n if (!this._threeDSjs) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._threeDSjs.initiateAuthentication(orderId, transactionId, (data) => {\n const error = data.error;\n\n if (error) {\n return reject(new PaymentMethodDeclinedError(error.msg));\n }\n\n if (this._threeDSjs && data.gatewayRecommendation === THREE_D_SECURE_PROCEED) {\n return resolve(data.restApiResponse);\n }\n\n return reject(new PaymentMethodDeclinedError());\n });\n });\n\n if (\n response.transaction &&\n response.transaction.authenticationStatus === THREE_D_SECURE_AVAILABLE\n ) {\n return this._authenticatePayer(orderId, transactionId);\n }\n\n throw new PaymentMethodDeclinedError();\n }\n\n private async _authenticatePayer(\n orderId: string,\n transactionId: string,\n attempt = 1,\n ): Promise {\n return new Promise((_resolve, reject) => {\n if (!this._threeDSjs) {\n return reject(\n new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n this._threeDSjs.authenticatePayer(\n orderId,\n transactionId,\n async (data) => {\n const error = data.error;\n\n if (error) {\n if (error.cause && error.cause === THREE_D_SECURE_BUSY && attempt < 5) {\n // Wait 3 seconds for MPGS server to process the `initiateAuthentication` call\n // See: Step 1: Initiate Authentication -> Initiate Authentication Request:\n // https://ap-gateway.mastercard.com/api/documentation/integrationGuidelines/supportedFeatures/pickAdditionalFunctionality/authentication/3DS/integrationModelAPI.html?locale=en_US#x_3DSTest\n await new Promise((resolve) => setTimeout(resolve, 3000));\n\n return this._authenticatePayer(orderId, transactionId, ++attempt);\n }\n\n return reject(new PaymentMethodDeclinedError());\n }\n\n // ThreeDSjs will handle the redirect so return a promise that doesn't really resolve\n return new Promise(noop);\n },\n { fullScreenRedirect: true },\n );\n });\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { CBAMPGSHostWindow, ThreeDSjs } from './cba-mpgs';\n\nexport default class CBAMPGSScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, private _window: CBAMPGSHostWindow = window) {}\n\n async load(testMode?: boolean): Promise {\n await this._scriptLoader.loadScript(\n `//${\n testMode ? 'test' : 'ap'\n }-gateway.mastercard.com/static/threeDS/1.3.0/three-ds.min.js`,\n );\n\n if (!this._window.ThreeDS) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.ThreeDS;\n }\n}\n","export enum ChasePayEventType {\n StartCheckout = 'startCheckout',\n CompleteCheckout = 'completeCheckout',\n CancelCheckout = 'cancelCheckout',\n}\n\nexport interface ChasePayEventMap {\n [ChasePayEventType.StartCheckout](digitalSessionId: string): void;\n [ChasePayEventType.CompleteCheckout](payload: ChasePaySuccessPayload): void;\n [ChasePayEventType.CancelCheckout](): void;\n}\n\nexport interface ChasePayHostWindow extends Window {\n JPMC?: JPMC;\n}\n\nexport interface JPMC {\n ChasePay: ChasePay;\n}\n\nexport interface ChasePaySuccessPayload {\n sessionToken: string;\n}\n\nexport interface ChasePayInsertOptions {\n color?: string;\n containers?: string[];\n height?: number;\n width?: number;\n}\n\nexport interface ChasePayConfigureOptions {\n language?: string;\n zindex?: number;\n sessionWarningTime?: number;\n sessionTimeoutTime?: number;\n}\n\nexport interface ChasePay {\n EventType: {\n START_CHECKOUT: ChasePayEventType.StartCheckout;\n COMPLETE_CHECKOUT: ChasePayEventType.CompleteCheckout;\n CANCEL_CHECKOUT: ChasePayEventType.CancelCheckout;\n };\n isChasePayUp: boolean;\n insertButtons(options: ChasePayInsertOptions): void;\n insertBrandings(options: ChasePayInsertOptions): void;\n startCheckout(digitalSessionId?: string): void;\n showLoadingAnimation(): void;\n configure(options: ChasePayConfigureOptions): void;\n on(\n eventType: ChasePayEventType,\n callback: ChasePayEventMap[ChasePayEventType],\n ): void;\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\nimport { Subject } from 'rxjs';\nimport { take } from 'rxjs/operators';\n\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { SDK_VERSION_HEADERS } from '../../../common/http-request';\nimport { bindDecorator as bind } from '../../../common/utility';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentMethodCancelledError } from '../../errors';\nimport Payment from '../../payment';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategyActionCreator from '../../payment-strategy-action-creator';\nimport PaymentStrategy from '../payment-strategy';\nimport { WepayRiskClient } from '../wepay';\n\nimport { ChasePay, ChasePayEventType, ChasePaySuccessPayload } from './chasepay';\nimport ChasePayInitializeOptions from './chasepay-initialize-options';\nimport ChasePayScriptLoader from './chasepay-script-loader';\n\nexport default class ChasePayPaymentStrategy implements PaymentStrategy {\n private _chasePayClient?: ChasePay;\n private _methodId!: string;\n private _walletButton?: HTMLElement;\n private _walletEvent$: Subject<{ type: ChasePayEventType }>;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentStrategyActionCreator: PaymentStrategyActionCreator,\n private _requestSender: RequestSender,\n private _chasePayScriptLoader: ChasePayScriptLoader,\n private _wepayRiskClient: WepayRiskClient,\n ) {\n this._walletEvent$ = new Subject();\n }\n\n initialize(options: PaymentInitializeOptions): Promise {\n this._methodId = options.methodId;\n\n if (!options.chasepay) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.chasepay\" argument is not provided.',\n );\n }\n\n const walletButton =\n options.chasepay.walletButton && document.getElementById(options.chasepay.walletButton);\n\n if (walletButton) {\n this._walletButton = walletButton;\n this._walletButton.addEventListener('click', this._handleWalletButtonClick);\n }\n\n return this._configureWallet(options.chasepay).then(() => this._store.getState());\n }\n\n deinitialize(): Promise {\n if (this._walletButton) {\n this._walletButton.removeEventListener('click', this._handleWalletButtonClick);\n }\n\n this._walletButton = undefined;\n this._chasePayClient = undefined;\n\n return Promise.resolve(this._store.getState());\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n return this._getPayment()\n .catch((error) => {\n if (error.subtype === MissingDataErrorType.MissingPayment) {\n return this._displayWallet().then(() => this._getPayment());\n }\n\n throw error;\n })\n .then((payment) => this._createOrder(payment, payload.useStoreCredit, options));\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private _configureWallet(options: ChasePayInitializeOptions): Promise {\n const state = this._store.getState();\n const paymentMethod = state.paymentMethods.getPaymentMethod(this._methodId);\n const storeConfig = state.config.getStoreConfig();\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n return this._chasePayScriptLoader\n .load(paymentMethod.config.testMode)\n .then(({ ChasePay }) => {\n this._chasePayClient = ChasePay;\n\n if (options.logoContainer && document.getElementById(options.logoContainer)) {\n this._chasePayClient.insertBrandings({\n color: 'white',\n containers: [options.logoContainer],\n });\n }\n\n this._chasePayClient.configure({\n language: storeConfig.storeProfile.storeLanguage,\n });\n\n this._chasePayClient.on(ChasePayEventType.CancelCheckout, () => {\n this._walletEvent$.next({ type: ChasePayEventType.CancelCheckout });\n\n if (options.onCancel) {\n options.onCancel();\n }\n });\n\n this._chasePayClient.on(\n ChasePayEventType.CompleteCheckout,\n (payload: ChasePaySuccessPayload) => {\n this._setSessionToken(payload.sessionToken).then(() => {\n this._walletEvent$.next({ type: ChasePayEventType.CompleteCheckout });\n\n if (options.onPaymentSelect) {\n options.onPaymentSelect();\n }\n });\n },\n );\n });\n }\n\n private _displayWallet(): Promise {\n return this._store.dispatch(\n this._paymentStrategyActionCreator.widgetInteraction(\n () => {\n this._store\n .dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(this._methodId),\n )\n .then((state) => {\n const paymentMethod = state.paymentMethods.getPaymentMethod(\n this._methodId,\n );\n\n if (!this._chasePayClient) {\n throw new NotInitializedError(\n NotInitializedErrorType.PaymentNotInitialized,\n );\n }\n\n if (!paymentMethod) {\n throw new MissingDataError(\n MissingDataErrorType.MissingPaymentMethod,\n );\n }\n\n this._chasePayClient.showLoadingAnimation();\n this._chasePayClient.startCheckout(\n paymentMethod.initializationData.digitalSessionId,\n );\n });\n\n // Wait for payment selection\n return new Promise((resolve, reject) => {\n this._walletEvent$\n .pipe(take(1))\n .subscribe((event: { type: ChasePayEventType }) => {\n if (event.type === ChasePayEventType.CancelCheckout) {\n reject(new PaymentMethodCancelledError());\n } else if (event.type === ChasePayEventType.CompleteCheckout) {\n resolve();\n }\n });\n });\n },\n { methodId: this._methodId },\n ),\n { queueId: 'widgetInteraction' },\n );\n }\n\n private _setSessionToken(sessionToken: string): Promise {\n const state = this._store.getState();\n const paymentMethod = state.paymentMethods.getPaymentMethod(this._methodId);\n const merchantRequestId =\n paymentMethod && paymentMethod.initializationData.merchantRequestId;\n\n return (\n this._requestSender\n .post('checkout.php', {\n headers: {\n Accept: 'text/html',\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n ...SDK_VERSION_HEADERS,\n },\n body: {\n action: 'set_external_checkout',\n provider: this._methodId,\n sessionToken,\n merchantRequestId,\n },\n })\n // Re-hydrate checkout data\n .then(() =>\n Promise.all([\n this._store.dispatch(this._checkoutActionCreator.loadCurrentCheckout()),\n this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(this._methodId),\n ),\n ]),\n )\n .then(() => this._store.getState())\n );\n }\n\n private _getPayment(): Promise {\n return this._store\n .dispatch(this._paymentMethodActionCreator.loadPaymentMethod(this._methodId))\n .then(() => {\n if (this._methodId === 'wepay') {\n return this._wepayRiskClient\n .initialize()\n .then((client) => client.getRiskToken());\n }\n\n return '';\n })\n .then((riskToken) => {\n const state = this._store.getState();\n const paymentMethod = state.paymentMethods.getPaymentMethod(this._methodId);\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (!paymentMethod.initializationData.paymentCryptogram) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n const paymentData = {\n method: this._methodId,\n cryptogramId: paymentMethod.initializationData.paymentCryptogram,\n eci: paymentMethod.initializationData.eci,\n transactionId: btoa(paymentMethod.initializationData.reqTokenId),\n ccExpiry: {\n month: paymentMethod.initializationData.expDate.toString().substr(0, 2),\n year: paymentMethod.initializationData.expDate.toString().substr(2, 2),\n },\n ccNumber: paymentMethod.initializationData.accountNum,\n accountMask: paymentMethod.initializationData.accountMask,\n extraData: riskToken ? { riskToken } : undefined,\n };\n\n return {\n methodId: this._methodId,\n paymentData,\n };\n });\n }\n\n private _createOrder(\n payment: Payment,\n useStoreCredit?: boolean,\n options?: PaymentRequestOptions,\n ): Promise {\n return this._store\n .dispatch(this._orderActionCreator.submitOrder({ useStoreCredit }, options))\n .then(() => this._store.dispatch(this._paymentActionCreator.submitPayment(payment)));\n }\n\n @bind\n private _handleWalletButtonClick(event: Event): void {\n event.preventDefault();\n\n this._displayWallet();\n }\n}\n","export default interface PaymentResponseBody {\n status: string;\n id: string;\n avs_result: AvsResult | {};\n cvv_result: CvvResult | {};\n three_ds_result: ThreeDsResult | {};\n fraud_review: boolean;\n transaction_type: string;\n additional_action_required?: AdditionalActionRequired;\n errors?: Array<{\n code: string;\n message: string;\n }>;\n}\n\nexport interface AvsResult {\n code: string;\n message: string;\n street_match: string;\n postal_match: string;\n}\n\nexport interface CvvResult {\n code: string;\n message: string;\n}\n\nexport interface ThreeDsResult {\n acs_url: string;\n payer_auth_request: string;\n merchant_data: string;\n callback_url: string;\n}\n\nexport interface AdditionalActionRequired {\n type: AdditionalActionType;\n data: AdditionalRedirectData;\n}\n\nexport interface AdditionalRedirectData {\n redirect_url: string;\n transaction_id?: string;\n}\n\nexport enum AdditionalActionType {\n OffsiteRedirect = 'offsite_redirect',\n}\n","import { InternalCheckoutSelectors } from '../../../checkout';\nimport {\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport { AdditionalActionRequired, AdditionalActionType } from '../../payment-response-body';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class CheckoutcomCustomPaymentStrategy extends CreditCardPaymentStrategy {\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this._store.getState();\n const order = state.order.getOrder();\n\n if (order && state.payment.getPaymentStatus() === paymentStatusTypes.FINALIZE) {\n return this._store.dispatch(\n this._orderActionCreator.finalizeOrder(order.orderId, options),\n );\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n protected async _executeWithHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!payment || !payment.methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n try {\n await form.validate();\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n await form.submit(payment);\n } catch (error) {\n return this._processResponse(error);\n }\n\n return this._store.dispatch(this._orderActionCreator.loadCurrentOrder());\n }\n\n protected _processResponse(error: RequestError): Promise {\n if (!(error instanceof RequestError)) {\n return Promise.reject(error);\n }\n\n const additionalActionRequired: AdditionalActionRequired =\n error.body.additional_action_required;\n\n // TODO validate all possible responses and perform respective additional actions\n if (\n additionalActionRequired &&\n additionalActionRequired.type === AdditionalActionType.OffsiteRedirect\n ) {\n return this._performRedirect(additionalActionRequired);\n }\n\n return Promise.reject(error);\n }\n\n private _performRedirect(\n additionalActionRequired: AdditionalActionRequired,\n ): Promise {\n return new Promise(() => {\n window.location.replace(additionalActionRequired.data.redirect_url);\n });\n }\n}\n","import { InternalCheckoutSelectors } from '../../../../checkout';\nimport { OrderRequestBody } from '../../../../order';\nimport { PaymentArgumentInvalidError } from '../../../errors';\nimport { PaymentInstrument, WithDocumentInstrument } from '../../../payment';\nimport { PaymentRequestOptions } from '../../../payment-request-options';\nimport CheckoutcomCustomPaymentStrategy from '../checkoutcom-custom-payment-strategy';\n\nconst DOCUMENT_SUPPORTED_APMS = ['boleto', 'oxxo', 'qpay', 'ideal'];\n\nexport default class CheckoutcomAPMPaymentStrategy extends CheckoutcomCustomPaymentStrategy {\n protected async _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment?.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n ...payment,\n paymentData: {\n ...paymentData,\n formattedPayload: this._createFormattedPayload(\n payment.methodId,\n paymentData,\n ),\n },\n }),\n );\n } catch (error) {\n return this._processResponse(error);\n }\n }\n\n private _createFormattedPayload(\n methodId: string,\n paymentData: PaymentInstrument,\n ): WithDocumentInstrument {\n const formattedPayload: WithDocumentInstrument = { ccDocument: '' };\n const ccDocument = 'ccDocument' in paymentData ? paymentData.ccDocument : '';\n\n if (DOCUMENT_SUPPORTED_APMS.indexOf(methodId) !== -1 && ccDocument) {\n formattedPayload.ccDocument = ccDocument;\n }\n\n return formattedPayload;\n }\n}\n","import { InternalCheckoutSelectors } from '../../../../checkout';\nimport { OrderRequestBody } from '../../../../order';\nimport { PaymentArgumentInvalidError } from '../../../errors';\nimport { PaymentInstrument, WithCheckoutcomFawryInstrument } from '../../../payment';\nimport { PaymentRequestOptions } from '../../../payment-request-options';\nimport CheckoutcomCustomPaymentStrategy from '../checkoutcom-custom-payment-strategy';\n\nconst CHECKOUTCOM_FAWRY_PAYMENT_METHOD = 'fawry';\n\nexport default class CheckoutcomFawryPaymentStrategy extends CheckoutcomCustomPaymentStrategy {\n protected async _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment && payment.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n ...payment,\n paymentData: {\n ...paymentData,\n formattedPayload: this._createFormattedPayload(\n payment.methodId,\n paymentData,\n ),\n },\n }),\n );\n } catch (error) {\n return this._processResponse(error);\n }\n }\n\n private _createFormattedPayload(\n methodId: string,\n paymentData: PaymentInstrument,\n ): WithCheckoutcomFawryInstrument | undefined {\n if (\n CHECKOUTCOM_FAWRY_PAYMENT_METHOD === methodId &&\n 'customerMobile' in paymentData &&\n 'customerEmail' in paymentData\n ) {\n return {\n customerMobile: paymentData.customerMobile,\n customerEmail: paymentData.customerEmail,\n };\n }\n }\n}\n","import { InternalCheckoutSelectors } from '../../../../checkout';\nimport { OrderRequestBody } from '../../../../order';\nimport { PaymentArgumentInvalidError } from '../../../errors';\nimport { PaymentInstrument, WithCheckoutcomiDealInstrument } from '../../../payment';\nimport { PaymentRequestOptions } from '../../../payment-request-options';\nimport CheckoutcomCustomPaymentStrategy from '../checkoutcom-custom-payment-strategy';\n\nconst CHECKOUTCOM_IDEAL_PAYMENT_METHOD = 'ideal';\n\nexport default class CheckoutcomiDealPaymentStrategy extends CheckoutcomCustomPaymentStrategy {\n protected async _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment?.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n ...payment,\n paymentData: {\n ...paymentData,\n formattedPayload: this._createFormattedPayload(\n payment.methodId,\n paymentData,\n ),\n },\n }),\n );\n } catch (error) {\n return this._processResponse(error);\n }\n }\n\n private _createFormattedPayload(\n methodId: string,\n paymentData: PaymentInstrument,\n ): WithCheckoutcomiDealInstrument | undefined {\n if (CHECKOUTCOM_IDEAL_PAYMENT_METHOD === methodId && 'bic' in paymentData) {\n return { bic: paymentData.bic };\n }\n }\n}\n","import { InternalCheckoutSelectors } from '../../../../checkout';\nimport { OrderRequestBody } from '../../../../order';\nimport { PaymentArgumentInvalidError } from '../../../errors';\nimport { PaymentInstrument, WithCheckoutcomSEPAInstrument } from '../../../payment';\nimport { PaymentRequestOptions } from '../../../payment-request-options';\nimport CheckoutcomCustomPaymentStrategy from '../checkoutcom-custom-payment-strategy';\n\nconst CHECKOUTCOM_SEPA_PAYMENT_METHOD = 'sepa';\n\nexport default class CheckoutcomSEPAPaymentStrategy extends CheckoutcomCustomPaymentStrategy {\n protected async _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment?.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n ...payment,\n paymentData: {\n ...paymentData,\n formattedPayload: this._createFormattedPayload(\n payment.methodId,\n paymentData,\n ),\n },\n }),\n );\n } catch (error) {\n return this._processResponse(error);\n }\n }\n\n private _createFormattedPayload(\n methodId: string,\n paymentData: PaymentInstrument,\n ): WithCheckoutcomSEPAInstrument {\n const formattedPayload: WithCheckoutcomSEPAInstrument = { iban: '', bic: '' };\n const { iban, bic } = 'iban' in paymentData ? paymentData : formattedPayload;\n\n if (methodId === CHECKOUTCOM_SEPA_PAYMENT_METHOD && document) {\n formattedPayload.iban = iban;\n formattedPayload.bic = bic;\n }\n\n return formattedPayload;\n }\n}\n","import { noop } from 'lodash';\n\nimport { CheckoutStore, CheckoutValidator, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { RequestOptions } from '../../../common/http-request';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotCompletedError } from '../../../order/errors';\nimport { RemoteCheckoutRequestSender } from '../../../remote-checkout';\nimport { StoreCreditActionCreator } from '../../../store-credit';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport ClearpayScriptLoader from './clearpay-script-loader';\nimport ClearpaySdk from './clearpay-sdk';\n\nexport default class ClearpayPaymentStrategy implements PaymentStrategy {\n private _clearpaySdk?: ClearpaySdk;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutValidator: CheckoutValidator,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _remoteCheckoutRequestSender: RemoteCheckoutRequestSender,\n private _storeCreditActionCreator: StoreCreditActionCreator,\n private _clearpayScriptLoader: ClearpayScriptLoader,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(options.methodId, options.gatewayId);\n\n this._clearpaySdk = await this._clearpayScriptLoader.load(paymentMethod);\n\n return this._store.getState();\n }\n\n deinitialize(): Promise {\n this._clearpaySdk = undefined;\n\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n if (!payload.payment) {\n throw new PaymentArgumentInvalidError(['payment.gatewayId', 'payment.methodId']);\n }\n\n const { gatewayId, methodId } = payload.payment;\n\n if (!gatewayId || !methodId) {\n throw new PaymentArgumentInvalidError(['payment.gatewayId', 'payment.methodId']);\n }\n\n const { isStoreCreditApplied: useStoreCredit } = this._store\n .getState()\n .checkout.getCheckoutOrThrow();\n let state = this._store.getState();\n\n if (useStoreCredit !== undefined) {\n state = await this._store.dispatch(\n this._storeCreditActionCreator.applyStoreCredit(useStoreCredit),\n );\n }\n\n await this._checkoutValidator.validate(state.checkout.getCheckout(), options);\n\n const { countryCode } = this._store.getState().billingAddress.getBillingAddressOrThrow();\n\n if (!this._isCountrySupported(countryCode)) {\n throw new InvalidArgumentError(\n 'Unable to proceed because billing country is not supported.',\n );\n }\n\n state = await this._loadPaymentMethod(gatewayId, methodId, options);\n\n await this._redirectToClearpay(\n countryCode,\n state.paymentMethods.getPaymentMethod(methodId, gatewayId),\n );\n\n // Clearpay will handle the rest of the flow so return a promise that doesn't really resolve\n return new Promise(noop);\n }\n\n async finalize(options: PaymentRequestOptions): Promise {\n const state = this._store.getState();\n const payment = state.payment.getPaymentId();\n const config = state.config.getContextConfig();\n\n if (!payment) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!config || !config.payment.token) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const paymentPayload = {\n methodId: payment.providerId,\n paymentData: { nonce: config.payment.token },\n };\n\n await this._store.dispatch(this._orderActionCreator.submitOrder({}, options));\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentPayload),\n );\n } catch (error) {\n await this._remoteCheckoutRequestSender.forgetCheckout();\n await this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethods());\n\n throw new OrderFinalizationNotCompletedError(error.body?.errors?.[0]?.message);\n }\n }\n\n private _redirectToClearpay(countryCode: string, paymentMethod?: PaymentMethod): void {\n if (!this._clearpaySdk || !paymentMethod || !paymentMethod.clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._clearpaySdk.initialize({ countryCode });\n this._clearpaySdk.redirect({ token: paymentMethod.clientToken });\n }\n\n private _isCountrySupported(countryCode: string): boolean {\n return countryCode === 'GB';\n }\n\n private async _loadPaymentMethod(\n gatewayId: string,\n methodId: string,\n options?: RequestOptions,\n ): Promise {\n try {\n return await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(gatewayId, {\n ...options,\n params: { ...options?.params, method: methodId },\n }),\n );\n } catch (error) {\n if (error instanceof RequestError && error.body?.status === 422) {\n throw new InvalidArgumentError(\n \"Clearpay can't process your payment for this order, please try another payment method\",\n );\n }\n\n throw error;\n }\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\nimport PaymentMethod from '../../payment-method';\n\nimport ClearpaySdk from './clearpay-sdk';\nimport ClearpayWindow from './clearpay-window';\n\nconst SCRIPTS_DEFAULT = {\n PROD: '//portal.clearpay.co.uk/afterpay-async.js',\n SANDBOX: '//portal.sandbox.clearpay.co.uk/afterpay-async.js',\n};\n\nexport default class ClearpayScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, public _window: ClearpayWindow = window) {}\n\n async load(method: PaymentMethod): Promise {\n await this._scriptLoader.loadScript(this._getScriptUrl(method.config.testMode));\n\n if (!this._window.AfterPay) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.AfterPay;\n }\n\n private _getScriptUrl(testMode?: boolean): string {\n return testMode ? SCRIPTS_DEFAULT.SANDBOX : SCRIPTS_DEFAULT.PROD;\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { some } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { RequestError } from '../../../common/error/errors';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class ConvergePaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _formPoster: FormPoster,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n return super.execute(payload, options).catch((error) => {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return Promise.reject(error);\n }\n\n return new Promise(() => {\n this._formPoster.postForm(error.body.three_ds_result.acs_url, {\n PaReq: error.body.three_ds_result.payer_auth_request,\n TermUrl: error.body.three_ds_result.callback_url,\n MD: error.body.three_ds_result.merchant_data,\n });\n });\n });\n }\n\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this._store.getState();\n const order = state.order.getOrder();\n\n if (order && state.payment.getPaymentStatus() === paymentStatusTypes.FINALIZE) {\n return this._store.dispatch(\n this._orderActionCreator.finalizeOrder(order.orderId, options),\n );\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { some } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class CreditCardRedirectPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n protected _store: CheckoutStore,\n protected _orderActionCreator: OrderActionCreator,\n protected _paymentActionCreator: PaymentActionCreator,\n protected _hostedFormFactory: HostedFormFactory,\n protected _formPoster: FormPoster,\n ) {\n super(_store, _orderActionCreator, _paymentActionCreator, _hostedFormFactory);\n }\n\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this._store.getState();\n const order = state.order.getOrder();\n\n if (order && state.payment.getPaymentStatus() === paymentStatusTypes.FINALIZE) {\n return this._store.dispatch(\n this._orderActionCreator.finalizeOrder(order.orderId, options),\n );\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n protected async _executeWithoutHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment && payment.paymentData;\n\n if (!payment || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({ ...payment, paymentData }),\n );\n } catch (error) {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return Promise.reject(error);\n }\n\n return new Promise(() =>\n this._formPoster.postForm(error.body.three_ds_result.acs_url, {\n PaReq: error.body.three_ds_result.payer_auth_request || null,\n TermUrl: error.body.three_ds_result.callback_url || null,\n MD: error.body.three_ds_result.merchant_data || null,\n }),\n );\n }\n }\n\n protected async _executeWithHostedForm(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!payment || !payment.methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n try {\n await form.validate();\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n await form.submit(payment);\n } catch (error) {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return Promise.reject(error);\n }\n\n return new Promise(() =>\n this._formPoster.postForm(error.body.three_ds_result.acs_url, {\n PaReq: error.body.three_ds_result.payer_auth_request || null,\n TermUrl: error.body.three_ds_result.callback_url || null,\n MD: error.body.three_ds_result.merchant_data || null,\n }),\n );\n }\n\n return this._store.dispatch(this._orderActionCreator.loadCurrentOrder());\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { CardinalThreeDSecureFlow } from '../cardinal';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class CyberSourcePaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _threeDSecureFlow: CardinalThreeDSecureFlow,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(options.methodId);\n\n if (paymentMethod.config.is3dsEnabled) {\n await this._threeDSecureFlow.prepare(paymentMethod);\n }\n\n return this._store.getState();\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment: { methodId = '' } = {} } = payload;\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n\n if (getPaymentMethodOrThrow(methodId).config.is3dsEnabled) {\n return this._threeDSecureFlow.start(\n super.execute.bind(this),\n payload,\n options,\n this._hostedForm,\n );\n }\n\n return super.execute(payload, options);\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { CardinalThreeDSecureFlowV2 } from '../cardinal';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class CyberSourceV2PaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _threeDSecureFlow: CardinalThreeDSecureFlowV2,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(options.methodId);\n\n if (paymentMethod.config.is3dsEnabled) {\n await this._threeDSecureFlow.prepare(paymentMethod);\n }\n\n return this._store.getState();\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment: { methodId = '' } = {} } = payload;\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n\n if (getPaymentMethodOrThrow(methodId).config.is3dsEnabled) {\n return this._threeDSecureFlow.start(\n super.execute.bind(this),\n payload,\n options,\n this._hostedForm,\n );\n }\n\n return super.execute(payload, options);\n }\n}\n","export interface DigitalRiverWindow extends Window {\n /**\n * Object to create an instance of the DigitalRiver object. This is called a Digital River publishable API key\n * This function accepts an optional options object using the following format DigitalRiver(publishableApiKey{, options})\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/digitalriver.js/reference/digital-river-publishable-api-key\n */\n DigitalRiver?: DigitalRiverClass;\n}\n\nexport type DigitalRiverClass = new (\n apiKey: string,\n options?: DigitalRiverJSOptions,\n) => DigitalRiverJS;\n\nexport default interface DigitalRiverJS {\n createDropin(configuration: DigitalRiverDropInConfiguration): DigitalRiverDropIn;\n authenticateSource(\n data: DigitalRiverAuthenticateSourceRequest,\n ): Promise;\n createElement(type: string, options: DigitalRiverElementOptions): DigitalRiverElement;\n}\n\nexport interface DigitalRiverElementOptions {\n classes: {\n base: string;\n };\n compliance: {\n entity: string;\n };\n}\n\ninterface DigitalRiverAuthenticateSourceRequest {\n sessionId: string;\n sourceId: string;\n sourceClientSecret: string;\n}\n\nexport interface DigitalRiverAdditionalProviderData {\n source_id: string;\n source_client_secret: string;\n}\n\nexport interface DigitalRiverAuthenticateSourceResponse {\n status: AuthenticationSourceStatus;\n}\n\nexport enum AuthenticationSourceStatus {\n complete = 'complete',\n authentication_not_required = 'authentication_not_required',\n failed = 'failed',\n}\n\nexport interface DigitalRiverJSOptions {\n /**\n * The locale used to localize the various display and error strings within DigitalRiver.js\n * Currently supported locales:\n * ar-EG, cs-CZ, da-DK, de-AT, de-CH, de-DE, el-GR, en-AU, en-BE, en-CA, en-CH, en-DK, en-FI, en-GB, en-IE, en-IN,\n * en-MY, en-NL, en-NO, en-NZ, en-PR, en-SE, en-SG, en-US, en-ZA, es-AR, es-CL, es-CO, es-EC, es-ES, es-MX, es-PE,\n * es-VE, et-EE, fi-FI, fr-BE, fr-CA, fr-CH, fr-FR, hu-HU, it-CH, it-IT, iw-IL, ja-JP, ko-KR, lt-LT, lv-LV, nl-BE,\n * nl-NL, no-NO, pl-PL, pt-BR, pt-PT, ro-RO, ru-RU, sk-SK, sl-SI, sr-YU, sv-SE, th-TH, tr-TR, zh-CN, zh-HK, zh-TW\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/digitalriver.js/reference/digital-river-publishable-api-key\n */\n locale?: string;\n}\n\n/**\n * Create a Configuration object for Drop-in\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#step-5-configure-hydrate\n */\nexport interface DigitalRiverDropInConfiguration {\n /**\n * The payment session identifier returned by Digital River.\n */\n sessionId: string;\n\n /**\n * you can specify options to trigger different features or functionality\n */\n options?: OptionsResponse;\n billingAddress: {\n firstName: string;\n lastName: string;\n email: string;\n phoneNumber: string;\n address: {\n line1: string;\n line2?: string;\n city?: string;\n state?: string;\n postalCode: string;\n country: string;\n };\n };\n\n /**\n * Additional configuration details for configuration structure (classes, styles etc..)\n */\n paymentMethodConfiguration?: BaseElementOptions;\n\n /**\n * The function called when the shopper has authorized payment and a payment source has been successfully created.\n */\n onSuccess?(data: OnSuccessResponse): void;\n\n /**\n * The function called when the shopper cancels the payment process before authorizing payment.\n */\n onCancel?(error: OnCancelOrErrorResponse): void;\n\n /**\n * The function called when an error has occurred.\n */\n onError?(error: OnCancelOrErrorResponse): void;\n\n /**\n * The function called when Drop-in is ready for user interaction.\n */\n onReady?(data: OnReadyResponse): void;\n}\n\nexport interface OnCancelOrErrorResponse {\n /**\n * If an error occurs, Drop-in emits an event that identifies the payment method associated with the error.\n * Instruct your customer to provide a new method of payment.\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#onerror\n * Or When your customer chooses to pay with a specific payment method and decides to cancel during the redirect phase,\n * Drop-in emits an event that identifies the cancelled payment method.\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#oncancel\n */\n errors: ErrorData[];\n}\n\nexport interface ErrorData {\n code: string;\n message: string;\n}\n\nexport interface OnReadyResponse {\n /**\n * When ready, Drop-in will emit an event that contains a \"paymentMethodTypes\" array of the available payment methods.\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#onready\n */\n paymentMethodTypes: string[];\n}\n\n/**\n * When creating your Drop-in instance, you can specify options to trigger different features or functionality.\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#drop-in-options\n */\nexport interface OptionsResponse {\n /**\n * Use this option if you are using Drop-in within a standard checkout flow. Example Value: \"checkout\"\n */\n flow?: string;\n\n /**\n * When enabled, presents the customer with an option to save their payment details for future use within Drop-in.\n * Enabling this feature will show the appropriate check boxes and localized disclosure statements and facilitate\n * any necessary Strong Customer Authentication.\n * If disabled, Drop-in will not present the customer with an option to save their payment details.\n */\n showSavePaymentAgreement?: boolean;\n\n /**\n * Will show a localized compliance link section as part of Drop-in. This is an important piece for accessing the Digital River business model.\n */\n showComplianceSection?: boolean;\n\n /**\n * Use this option to customize the text of the Drop-in button.\n */\n button?: ButtonResponse;\n\n /**\n * Use this option to specify the future use of a source.\n */\n usage?: string;\n\n /**\n * Use this option to show the required terms of sale disclosure. These localized terms automatically update if recurring products are purchased.\n */\n showTermsOfSaleDisclosure?: boolean;\n\n /**\n * Additional configuration details for drop-in.\n */\n paymentMethodConfiguration?: BaseElementOptions;\n}\n\nexport interface ButtonResponse {\n /**\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#customizing-the-text-of-the-drop-in-button\n * The text of the Drop-in button is customizable. You can either display pre-configured text or you can specify a unique text\n * Examples type: \"payNow\" || type: \"buyNow\" || type: \"completeOrder\" || type: \"submitOrder\"\n */\n type: string;\n}\n\nexport interface OnSuccessResponse {\n /**\n * Event that gets triggered after the customer's payment has provided with the necessary details for payment\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#onsuccess\n */\n source: {\n id: string;\n reusable: boolean;\n browserInfo?: {\n browserIp?: string;\n };\n owner?: {\n email: string;\n firstName: string;\n lastName: string;\n phoneNumber: string;\n address: {\n city: string;\n country: string;\n line1: string;\n postalCode: string;\n state: string;\n };\n };\n };\n\n /**\n * Indicates whether the source has been enabled for future use.\n * Important: If this value is true, it does not mean the customer can use this source multiple times.\n * This flag identifies whether the necessary downstream actions have been triggered to prepare the source for storage.\n * You must attach the source to your customer for it to be truly reusable.\n */\n readyForStorage: boolean;\n}\n\nexport interface DigitalRiverDropIn {\n /**\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#step-7-place-drop-in-on-your-checkout-or-customer-page\n * example \"drop-in\"\n */\n mount(dropInId: string): void;\n}\n\ninterface DigitalRiverElement {\n /**\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#step-7-place-drop-in-on-your-checkout-or-customer-page\n * example \"drop-in\"\n */\n mount(dropInId: string): void;\n}\n\ninterface BaseElementOptions {\n /**\n * Set custom class names on the container DOM element when the Digital River element is in a particular state.\n */\n classes?: DigitalRiverElementClasses;\n /**\n * Use disabledPaymentMethods to disable specific payment methods.\n */\n disabledPaymentMethods?: string[];\n}\n\n/**\n * Custom classes\n * You can specify custom classes as part of a Class object included within the Options object when you create or\n * update an element. If you do not provide custom classes, the system uses the default options.\n * https://docs.digitalriver.com/digital-river-api/payment-integrations-1/digitalriver.js/reference/elements#custom-classes\n */\nexport interface DigitalRiverElementClasses {\n /**\n * The Element is in its base state. The user either has not entered anything into the input field or is currently typing.\n */\n base?: string;\n\n /**\n * The Element is in its complete state. The user has input value, and it meets the basic validation requirements of that field.\n */\n complete?: string;\n\n /**\n * The Element is empty. The Element once had value but is now empty.\n */\n empty?: string;\n\n /**\n * The Element has focus.\n */\n focus?: string;\n\n /**\n * The Element has value, but it does not meet the basic validation requirements of the field.\n */\n invalid?: string;\n\n /**\n * The element has a value that has been automatically filled by the browser.\n */\n webkitAutofill?: string;\n}\n\nexport interface DigitalRiverInitializeToken {\n sessionId: string;\n checkoutData: DigitalRiverCheckoutData;\n}\n\ninterface DigitalRiverCheckoutData {\n checkoutId: string;\n sellingEntity: string;\n}\n","import { StandardError } from '../../../common/error/errors';\n\nconst defaultMessage =\n 'There was an error while processing your payment. Please try again or contact us.';\n\nexport default class DigitalRiverError extends StandardError {\n constructor(type: string, name: string, message?: string) {\n super(message || defaultMessage);\n\n this.type = type;\n this.name = name;\n }\n}\n","import { some } from 'lodash';\n\nimport { BillingAddressActionCreator } from '../../../billing';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { StoreCreditActionCreator } from '../../../store-credit';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport { HostedInstrument, isVaultedInstrument } from '../../index';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport DigitalRiverJS, {\n AuthenticationSourceStatus,\n DigitalRiverAdditionalProviderData,\n DigitalRiverAuthenticateSourceResponse,\n DigitalRiverDropIn,\n DigitalRiverElementOptions,\n DigitalRiverInitializeToken,\n OnCancelOrErrorResponse,\n OnReadyResponse,\n OnSuccessResponse,\n} from './digitalriver';\nimport DigitalRiverError from './digitalriver-error';\nimport DigitalRiverPaymentInitializeOptions from './digitalriver-payment-initialize-options';\nimport DigitalRiverScriptLoader from './digitalriver-script-loader';\n\nexport default class DigitalRiverPaymentStrategy implements PaymentStrategy {\n private _digitalRiverJS?: DigitalRiverJS;\n private _digitalRiverDropComponent?: DigitalRiverDropIn;\n private _submitFormEvent?: () => void;\n private _loadSuccessResponse?: OnSuccessResponse;\n private _digitalRiverCheckoutData?: DigitalRiverInitializeToken;\n private _unsubscribe?: () => void;\n private _digitalRiverInitializeOptions?: DigitalRiverPaymentInitializeOptions;\n\n constructor(\n private _store: CheckoutStore,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _storeCreditActionCreator: StoreCreditActionCreator,\n private _digitalRiverScriptLoader: DigitalRiverScriptLoader,\n private _billingAddressActionCreator: BillingAddressActionCreator,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n this._digitalRiverInitializeOptions = options.digitalriver;\n\n const paymentMethod = this._store\n .getState()\n .paymentMethods.getPaymentMethodOrThrow(options.methodId);\n const { publicKey, paymentLanguage: locale } = paymentMethod.initializationData;\n const { containerId } = this._getDigitalRiverInitializeOptions();\n\n this._digitalRiverJS = await this._digitalRiverScriptLoader.load(publicKey, locale);\n\n this._unsubscribe = await this._store.subscribe(\n async (state) => {\n if (\n state.paymentStrategies.isInitialized({\n methodId: options.methodId,\n gatewayId: options.gatewayId,\n })\n ) {\n const container = document.getElementById(containerId);\n\n if (container) {\n container.innerHTML = '';\n\n this._digitalRiverJS = await this._digitalRiverScriptLoader.load(\n publicKey,\n locale,\n );\n }\n\n await this._loadWidget(options);\n }\n },\n (state) => {\n const checkout = state.checkout.getCheckout();\n\n return checkout && checkout.outstandingBalance;\n },\n (state) => {\n const checkout = state.checkout.getCheckout();\n\n return checkout && checkout.coupons;\n },\n );\n\n return this._loadWidget(options);\n }\n\n deinitialize(): Promise {\n if (this._unsubscribe) {\n this._unsubscribe();\n }\n\n const { containerId } = this._getDigitalRiverInitializeOptions();\n const container = document.getElementById(containerId);\n\n if (container) {\n container.innerHTML = '';\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n orderRequest: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment || !payment.paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const { paymentData, methodId } = payment;\n const { shouldSetAsDefaultInstrument = false } = paymentData as HostedInstrument;\n const { isStoreCreditApplied: useStoreCredit } = this._store\n .getState()\n .checkout.getCheckoutOrThrow();\n\n if (useStoreCredit !== undefined) {\n await this._store.dispatch(\n this._storeCreditActionCreator.applyStoreCredit(useStoreCredit),\n );\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n if (!this._digitalRiverCheckoutData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (isVaultedInstrument(paymentData)) {\n try {\n return await this._submitVaultedInstrument(\n methodId,\n paymentData.instrumentId,\n this._digitalRiverCheckoutData.checkoutData.checkoutId,\n shouldSetAsDefaultInstrument,\n false,\n );\n } catch (error) {\n if (!this._isAuthenticateSourceAction(error)) {\n throw error;\n }\n\n const confirm = await this._authenticateSource(error.body.provider_data);\n\n return await this._submitVaultedInstrument(\n methodId,\n paymentData.instrumentId,\n this._digitalRiverCheckoutData.checkoutData.checkoutId,\n shouldSetAsDefaultInstrument,\n confirm,\n );\n }\n } else {\n if (!this._loadSuccessResponse) {\n throw new PaymentArgumentInvalidError(['this._loadSuccessResponse']);\n }\n\n const paymentPayload = {\n methodId: payment.methodId,\n paymentData: {\n formattedPayload: {\n credit_card_token: {\n token: JSON.stringify({\n checkoutId: this._digitalRiverCheckoutData.checkoutData.checkoutId,\n source: this._loadSuccessResponse,\n sessionId: this._digitalRiverCheckoutData.sessionId,\n }),\n },\n vault_payment_instrument: this._loadSuccessResponse.readyForStorage,\n set_as_default_stored_instrument: false,\n },\n },\n };\n\n return this._store.dispatch(this._paymentActionCreator.submitPayment(paymentPayload));\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private _getDigitalRiverJs(): DigitalRiverJS {\n if (!this._digitalRiverJS) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._digitalRiverJS;\n }\n\n private _getErrorMessage(error: OnCancelOrErrorResponse): string {\n const { errors } = error;\n\n return errors.map((e) => `code: ${e.code} message: ${e.message}`).join('\\n');\n }\n\n private async _onSuccessResponse(data?: OnSuccessResponse): Promise {\n const error = new InvalidArgumentError(\n 'Unable to initialize payment because success argument is not provided.',\n );\n\n if (data && this._submitFormEvent) {\n const { browserInfo, owner } = data.source;\n\n this._loadSuccessResponse = browserInfo\n ? {\n source: {\n id: data.source.id,\n reusable: data.source.reusable,\n ...browserInfo,\n },\n readyForStorage: data.readyForStorage,\n }\n : {\n source: {\n id: data.source.id,\n reusable: data.source.reusable,\n },\n readyForStorage: data.readyForStorage,\n };\n\n if (owner) {\n const billingAddressPayPal = {\n firstName: owner.firstName,\n lastName: owner.lastName,\n city: owner.address.city,\n company: '',\n address1: owner.address.line1,\n address2: '',\n postalCode: owner.address.postalCode,\n countryCode: owner.address.country,\n phone: owner.phoneNumber,\n stateOrProvince: owner.address.state,\n stateOrProvinceCode: owner.address.country,\n customFields: [],\n email: owner.email || owner.email,\n };\n\n this._loadSuccessResponse.source.owner = data.source.owner;\n await this._store.dispatch(\n this._billingAddressActionCreator.updateAddress(billingAddressPayPal),\n );\n }\n\n return this._submitFormEvent();\n }\n\n return this._getDigitalRiverInitializeOptions().onError?.(error);\n }\n\n private _onReadyResponse(data?: OnReadyResponse): void {\n if (data) {\n this._getDigitalRiverInitializeOptions().onRenderButton?.();\n }\n }\n\n private _getDigitalRiverInitializeOptions(): DigitalRiverPaymentInitializeOptions {\n if (!this._digitalRiverInitializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._digitalRiverInitializeOptions;\n }\n\n private async _loadWidget(\n options: PaymentInitializeOptions,\n ): Promise {\n try {\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(options.methodId),\n );\n const billing = state.billingAddress.getBillingAddressOrThrow();\n const customer = state.customer.getCustomerOrThrow();\n const { features } = state.config.getStoreConfigOrThrow().checkoutSettings;\n const { paymentMethodConfiguration } =\n this._getDigitalRiverInitializeOptions().configuration;\n const { containerId, configuration } = this._getDigitalRiverInitializeOptions();\n const { clientToken } = state.paymentMethods.getPaymentMethodOrThrow(options.methodId);\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._digitalRiverCheckoutData = JSON.parse(clientToken);\n\n if (!this._digitalRiverCheckoutData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._mountComplianceSection(this._digitalRiverCheckoutData.checkoutData.sellingEntity);\n\n this._submitFormEvent = this._getDigitalRiverInitializeOptions().onSubmitForm;\n\n const disabledPaymentMethods = features['PROJECT-4802.digital_river_paypal_support']\n ? []\n : ['payPal'];\n\n const digitalRiverConfiguration = {\n sessionId: this._digitalRiverCheckoutData.sessionId,\n options: {\n ...configuration,\n showSavePaymentAgreement:\n Boolean(customer.email) && configuration.showSavePaymentAgreement,\n },\n billingAddress: {\n firstName: billing.firstName,\n lastName: billing.lastName,\n email: billing.email || customer.email,\n phoneNumber: billing.phone,\n address: {\n line1: billing.address1,\n line2: billing.address2,\n city: billing.city,\n state: billing.stateOrProvinceCode,\n postalCode: billing.postalCode,\n country: billing.countryCode,\n },\n },\n paymentMethodConfiguration: {\n ...paymentMethodConfiguration,\n disabledPaymentMethods,\n },\n onSuccess: (data?: OnSuccessResponse) => {\n this._onSuccessResponse(data);\n },\n onReady: (data?: OnReadyResponse) => {\n this._onReadyResponse(data);\n },\n onError: (error: OnCancelOrErrorResponse) => {\n const descriptiveError = new Error(this._getErrorMessage(error));\n\n this._getDigitalRiverInitializeOptions().onError?.(descriptiveError);\n },\n };\n\n this._digitalRiverDropComponent = await this._getDigitalRiverJs().createDropin(\n digitalRiverConfiguration,\n );\n this._digitalRiverDropComponent.mount(containerId);\n\n return state;\n } catch {\n throw new DigitalRiverError(\n 'payment.digitalriver_checkout_error',\n 'digitalRiverCheckoutError',\n );\n }\n }\n\n private _isAuthenticateSourceAction(error: unknown): boolean {\n return !(\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'additional_action_required' })\n );\n }\n\n private async _authenticateSource(\n additionalAction: DigitalRiverAdditionalProviderData,\n ): Promise {\n if (!this._digitalRiverCheckoutData) {\n throw new InvalidArgumentError(\n 'Unable to proceed because payload payment argument is not provided.',\n );\n }\n\n const authenticateSourceResponse: DigitalRiverAuthenticateSourceResponse =\n await this._getDigitalRiverJs().authenticateSource({\n sessionId: this._digitalRiverCheckoutData.sessionId,\n sourceId: additionalAction.source_id,\n sourceClientSecret: additionalAction.source_client_secret,\n });\n\n if (authenticateSourceResponse.status === AuthenticationSourceStatus.failed) {\n throw new Error('Source authentication failed, please try again');\n }\n\n return (\n authenticateSourceResponse.status === AuthenticationSourceStatus.complete ||\n authenticateSourceResponse.status ===\n AuthenticationSourceStatus.authentication_not_required\n );\n }\n\n private async _submitVaultedInstrument(\n methodId: string,\n instrumentId: string,\n checkoutId: string,\n shouldSetAsDefaultInstrument: boolean,\n confirm: boolean,\n ): Promise {\n const paymentPayload = {\n methodId,\n paymentData: {\n formattedPayload: {\n bigpay_token: {\n token: instrumentId,\n },\n credit_card_token: {\n token: JSON.stringify({\n checkoutId,\n }),\n },\n confirm,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument || null,\n },\n },\n };\n\n return this._store.dispatch(this._paymentActionCreator.submitPayment(paymentPayload));\n }\n\n private _mountComplianceSection(sellingEntity: string) {\n const complianceDiv = document.getElementById('compliance');\n\n const complianceOptions: DigitalRiverElementOptions = {\n classes: {\n base: 'DRElement',\n },\n compliance: {\n entity: sellingEntity,\n },\n };\n\n if (complianceDiv) {\n complianceDiv.innerHTML = '';\n\n const complianceElement = this._getDigitalRiverJs().createElement(\n 'compliance',\n complianceOptions,\n );\n\n complianceElement.mount('compliance');\n } else {\n const drfooter = document.createElement('div');\n\n drfooter.setAttribute('id', 'compliance');\n drfooter.style.cssText = 'min-height: 45px;';\n drfooter.classList.add('layout');\n document.body.appendChild(drfooter);\n\n const complianceElement = this._getDigitalRiverJs().createElement(\n 'compliance',\n complianceOptions,\n );\n\n complianceElement.mount('compliance');\n }\n }\n}\n","import { ScriptLoader, StylesheetLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport DigitalRiverJS, { DigitalRiverWindow } from './digitalriver';\n\nexport default class DigitalRiverScriptLoader {\n constructor(\n private _scriptLoader: ScriptLoader,\n private _stylesheetLoader: StylesheetLoader,\n private _window: DigitalRiverWindow = window,\n ) {}\n\n async load(publicKey: string, locale: string): Promise {\n await Promise.all([\n this._stylesheetLoader.loadStylesheet(\n `https://js.digitalriverws.com/v1/css/DigitalRiver.css`,\n ),\n this._scriptLoader.loadScript(`https://js.digitalriverws.com/v1/DigitalRiver.js`),\n ]);\n\n if (!this._window.DigitalRiver) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return Promise.resolve(new this._window.DigitalRiver(publicKey, { locale }));\n }\n}\n","import BrowserInfo from './browser-info';\n\nexport default function getBrowserInfo(): BrowserInfo {\n return {\n color_depth: screen.colorDepth || 24,\n java_enabled: typeof navigator.javaEnabled === 'function' ? navigator.javaEnabled() : false,\n language: navigator.language || (navigator as any).userLanguage,\n screen_height: screen.height,\n screen_width: screen.width,\n time_zone_offset: new Date().getTimezoneOffset().toString(),\n };\n}\n","import { noop } from 'lodash';\n\nimport { CancellablePromise } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { getBrowserInfo } from '../../../common/browser-info';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport { PaymentStrategyType } from '../../index';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategyActionCreator from '../../payment-strategy-action-creator';\nimport {\n BraintreeGooglePayThreeDSecure,\n BraintreeSDKCreator,\n BraintreeVerifyPayload,\n} from '../braintree';\nimport PaymentStrategy from '../payment-strategy';\n\nimport {\n GooglePaymentData,\n GooglePayProviderProcessor,\n GooglePayVerifyPayload,\n PaymentMethodData,\n} from './googlepay';\nimport GooglePayPaymentInitializeOptions from './googlepay-initialize-options';\nimport GooglePayPaymentProcessor from './googlepay-payment-processor';\n\nexport default class GooglePayPaymentStrategy implements PaymentStrategy {\n private _googlePayOptions?: GooglePayPaymentInitializeOptions;\n private _walletButton?: HTMLElement;\n private _paymentMethod?: PaymentMethod;\n private _is3dsEnabled?: boolean;\n private _buttonClickEventHandler?: (event: Event) => Promise;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentStrategyActionCreator: PaymentStrategyActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _orderActionCreator: OrderActionCreator,\n private _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n private _googlePayProviderProcessor?: GooglePayProviderProcessor,\n private _braintreeSDKCreator?: BraintreeSDKCreator,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const { methodId } = options;\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n\n this._paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n this._is3dsEnabled =\n state.paymentMethods.getPaymentMethodOrThrow(\n methodId,\n ).initializationData.isThreeDSecureEnabled;\n\n this._googlePayOptions = this._getGooglePayOptions(options);\n\n this._buttonClickEventHandler = this._handleButtonClickedEvent(methodId);\n\n if (this._paymentMethod.clientToken) {\n this._braintreeSDKCreator?.initialize(this._paymentMethod.clientToken);\n }\n\n await this._googlePayPaymentProcessor.initialize(methodId);\n\n if (!this._googlePayOptions.walletButton) {\n throw new InvalidArgumentError('walletButton argument is missing');\n }\n\n const walletButton = document.getElementById(this._googlePayOptions.walletButton);\n\n if (!walletButton) {\n throw new InvalidArgumentError(\n 'Unable to create wallet, walletButton ID could not be found',\n );\n }\n\n this._walletButton = walletButton;\n this._walletButton.addEventListener('click', this._buttonClickEventHandler);\n\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n if (this._walletButton && this._buttonClickEventHandler) {\n this._walletButton.removeEventListener('click', this._buttonClickEventHandler);\n }\n\n this._buttonClickEventHandler = undefined;\n this._walletButton = undefined;\n\n return this._googlePayPaymentProcessor.deinitialize().then(() => this._store.getState());\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n if (!this._googlePayOptions) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.googlepay\" argument is not provided.',\n );\n }\n\n if (!payload.payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId } = payload.payment;\n\n if (this._paymentMethod?.initializationData.nonce !== '') {\n const state = this._store.getState();\n\n this._paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n }\n\n let payment = await this._getPayment(methodId);\n\n if (!payment.paymentData.nonce || !payment.paymentData.cardInformation) {\n const { onError, onPaymentSelect } = this._googlePayOptions;\n\n await this._displayWallet(methodId, onPaymentSelect, onError);\n payment = await this._getPayment(methodId, true);\n }\n\n if (!payment.paymentData.nonce) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n try {\n const state = await this._store.dispatch(\n this._orderActionCreator.submitOrder(\n { useStoreCredit: payload.useStoreCredit },\n options,\n ),\n );\n let verification;\n\n if (this._is3dsEnabled) {\n const {\n order: { getOrderOrThrow },\n } = state;\n\n verification = await this._verifyCard(\n methodId,\n getOrderOrThrow().orderAmount,\n payment,\n );\n }\n\n const newPayment = {\n ...payment,\n paymentData: {\n ...payment.paymentData,\n nonce: verification?.nonce || payment.paymentData.nonce,\n },\n };\n\n return await this._store.dispatch(this._paymentActionCreator.submitPayment(newPayment));\n } catch (error) {\n return this._processAdditionalAction(error);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private _processAdditionalAction(error: unknown): Promise {\n if (!this._googlePayProviderProcessor) {\n return Promise.reject(error);\n }\n\n return this._googlePayProviderProcessor.processAdditionalAction(error);\n }\n\n private async _verifyCard(\n methodId: string,\n amount: number,\n payment: PaymentMethodData,\n ): Promise {\n if (methodId === PaymentStrategyType.BRAINTREE_GOOGLE_PAY) {\n const { nonce } = payment.paymentData;\n const threeDSecure = await this._braintreeSDKCreator?.get3DS();\n\n if (!nonce || !threeDSecure) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._braintreePresent3DSChallenge(threeDSecure, amount, nonce);\n }\n }\n\n private _braintreePresent3DSChallenge(\n threeDSecure: BraintreeGooglePayThreeDSecure,\n amount: number,\n nonce: string,\n ): Promise {\n const verification = new CancellablePromise(\n threeDSecure.verifyCard({\n amount,\n nonce,\n onLookupComplete: (_data, next) => {\n next();\n },\n }),\n );\n\n return verification.promise;\n }\n\n /* tslint:disable:cyclomatic-complexity */\n private _getGooglePayOptions(\n options: PaymentInitializeOptions,\n ): GooglePayPaymentInitializeOptions {\n if (\n options.methodId === PaymentStrategyType.ADYENV2_GOOGLEPAY &&\n options.googlepayadyenv2\n ) {\n if (!this._googlePayProviderProcessor) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._googlePayProviderProcessor.initialize(options);\n\n return options.googlepayadyenv2;\n }\n\n if (\n options.methodId === PaymentStrategyType.ADYENV3_GOOGLEPAY &&\n options.googlepayadyenv3\n ) {\n if (!this._googlePayProviderProcessor) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._googlePayProviderProcessor.initialize(options);\n\n return options.googlepayadyenv3;\n }\n\n if (\n options.methodId === PaymentStrategyType.AUTHORIZENET_GOOGLE_PAY &&\n options.googlepayauthorizenet\n ) {\n return options.googlepayauthorizenet;\n }\n\n if (options.methodId === PaymentStrategyType.BNZ_GOOGLEPAY && options.googlepaybnz) {\n return options.googlepaybnz;\n }\n\n if (\n options.methodId === PaymentStrategyType.CHECKOUTCOM_GOOGLE_PAY &&\n options.googlepaycheckoutcom\n ) {\n return options.googlepaycheckoutcom;\n }\n\n if (\n options.methodId === PaymentStrategyType.CYBERSOURCEV2_GOOGLE_PAY &&\n options.googlepaycybersourcev2\n ) {\n return options.googlepaycybersourcev2;\n }\n\n if (\n options.methodId === PaymentStrategyType.ORBITAL_GOOGLE_PAY &&\n options.googlepayorbital\n ) {\n return options.googlepayorbital;\n }\n\n if (\n options.methodId === PaymentStrategyType.BRAINTREE_GOOGLE_PAY &&\n options.googlepaybraintree\n ) {\n return options.googlepaybraintree;\n }\n\n if (options.methodId === PaymentStrategyType.STRIPE_GOOGLE_PAY && options.googlepaystripe) {\n return options.googlepaystripe;\n }\n\n if (\n options.methodId === PaymentStrategyType.STRIPE_UPE_GOOGLE_PAY &&\n options.googlepaystripeupe\n ) {\n return options.googlepaystripeupe;\n }\n\n if (\n options.methodId === PaymentStrategyType.WORLDPAYACCESS_GOOGLE_PAY &&\n options.googlepayworldpayaccess\n ) {\n return options.googlepayworldpayaccess;\n }\n\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.googlepay\" argument is not provided.',\n );\n }\n /* tslint:enable:cyclomatic-complexity */\n\n private async _getPayment(\n methodId: string,\n requireRenewNonce = false,\n ): Promise {\n if (!methodId || !this._paymentMethod) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const card_information = this._paymentMethod.initializationData.card_information;\n let nonce = this._paymentMethod.initializationData.nonce;\n\n if (nonce) {\n this._paymentMethod = { ...this._paymentMethod, initializationData: { nonce: '' } };\n }\n\n if (requireRenewNonce) {\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n\n this._paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n nonce = this._paymentMethod.initializationData.nonce;\n }\n\n return {\n methodId,\n paymentData: {\n method: methodId,\n cardInformation: card_information,\n nonce: await this._encodeNonce(methodId, nonce),\n },\n };\n }\n\n private async _encodeNonce(methodId: string, nonce: string) {\n if (methodId === PaymentStrategyType.ADYENV2_GOOGLEPAY) {\n return JSON.stringify({\n type: this._paymentMethod?.method,\n googlePayToken: nonce,\n browser_info: getBrowserInfo(),\n });\n }\n\n if (methodId === PaymentStrategyType.ADYENV3_GOOGLEPAY) {\n return JSON.stringify({\n type: this._paymentMethod?.method,\n googlePayToken: nonce,\n browser_info: getBrowserInfo(),\n });\n }\n\n return nonce;\n }\n\n private async _paymentInstrumentSelected(paymentData: GooglePaymentData, methodId: string) {\n if (!methodId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n // TODO: Revisit how we deal with GooglePaymentData after receiving it from Google\n await this._googlePayPaymentProcessor.handleSuccess(paymentData);\n\n const state = this._store.getState();\n\n this._paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n return Promise.all([\n this._store.dispatch(this._checkoutActionCreator.loadCurrentCheckout()),\n this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId)),\n ]);\n }\n\n private _handleButtonClickedEvent(\n methodId: string,\n ): (event?: Event) => Promise {\n return (event?: Event) => {\n event?.preventDefault();\n\n const cart = this._store.getState().cart.getCartOrThrow();\n\n const payloadToUpdate = {\n transactionInfo: {\n currencyCode: cart.currency.code,\n totalPrice: String(cart.cartAmount),\n },\n };\n\n this._googlePayPaymentProcessor.updatePaymentDataRequest(payloadToUpdate);\n\n if (!methodId || !this._googlePayOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { onError, onPaymentSelect } = this._googlePayOptions;\n\n return this._store.dispatch(\n this._paymentStrategyActionCreator.widgetInteraction(\n async () => this._displayWallet(methodId, onPaymentSelect, onError),\n { methodId },\n ),\n { queueId: 'widgetInteraction' },\n );\n };\n }\n\n private async _displayWallet(\n methodId: string,\n onPaymentSelect = noop,\n onError = noop,\n ): Promise {\n try {\n const paymentData = await this._googlePayPaymentProcessor.displayWallet();\n\n await this._paymentInstrumentSelected(paymentData, methodId);\n\n return onPaymentSelect();\n } catch (error) {\n if (error.statusCode === 'CANCELED') {\n throw new Error('CANCELED');\n }\n\n onError(error);\n }\n }\n}\n","import { some } from 'lodash';\n\nimport { Payment, PaymentActionCreator, PaymentInitializeOptions } from '../..';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { PaymentMethodCancelledError } from '../../errors';\nimport {\n AdyenAction,\n AdyenAdditionalAction,\n AdyenAdditionalActionState,\n AdyenClient,\n AdyenError,\n AdyenV2ScriptLoader,\n} from '../adyenv2';\n\nimport { GooglePayProviderProcessor } from './googlepay';\n\nexport default class GooglePayAdyenV2PaymentProcessor implements GooglePayProviderProcessor {\n private _adyenClient?: AdyenClient;\n\n constructor(\n private _store: CheckoutStore,\n private _paymentActionCreator: PaymentActionCreator,\n private _scriptLoader: AdyenV2ScriptLoader,\n ) {}\n\n async initialize(options: PaymentInitializeOptions) {\n const state = this._store.getState();\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(options.methodId);\n const storeConfig = state.config.getStoreConfig();\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const clientSideAuthentication = {\n key: '',\n value: '',\n };\n\n if (paymentMethod.initializationData.originKey) {\n clientSideAuthentication.key = 'originKey';\n clientSideAuthentication.value = paymentMethod.initializationData.originKey;\n } else {\n clientSideAuthentication.key = 'clientKey';\n clientSideAuthentication.value = paymentMethod.initializationData.clientKey;\n }\n\n this._adyenClient = await this._scriptLoader.load({\n environment: paymentMethod.config.testMode ? 'test' : 'live',\n locale: storeConfig.storeProfile.storeLanguage,\n [clientSideAuthentication.key]: clientSideAuthentication.value,\n paymentMethodsResponse: paymentMethod.initializationData.paymentMethodsResponse,\n });\n }\n\n async processAdditionalAction(error: unknown): Promise {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'additional_action_required' })\n ) {\n return Promise.reject(error);\n }\n\n const payment = await this._handleAction(error.body.provider_data);\n\n try {\n return await this._store.dispatch(this._paymentActionCreator.submitPayment(payment));\n } catch (error) {\n return this.processAdditionalAction(error);\n }\n }\n\n private _handleAction(additionalAction: AdyenAdditionalAction): Promise {\n return new Promise((resolve, reject) => {\n const adyenAction: AdyenAction = JSON.parse(additionalAction.action);\n\n const additionalActionComponent = this._getAdyenClient().createFromAction(adyenAction, {\n onAdditionalDetails: (additionalActionState: AdyenAdditionalActionState) => {\n const paymentPayload = {\n methodId: adyenAction.paymentMethodType,\n paymentData: {\n nonce: JSON.stringify(additionalActionState.data),\n },\n };\n\n resolve(paymentPayload);\n },\n size: '05',\n onError: (error: AdyenError) => reject(error),\n });\n\n additionalActionComponent.mount('body');\n\n reject(new PaymentMethodCancelledError());\n });\n }\n\n private _getAdyenClient(): AdyenClient {\n if (!this._adyenClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._adyenClient;\n }\n}\n","import { some } from 'lodash';\n\nimport { Payment, PaymentActionCreator, PaymentInitializeOptions } from '../..';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { PaymentMethodCancelledError } from '../../errors';\nimport {\n AdyenAction,\n AdyenAdditionalAction,\n AdyenAdditionalActionState,\n AdyenClient,\n AdyenError,\n AdyenV3ScriptLoader,\n} from '../adyenv3';\n\nimport { GooglePayProviderProcessor } from './googlepay';\n\nexport default class GooglePayAdyenV3PaymentProcessor implements GooglePayProviderProcessor {\n private _adyenClient?: AdyenClient;\n\n constructor(\n private _store: CheckoutStore,\n private _paymentActionCreator: PaymentActionCreator,\n private _scriptLoader: AdyenV3ScriptLoader,\n ) {}\n\n async initialize(options: PaymentInitializeOptions) {\n const state = this._store.getState();\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(options.methodId);\n const storeConfig = state.config.getStoreConfig();\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n this._adyenClient = await this._scriptLoader.load({\n environment: paymentMethod.config.testMode ? 'test' : 'live',\n locale: storeConfig.storeProfile.storeLanguage,\n clientKey: paymentMethod.initializationData.clientKey,\n paymentMethodsResponse: paymentMethod.initializationData.paymentMethodsResponse,\n });\n }\n\n async processAdditionalAction(error: unknown): Promise {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'additional_action_required' })\n ) {\n return Promise.reject(error);\n }\n\n const payment = await this._handleAction(error.body.provider_data);\n\n try {\n return await this._store.dispatch(this._paymentActionCreator.submitPayment(payment));\n } catch (error) {\n return this.processAdditionalAction(error);\n }\n }\n\n private _handleAction(additionalAction: AdyenAdditionalAction): Promise {\n return new Promise((resolve, reject) => {\n const adyenAction: AdyenAction = JSON.parse(additionalAction.action);\n\n const additionalActionComponent = this._getAdyenClient().createFromAction(adyenAction, {\n onAdditionalDetails: (additionalActionState: AdyenAdditionalActionState) => {\n const paymentPayload = {\n methodId: adyenAction.paymentMethodType,\n paymentData: {\n nonce: JSON.stringify(additionalActionState.data),\n },\n };\n\n resolve(paymentPayload);\n },\n challengeWindowSize: '05',\n onError: (error: AdyenError) => reject(error),\n });\n\n additionalActionComponent.mount('body');\n\n reject(new PaymentMethodCancelledError());\n });\n }\n\n private _getAdyenClient(): AdyenClient {\n if (!this._adyenClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._adyenClient;\n }\n}\n","import { some } from 'lodash';\n\nimport { InternalCheckoutSelectors } from '../../../checkout';\nimport { RequestError } from '../../../common/error/errors';\nimport { PaymentInitializeOptions } from '../../payment-request-options';\n\nimport { GooglePayProviderProcessor } from './googlepay';\n\nexport default class GooglePayCheckoutcomPaymentProcessor implements GooglePayProviderProcessor {\n initialize(_options: PaymentInitializeOptions): Promise {\n return Promise.resolve();\n }\n\n async processAdditionalAction(error: unknown): Promise {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return Promise.reject(error);\n }\n\n const redirectUrl = error.body.three_ds_result.acs_url;\n\n return this._performRedirect(redirectUrl);\n }\n\n private _performRedirect(redirectUrl: string): Promise {\n return new Promise(() => {\n window.location.assign(redirectUrl);\n });\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { PaymentExecuteError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { PaymentStrategy } from '..';\nimport { PaymentActionCreator } from '../..';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentRequestOptions } from '../../payment-request-options';\n\nexport default class HummPaymentStrategy implements PaymentStrategy {\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _formPoster: FormPoster,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n ) {}\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n\n if (!payment?.methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(payment.methodId, options),\n );\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(payment.methodId);\n\n if (!paymentMethod.initializationData?.processable) {\n throw new PaymentExecuteError(\n 'payment.humm_not_processable_error',\n 'hummNotProcessableError',\n );\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({ methodId: payment.methodId }),\n );\n } catch (error) {\n if (this._isOffsiteRedirectResponse(error)) {\n return this._handleOffsiteRedirectResponse(error);\n }\n\n return Promise.reject(error);\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n initialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n private _handleOffsiteRedirectResponse(response: OffsiteRedirectResponse): Promise {\n const url = response.body.additional_action_required.data.redirect_url;\n const data = response.body.provider_data;\n\n return new Promise(() => {\n this._formPoster.postForm(url, JSON.parse(data));\n });\n }\n\n private _isOffsiteRedirectResponse(response: unknown): response is OffsiteRedirectResponse {\n if (typeof response !== 'object' || response === null) {\n return false;\n }\n\n const partialResponse: Partial = response;\n\n if (!partialResponse.body) {\n return false;\n }\n\n const partialBody: Partial = partialResponse.body;\n\n return (\n partialBody.status === 'additional_action_required' &&\n !!partialBody.additional_action_required &&\n partialBody.additional_action_required.type === 'offsite_redirect' &&\n typeof partialBody.provider_data === 'string'\n );\n }\n}\n\ninterface OffsiteRedirectResponse {\n body: {\n additional_action_required: {\n type: 'offsite_redirect';\n data: {\n redirect_url: string;\n };\n };\n status: string;\n provider_data: string;\n };\n}\n","export const supportedCountries = [\n 'AT',\n 'BE',\n 'CA',\n 'CH',\n 'CZ',\n 'DE',\n 'DK',\n 'ES',\n 'FI',\n 'FR',\n 'GB',\n 'GR',\n 'IE',\n 'IT',\n 'NL',\n 'NO',\n 'NZ',\n 'PL',\n 'PT',\n 'SE',\n];\nexport const supportedCountriesRequiringStates = ['AU'];\n","import { includes } from 'lodash';\n\nimport { PaymentMethodInvalidError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Address } from '../../../address';\nimport { BillingAddress } from '../../../billing';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport { PaymentMethodCancelledError } from '../../errors';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { supportedCountries, supportedCountriesRequiringStates } from '../klarnav2';\nimport PaymentStrategy from '../payment-strategy';\n\nimport KlarnaCredit, {\n KlarnaAddress,\n KlarnaLoadResponse,\n KlarnaUpdateSessionParams,\n} from './klarna-credit';\nimport KlarnaScriptLoader from './klarna-script-loader';\n\nexport default class KlarnaPaymentStrategy implements PaymentStrategy {\n private _klarnaCredit?: KlarnaCredit;\n private _unsubscribe?: () => void;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n private _klarnaScriptLoader: KlarnaScriptLoader,\n ) {}\n\n initialize(options: PaymentInitializeOptions): Promise {\n return this._klarnaScriptLoader\n .load()\n .then((klarnaCredit) => {\n this._klarnaCredit = klarnaCredit;\n })\n .then(() => {\n this._unsubscribe = this._store.subscribe(\n (state) => {\n if (\n state.paymentStrategies.isInitialized({\n methodId: options.methodId,\n gatewayId: options.gatewayId,\n })\n ) {\n this._loadWidget(options);\n }\n },\n (state) => {\n const checkout = state.checkout.getCheckout();\n\n return checkout && checkout.outstandingBalance;\n },\n (state) => {\n const checkout = state.checkout.getCheckout();\n\n return checkout && checkout.coupons;\n },\n );\n\n return this._loadWidget(options);\n })\n .then(() => this._store.getState());\n }\n\n deinitialize(): Promise {\n if (this._unsubscribe) {\n this._unsubscribe();\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n if (!payload.payment) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"payload.payment\" argument is not provided.',\n );\n }\n\n const {\n payment: { paymentData, ...paymentPayload },\n } = payload;\n\n return this._authorize()\n .then(({ authorization_token: authorizationToken }) =>\n this._store.dispatch(\n this._remoteCheckoutActionCreator.initializePayment(paymentPayload.methodId, {\n authorizationToken,\n }),\n ),\n )\n .then(() =>\n this._store.dispatch(\n this._orderActionCreator.submitOrder(\n {\n ...payload,\n payment: paymentPayload,\n useStoreCredit: payload.useStoreCredit,\n },\n options,\n ),\n ),\n );\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private _loadWidget(options: PaymentInitializeOptions): Promise {\n if (!options.klarna) {\n throw new InvalidArgumentError(\n 'Unable to load widget because \"options.klarna\" argument is not provided.',\n );\n }\n\n const {\n methodId,\n klarna: { container, onLoad },\n } = options;\n\n return this._store\n .dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId))\n .then(\n (state) =>\n new Promise((resolve) => {\n const paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (!this._klarnaCredit || !paymentMethod.clientToken) {\n throw new NotInitializedError(\n NotInitializedErrorType.PaymentNotInitialized,\n );\n }\n\n this._klarnaCredit.init({ client_token: paymentMethod.clientToken });\n\n this._klarnaCredit.load({ container }, (response) => {\n if (onLoad) {\n onLoad(response);\n }\n\n resolve(response);\n });\n }),\n );\n }\n\n private _getUpdateSessionData(\n billingAddress: BillingAddress,\n shippingAddress?: Address,\n ): KlarnaUpdateSessionParams {\n if (\n !includes(\n [...supportedCountries, ...supportedCountriesRequiringStates],\n billingAddress.countryCode,\n )\n ) {\n return {};\n }\n\n const data: KlarnaUpdateSessionParams = {\n billing_address: this._mapToKlarnaAddress(billingAddress, billingAddress.email),\n };\n\n if (shippingAddress) {\n data.shipping_address = this._mapToKlarnaAddress(shippingAddress, billingAddress.email);\n }\n\n return data;\n }\n\n private _needsStateCode(countryCode: string) {\n return includes(supportedCountriesRequiringStates, countryCode);\n }\n\n private _mapToKlarnaAddress(address: Address, email?: string): KlarnaAddress {\n const klarnaAddress: KlarnaAddress = {\n street_address: address.address1,\n city: address.city,\n country: address.countryCode,\n given_name: address.firstName,\n family_name: address.lastName,\n postal_code: address.postalCode,\n region: this._needsStateCode(address.countryCode)\n ? address.stateOrProvinceCode\n : address.stateOrProvince,\n email,\n };\n\n if (address.address2) {\n klarnaAddress.street_address2 = address.address2;\n }\n\n if (address.phone) {\n klarnaAddress.phone = address.phone;\n }\n\n return klarnaAddress;\n }\n\n private _authorize(): Promise {\n return new Promise((resolve, reject) => {\n const billingAddress = this._store.getState().billingAddress.getBillingAddress();\n const shippingAddress = this._store.getState().shippingAddress.getShippingAddress();\n\n if (!billingAddress) {\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n\n if (!this._klarnaCredit) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const updateSessionData = this._getUpdateSessionData(billingAddress, shippingAddress);\n\n this._klarnaCredit.authorize(updateSessionData, (res) => {\n if (res.approved) {\n return resolve(res);\n }\n\n if (res.show_form) {\n return reject(new PaymentMethodCancelledError());\n }\n\n reject(new PaymentMethodInvalidError());\n });\n });\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport KlarnaCredit from './klarna-credit';\nimport KlarnaWindow from './klarna-window';\n\nconst SDK_URL = '//credit.klarnacdn.net/lib/v1/api.js';\n\nexport default class KlarnaScriptLoader {\n constructor(private _scriptLoader: ScriptLoader) {}\n\n load(): Promise {\n return this._scriptLoader\n .loadScript(SDK_URL)\n .then(() => (window as unknown as KlarnaWindow).Klarna.Credit);\n }\n}\n","import { includes } from 'lodash';\n\nimport { PaymentMethodInvalidError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { Address } from '../../../address';\nimport { BillingAddress } from '../../../billing';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport { PaymentMethodCancelledError } from '../../errors';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport KlarnaPayments, {\n KlarnaAddress,\n KlarnaAuthorizationResponse,\n KlarnaLoadResponse,\n KlarnaUpdateSessionParams,\n} from './klarna-payments';\nimport {\n supportedCountries,\n supportedCountriesRequiringStates,\n} from './klarna-supported-countries';\nimport KlarnaV2ScriptLoader from './klarnav2-script-loader';\nimport KlarnaV2TokenUpdater from './klarnav2-token-updater';\n\nexport default class KlarnaV2PaymentStrategy implements PaymentStrategy {\n private _klarnaPayments?: KlarnaPayments;\n private _unsubscribe?: () => void;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n private _klarnav2ScriptLoader: KlarnaV2ScriptLoader,\n private _klarnav2TokenUpdater: KlarnaV2TokenUpdater,\n ) {}\n\n initialize(options: PaymentInitializeOptions): Promise {\n return this._klarnav2ScriptLoader\n .load()\n .then((klarnaPayments) => {\n this._klarnaPayments = klarnaPayments;\n })\n .then(() => {\n this._unsubscribe = this._store.subscribe(\n (state) => {\n if (\n state.paymentStrategies.isInitialized({\n methodId: options.methodId,\n gatewayId: options.gatewayId,\n })\n ) {\n this._loadPaymentsWidget(options);\n }\n },\n (state) => {\n const checkout = state.checkout.getCheckout();\n\n return checkout && checkout.outstandingBalance;\n },\n (state) => {\n const checkout = state.checkout.getCheckout();\n\n return checkout && checkout.coupons;\n },\n );\n\n return this._loadPaymentsWidget(options);\n })\n .then(() => this._store.getState());\n }\n\n deinitialize(): Promise {\n if (this._unsubscribe) {\n this._unsubscribe();\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n if (!payload.payment) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"payload.payment\" argument is not provided.',\n );\n }\n\n const {\n payment: { paymentData, ...paymentPayload },\n } = payload;\n const { gatewayId } = paymentPayload;\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"payload.payment.gatewayId\" argument is not provided.',\n );\n }\n\n return this._authorize(paymentPayload.methodId)\n .then(({ authorization_token: authorizationToken }) =>\n this._store.dispatch(\n this._remoteCheckoutActionCreator.initializePayment(gatewayId, {\n authorizationToken,\n }),\n ),\n )\n .then(() =>\n this._store.dispatch(\n this._orderActionCreator.submitOrder(\n {\n ...payload,\n payment: paymentPayload,\n useStoreCredit: payload.useStoreCredit,\n },\n options,\n ),\n ),\n );\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private async _loadPaymentsWidget(\n options: PaymentInitializeOptions,\n ): Promise {\n if (!options.klarnav2) {\n throw new InvalidArgumentError(\n 'Unable to load widget because \"options.klarnav2\" argument is not provided.',\n );\n }\n\n const {\n methodId,\n gatewayId,\n klarnav2: { container, onLoad },\n } = options;\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"payload.payment.gatewayId\" argument is not provided.',\n );\n }\n\n const state = this._store.getState();\n const cartId = state.cart.getCartOrThrow().id;\n const params = { params: cartId };\n\n await this._klarnav2TokenUpdater.updateClientToken(gatewayId, { params }).catch(() => {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n });\n\n return new Promise((resolve) => {\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n if (!this._klarnaPayments || !paymentMethod.clientToken) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._klarnaPayments.init({ client_token: paymentMethod.clientToken });\n this._klarnaPayments.load(\n { container, payment_method_category: paymentMethod.id },\n (response) => {\n if (onLoad) {\n onLoad(response);\n }\n\n resolve(response);\n },\n );\n });\n }\n\n private _getUpdateSessionData(\n billingAddress: BillingAddress,\n shippingAddress?: Address,\n ): KlarnaUpdateSessionParams {\n if (\n !includes(\n [...supportedCountries, ...supportedCountriesRequiringStates],\n billingAddress.countryCode,\n )\n ) {\n return {};\n }\n\n const data: KlarnaUpdateSessionParams = {\n billing_address: this._mapToKlarnaAddress(billingAddress, billingAddress.email),\n };\n\n if (shippingAddress) {\n data.shipping_address = this._mapToKlarnaAddress(shippingAddress, billingAddress.email);\n }\n\n return data;\n }\n\n private _needsStateCode(countryCode: string) {\n return includes(supportedCountriesRequiringStates, countryCode);\n }\n\n private _mapToKlarnaAddress(address: Address, email?: string): KlarnaAddress {\n const klarnaAddress: KlarnaAddress = {\n street_address: address.address1,\n city: address.city,\n country: address.countryCode,\n given_name: address.firstName,\n family_name: address.lastName,\n postal_code: address.postalCode,\n region: this._needsStateCode(address.countryCode)\n ? address.stateOrProvinceCode\n : address.stateOrProvince,\n email,\n };\n\n if (address.address2) {\n klarnaAddress.street_address2 = address.address2;\n }\n\n if (address.phone) {\n klarnaAddress.phone = address.phone;\n }\n\n return klarnaAddress;\n }\n\n private _authorize(methodId: string): Promise {\n return new Promise((resolve, reject) => {\n const billingAddress = this._store.getState().billingAddress.getBillingAddress();\n const shippingAddress = this._store.getState().shippingAddress.getShippingAddress();\n\n if (!billingAddress) {\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n\n const updateSessionData = this._getUpdateSessionData(billingAddress, shippingAddress);\n\n if (!this._klarnaPayments) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._klarnaPayments.authorize(\n { payment_method_category: methodId },\n updateSessionData,\n (res) => {\n if (res.approved) {\n return resolve(res);\n }\n\n if (res.show_form) {\n return reject(new PaymentMethodCancelledError());\n }\n\n reject(new PaymentMethodInvalidError());\n },\n );\n });\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport KlarnaPayments from './klarna-payments';\nimport KlarnaV2Window from './klarnav2-window';\n\nconst SDK_URL = 'https://x.klarnacdn.net/kp/lib/v1/api.js';\n\nexport default class KlarnaV2ScriptLoader {\n constructor(private _scriptLoader: ScriptLoader) {}\n\n load(): Promise {\n return this._scriptLoader\n .loadScript(SDK_URL)\n .then(() => (window as unknown as KlarnaV2Window).Klarna.Payments);\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport {\n ContentType,\n INTERNAL_USE_ONLY,\n RequestOptions,\n SDK_VERSION_HEADERS,\n} from '../../../common/http-request';\nimport PaymentMethod from '../../payment-method';\n\nexport default class KlarnaV2TokenUpdater {\n constructor(private _requestSender: RequestSender) {}\n\n updateClientToken(\n gatewayId: string,\n { timeout, params }: RequestOptions = {},\n ): Promise> {\n const url = `/api/storefront/payments/${gatewayId}`;\n\n return this._requestSender.get(url, {\n timeout,\n headers: {\n Accept: ContentType.JsonV1,\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n params,\n });\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../../../common/error/errors';\nimport { bindDecorator as bind } from '../../../common/utility';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport formatLocale from './format-locale';\nimport getCallbackUrl from './get-callback-url';\nimport { Masterpass, MasterpassCheckoutOptions } from './masterpass';\nimport MasterpassScriptLoader from './masterpass-script-loader';\n\nexport default class MasterpassPaymentStrategy implements PaymentStrategy {\n private _masterpassClient?: Masterpass;\n private _paymentMethod?: PaymentMethod;\n private _walletButton?: HTMLElement;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _masterpassScriptLoader: MasterpassScriptLoader,\n private _locale: string,\n ) {}\n\n initialize(options: PaymentInitializeOptions): Promise {\n const { methodId } = options;\n\n this._paymentMethod = this._store.getState().paymentMethods.getPaymentMethod(methodId);\n\n if (!this._paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const masterpassScriptLoaderParams = {\n useMasterpassSrc: this._paymentMethod.initializationData.isMasterpassSrcEnabled,\n language: formatLocale(this._locale),\n testMode: this._paymentMethod.config.testMode,\n checkoutId: this._paymentMethod.initializationData.checkoutId,\n };\n\n return this._masterpassScriptLoader\n .load(masterpassScriptLoaderParams)\n .then((masterpass) => {\n this._masterpassClient = masterpass;\n\n if (!options.masterpass) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.masterpass\" argument is not provided.',\n );\n }\n\n const walletButton =\n options.masterpass.walletButton &&\n document.getElementById(options.masterpass.walletButton);\n\n if (walletButton) {\n this._walletButton = walletButton;\n this._walletButton.addEventListener('click', this._handleWalletButtonClick);\n }\n\n return this._store.getState();\n });\n }\n\n deinitialize(): Promise {\n this._paymentMethod = undefined;\n\n if (this._walletButton) {\n this._walletButton.removeEventListener('click', this._handleWalletButtonClick);\n }\n\n this._walletButton = undefined;\n this._masterpassClient = undefined;\n\n return Promise.resolve(this._store.getState());\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment } = payload;\n const order = { useStoreCredit: payload.useStoreCredit };\n\n if (!payment) {\n throw new InvalidArgumentError(\n 'Unable to submit payment because \"payload.payment\" argument is not provided.',\n );\n }\n\n if (\n !this._paymentMethod ||\n !this._paymentMethod.initializationData ||\n !this._paymentMethod.initializationData.gateway\n ) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n // TODO: Refactor the API endpoint to return nonce in the right place.\n const paymentData = this._paymentMethod.initializationData.paymentData;\n\n // TODO: Redirect to Masterpass if nonce has not been generated yet. And then finalise the order when the shopper is redirected back to the checkout page.\n if (!paymentData) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"paymentMethod.initializationData.paymentData\" argument is not provided.',\n );\n }\n\n return this._store\n .dispatch(this._orderActionCreator.submitOrder(order, options))\n .then(() =>\n this._store.dispatch(\n this._paymentActionCreator.submitPayment({ ...payment, paymentData }),\n ),\n );\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private _createMasterpassPayload(): MasterpassCheckoutOptions {\n const state = this._store.getState();\n const checkout = state.checkout.getCheckout();\n const storeConfig = state.config.getStoreConfig();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n if (!this._paymentMethod || !this._paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n return {\n checkoutId: this._paymentMethod.initializationData.checkoutId,\n allowedCardTypes: this._paymentMethod.initializationData.allowedCardTypes,\n amount: checkout.subtotal.toFixed(2),\n currency: storeConfig.currency.code,\n cartId: checkout.cart.id,\n callbackUrl: getCallbackUrl('checkout'),\n };\n }\n\n @bind\n private _handleWalletButtonClick(event: Event) {\n event.preventDefault();\n\n if (!this._masterpassClient) {\n return;\n }\n\n const payload = this._createMasterpassPayload();\n\n this._masterpassClient.checkout(payload);\n }\n}\n","import { each, some } from 'lodash';\n\nimport { PaymentActionCreator } from '../..';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { getBrowserInfo } from '../../../common/browser-info';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { HostedForm, HostedFormFactory, HostedFormOptions } from '../../../hosted-form';\nimport { OrderActionCreator, OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport isVaultedInstrument from '../../is-vaulted-instrument';\nimport { HostedInstrument } from '../../payment';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { MollieClient, MollieElement } from './mollie';\nimport MolliePaymentInitializeOptions from './mollie-initialize-options';\nimport MollieScriptLoader from './mollie-script-loader';\n\nexport enum MolliePaymentMethodType {\n creditcard = 'credit_card',\n}\n\nconst methodsNotAllowedWhenDigitalOrder = ['klarnapaylater', 'klarnasliceit'];\n\nexport default class MolliePaymentStrategy implements PaymentStrategy {\n private _initializeOptions?: MolliePaymentInitializeOptions;\n private _mollieClient?: MollieClient;\n private _cardHolderElement?: MollieElement;\n private _cardNumberElement?: MollieElement;\n private _verificationCodeElement?: MollieElement;\n private _expiryDateElement?: MollieElement;\n private _locale?: string;\n\n private _hostedForm?: HostedForm;\n\n private _unsubscribe?: () => void;\n\n constructor(\n private _hostedFormFactory: HostedFormFactory,\n private _store: CheckoutStore,\n private _mollieScriptLoader: MollieScriptLoader,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const { mollie, methodId, gatewayId } = options;\n\n if (!mollie) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.mollie\" argument is not provided.',\n );\n }\n\n if (!methodId || !gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"methodId\" and/or \"gatewayId\" argument is not provided.',\n );\n }\n\n const controllers = document.querySelectorAll('.mollie-components-controller');\n\n each(controllers, (controller) => controller.remove());\n\n const state = this._store.getState();\n const storeConfig = state.config.getStoreConfig();\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n this._initializeOptions = mollie;\n\n const paymentMethods = state.paymentMethods;\n const paymentMethod = paymentMethods.getPaymentMethodOrThrow(methodId, gatewayId);\n const {\n config: { merchantId, testMode },\n } = paymentMethod;\n const { locale } = paymentMethod.initializationData;\n\n this._locale = locale;\n\n if (!merchantId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"merchantId\" argument is not provided.',\n );\n }\n\n if (\n this.isCreditCard(methodId) &&\n mollie.form &&\n this.shouldShowTSVHostedForm(methodId, gatewayId)\n ) {\n this._hostedForm = await this._mountCardVerificationfields(mollie.form);\n } else if (this.isCreditCard(methodId)) {\n this._mollieClient = await this._loadMollieJs(\n merchantId,\n storeConfig.storeProfile.storeLanguage,\n testMode,\n );\n this._mountElements();\n }\n\n this._unsubscribe = this._store.subscribe(\n async (state) => {\n if (\n state.paymentStrategies.isInitialized({\n methodId: options.methodId,\n gatewayId: options.gatewayId,\n })\n ) {\n const element = document.getElementById(`${gatewayId}-${methodId}-paragraph`);\n\n if (element) {\n element.remove();\n }\n\n mollie.disableButton(false);\n\n this._loadPaymentMethodsAllowed(mollie, methodId, gatewayId, state);\n }\n },\n (state) => {\n const checkout = state.checkout.getCheckout();\n\n return checkout && checkout.outstandingBalance;\n },\n (state) => {\n const checkout = state.checkout.getCheckout();\n\n return checkout && checkout.coupons;\n },\n );\n\n this._loadPaymentMethodsAllowed(mollie, methodId, gatewayId, state);\n\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n const paymentData = payment?.paymentData;\n\n if (!payment || !payment.gatewayId || !paymentData) {\n throw new PaymentArgumentInvalidError(['payment', 'gatewayId', 'paymentData']);\n }\n\n try {\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n if (isVaultedInstrument(paymentData)) {\n return await this.executeWithVaulted(payment);\n }\n\n if (this.isCreditCard(payment.methodId)) {\n return await this.executeWithCC(payment);\n }\n\n return await this.executeWithAPM(payment);\n } catch (error) {\n return this._processAdditionalAction(error);\n }\n }\n\n finalize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(options?: PaymentRequestOptions): Promise {\n if (this._unsubscribe) {\n this._unsubscribe();\n }\n\n if (this._hostedForm) {\n this._hostedForm.detach();\n }\n\n if (options && options.methodId && options.gatewayId && !this._hostedForm) {\n const element = document.getElementById(`${options.gatewayId}-${options.methodId}`);\n\n if (element) {\n element.remove();\n }\n } else if (options && options.methodId && this.isCreditCard(options.methodId)) {\n if (\n this._cardHolderElement &&\n this._cardNumberElement &&\n this._verificationCodeElement &&\n this._expiryDateElement\n ) {\n this._cardHolderElement.unmount();\n this._cardHolderElement = undefined;\n\n this._cardNumberElement.unmount();\n this._cardNumberElement = undefined;\n\n this._verificationCodeElement.unmount();\n this._verificationCodeElement = undefined;\n\n this._expiryDateElement.unmount();\n this._expiryDateElement = undefined;\n }\n }\n\n this._mollieClient = undefined;\n\n return Promise.resolve(this._store.getState());\n }\n\n protected async executeWithCC(\n payment: OrderPaymentRequestBody,\n ): Promise {\n const paymentData = payment.paymentData;\n const shouldSaveInstrument = (paymentData as HostedInstrument).shouldSaveInstrument;\n const shouldSetAsDefaultInstrument = (paymentData as HostedInstrument)\n .shouldSetAsDefaultInstrument;\n\n const { token, error } = await this._getMollieClient().createToken();\n\n if (error) {\n return Promise.reject(error);\n }\n\n const formattedPayload = {\n credit_card_token: {\n token,\n },\n vault_payment_instrument: shouldSaveInstrument,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n browser_info: getBrowserInfo(),\n shopper_locale: this._getShopperLocale(),\n };\n\n return this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n ...payment,\n paymentData: {\n formattedPayload,\n },\n }),\n );\n }\n\n protected async executeWithVaulted(\n payment: OrderPaymentRequestBody,\n ): Promise {\n if (this._isHostedPaymentFormEnabled(payment.methodId, payment.gatewayId)) {\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n await form.validate();\n await form.submit(payment);\n\n return this._store.dispatch(this._orderActionCreator.loadCurrentOrder());\n }\n\n return this._store.dispatch(this._paymentActionCreator.submitPayment(payment));\n }\n\n protected async executeWithAPM(\n payment: OrderPaymentRequestBody,\n ): Promise {\n const paymentData = payment.paymentData;\n const issuer = paymentData && 'issuer' in paymentData ? paymentData.issuer : '';\n\n return this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n ...payment,\n paymentData: {\n ...paymentData,\n formattedPayload: {\n issuer,\n shopper_locale: this._getShopperLocale(),\n },\n },\n }),\n );\n }\n\n private isCreditCard(methodId: string): boolean {\n return methodId === MolliePaymentMethodType.creditcard;\n }\n\n private shouldShowTSVHostedForm(methodId: string, gatewayId: string): boolean {\n return (\n this._isHostedPaymentFormEnabled(methodId, gatewayId) && this._isHostedFieldAvailable()\n );\n }\n\n private _mountCardVerificationfields(formOptions: HostedFormOptions): Promise {\n /* eslint-disable */\n return new Promise(async (resolve , reject) => {\n try {\n const { config } = this._store.getState();\n const bigpayBaseUrl = config.getStoreConfig()?.paymentSettings.bigpayBaseUrl;\n\n if (!bigpayBaseUrl) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const form = this._hostedFormFactory.create(bigpayBaseUrl, formOptions);\n\n await form.attach();\n\n resolve(form);\n } catch (error) {\n reject(error);\n }\n });\n }\n\n private _isHostedPaymentFormEnabled(methodId: string, gatewayId?: string): boolean {\n const { paymentMethods: { getPaymentMethodOrThrow } } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(methodId, gatewayId);\n\n return paymentMethod.config.isHostedFormEnabled === true;\n }\n\n private _isHostedFieldAvailable(): boolean {\n const options = this._getInitializeOptions();\n\n return !!options.form?.fields;\n }\n\n private _processAdditionalAction(error: any): Promise {\n if (!(error instanceof RequestError) || !some(error.body.errors, {code: 'additional_action_required'})) {\n return Promise.reject(error);\n }\n const { additional_action_required: { data : { redirect_url } } } = error.body;\n\n return new Promise(() => window.location.replace(redirect_url));\n }\n\n private _getInitializeOptions(): MolliePaymentInitializeOptions {\n if (!this._initializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._initializeOptions;\n }\n\n private _loadMollieJs(merchantId: string, locale: string, testmode = false): Promise {\n if (this._mollieClient) {\n return Promise.resolve(this._mollieClient);\n }\n\n return this._mollieScriptLoader\n .load(merchantId, locale, testmode);\n }\n\n private _getMollieClient(): MollieClient {\n if (!this._mollieClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._mollieClient;\n }\n\n private _getShopperLocale(): string {\n if (!this._locale) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._locale;\n }\n\n /**\n * ContainerId is use in Mollie for determined either its showing or not the\n * container, because when Mollie has Vaulted Instruments it gets hide,\n * and shows an error because can't mount Provider Components\n *\n * We had to add a settimeout because Mollie sets de tab index after mounting\n * each component, but without a setTimeOut Mollie is not able to find the\n * components as they are hidden so we need to wait until they are shown\n */\n private _mountElements() {\n const { containerId, cardNumberId, cardCvcId, cardExpiryId, cardHolderId, styles } = this._getInitializeOptions();\n let container: HTMLElement | null;\n\n if (containerId) {\n container = document.getElementById(containerId);\n }\n\n setTimeout(() => {\n if (!containerId || container?.style.display !== 'none') {\n const mollieClient = this._getMollieClient();\n\n this._cardHolderElement = mollieClient.createComponent('cardHolder', { styles });\n this._cardHolderElement.mount(`#${cardHolderId}`);\n\n this._cardNumberElement = mollieClient.createComponent('cardNumber', { styles });\n this._cardNumberElement.mount(`#${cardNumberId}`);\n\n this._verificationCodeElement = mollieClient.createComponent('verificationCode', { styles });\n this._verificationCodeElement.mount(`#${cardCvcId}`);\n\n this._expiryDateElement = mollieClient.createComponent('expiryDate', { styles });\n this._expiryDateElement.mount(`#${cardExpiryId}`);\n }\n }, 0);\n }\n\n private _loadPaymentMethodsAllowed(mollie: MolliePaymentInitializeOptions, methodId: string, gatewayId: string, state: InternalCheckoutSelectors){\n if (methodsNotAllowedWhenDigitalOrder.includes(methodId)) {\n const cart = state.cart.getCartOrThrow();\n const cartDigitalItems = cart.lineItems.digitalItems;\n\n if (cartDigitalItems && cartDigitalItems.length > 0) {\n const { containerId } = this._getInitializeOptions();\n\n if (containerId) {\n const container = document.getElementById(containerId);\n\n if (container) {\n const paragraph = document.createElement('p') ;\n paragraph.setAttribute(\"id\",`${gatewayId}-${methodId}-paragraph`)\n\n if (mollie.unsupportedMethodMessage) {\n paragraph.innerText = mollie.unsupportedMethodMessage;\n container.appendChild(paragraph);\n mollie.disableButton(true);\n }\n }\n }\n }\n }\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { MollieClient, MollieHostWindow } from './mollie';\n\nexport default class MollieScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, private _window: Window = window) {}\n\n _isMollieWindow(window: Window): window is MollieHostWindow {\n const mollieWindow: MollieHostWindow = window as MollieHostWindow;\n\n return !!mollieWindow.Mollie;\n }\n\n async load(merchantId: string, locale: string, testmode: boolean): Promise {\n await this._scriptLoader.loadScript('https://js.mollie.com/v1/mollie.js');\n\n if (!this._isMollieWindow(this._window)) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.Mollie(merchantId, {\n locale,\n testmode,\n });\n }\n}\n","import { isEmpty, map, omitBy } from 'lodash';\n\nimport { isHostedInstrumentLike } from '../../';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { HostedForm, HostedFormFactory, HostedFormOptions } from '../../../hosted-form';\nimport { OrderActionCreator, OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { StoreCreditActionCreator } from '../../../store-credit';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport isVaultedInstrument from '../../is-vaulted-instrument';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport MonerisStylingProps, {\n MoneriesHostedFieldsQueryParams,\n MonerisInitializationData,\n MonerisResponseData,\n} from './moneris';\nimport MonerisPaymentInitializeOptions from './moneris-payment-initialize-options';\n\nconst IFRAME_NAME = 'moneris-payment-iframe';\nconst RESPONSE_SUCCESS_CODE = '001';\n\nexport default class MonerisPaymentStrategy implements PaymentStrategy {\n private _iframe?: HTMLIFrameElement;\n private _initializeOptions?: MonerisPaymentInitializeOptions;\n private _windowEventListener?: (response: MessageEvent) => void;\n\n private _hostedForm?: HostedForm;\n\n constructor(\n private _hostedFormFactory: HostedFormFactory,\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _storeCreditActionCreator: StoreCreditActionCreator,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const state = this._store.getState();\n\n const { moneris: monerisOptions, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"methodId\" argument is not provided.',\n );\n }\n\n if (!monerisOptions) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.moneris\" argument is not provided.',\n );\n }\n\n this._initializeOptions = monerisOptions;\n\n const { config, initializationData } =\n state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n if (!initializationData?.profileId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (monerisOptions.form && this._shouldShowTSVHostedForm(methodId)) {\n this._hostedForm = await this._mountCardVerificationfields(monerisOptions.form);\n }\n\n if (!this._iframe) {\n this._iframe = this._createIframe(\n monerisOptions.containerId,\n initializationData,\n !!config.testMode,\n );\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentInitializeOptions,\n ): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { isStoreCreditApplied: useStoreCredit } = this._store\n .getState()\n .checkout.getCheckoutOrThrow();\n\n if (useStoreCredit !== undefined) {\n await this._store.dispatch(\n this._storeCreditActionCreator.applyStoreCredit(useStoreCredit),\n );\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n if (payment.paymentData && isVaultedInstrument(payment.paymentData)) {\n return this._executeWithVaulted(payment);\n }\n\n return this._executeWithCC(payment);\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n if (this._hostedForm) {\n this._hostedForm.detach();\n }\n\n if (this._windowEventListener) {\n window.removeEventListener('message', this._windowEventListener);\n this._windowEventListener = undefined;\n }\n\n if (this._iframe && this._iframe.parentNode) {\n this._iframe.parentNode.removeChild(this._iframe);\n this._iframe = undefined;\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n private async _executeWithCC(\n payment: OrderPaymentRequestBody,\n ): Promise {\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(payment.methodId);\n\n const testMode = paymentMethod.config.testMode;\n const paymentData = payment.paymentData || {};\n const instrumentSettings = isHostedInstrumentLike(paymentData)\n ? paymentData\n : { shouldSaveInstrument: false, shouldSetAsDefaultInstrument: false };\n\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = instrumentSettings;\n\n const nonce = await new Promise((resolve, reject) => {\n if (!this._iframe) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const frameref = this._iframe.contentWindow;\n\n frameref?.postMessage('tokenize', this._monerisURL(!!testMode));\n\n this._windowEventListener = (response: MessageEvent) => {\n if (typeof response.data !== 'string') {\n return;\n }\n\n try {\n resolve(this._handleMonerisResponse(response));\n } catch (error) {\n reject(error);\n }\n };\n\n window.addEventListener('message', this._windowEventListener);\n });\n\n if (nonce !== undefined) {\n return this._store.dispatch(\n this._paymentActionCreator.submitPayment({\n methodId: payment.methodId,\n paymentData: { nonce, shouldSaveInstrument, shouldSetAsDefaultInstrument },\n }),\n );\n }\n\n return this._store.getState();\n }\n\n private async _executeWithVaulted(\n payment: OrderPaymentRequestBody,\n ): Promise {\n if (this._hostedForm) {\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n await form.validate();\n await form.submit(payment);\n\n return this._store.dispatch(this._orderActionCreator.loadCurrentOrder());\n }\n\n return this._store.dispatch(this._paymentActionCreator.submitPayment(payment));\n }\n\n private _shouldShowTSVHostedForm(methodId: string): boolean {\n return this._isHostedPaymentFormEnabled(methodId) && this._isHostedFieldAvailable();\n }\n\n private _isHostedPaymentFormEnabled(methodId: string): boolean {\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(methodId);\n\n return Boolean(paymentMethod.config.isHostedFormEnabled);\n }\n\n private _isHostedFieldAvailable(): boolean {\n const options = this._getInitializeOptions();\n const definedFields = omitBy(options.form?.fields, isEmpty);\n\n return !isEmpty(definedFields);\n }\n\n private _getInitializeOptions(): MonerisPaymentInitializeOptions {\n if (!this._initializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._initializeOptions;\n }\n\n private async _mountCardVerificationfields(\n formOptions: HostedFormOptions,\n ): Promise {\n const { config } = this._store.getState();\n const bigpayBaseUrl = config.getStoreConfig()?.paymentSettings.bigpayBaseUrl;\n\n if (!bigpayBaseUrl) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const form = this._hostedFormFactory.create(bigpayBaseUrl, formOptions);\n\n await form.attach();\n\n return form;\n }\n\n private _createIframe(\n containerId: string,\n initializationData: MonerisInitializationData,\n testMode: boolean,\n style?: MonerisStylingProps,\n ): HTMLIFrameElement {\n const container = document.getElementById(containerId);\n\n if (!container) {\n throw new InvalidArgumentError('Unable to create iframe without valid container ID.');\n }\n\n const iframe = document.createElement('iframe');\n const monerisQueryParams: MoneriesHostedFieldsQueryParams = {\n id: initializationData.profileId,\n pmmsg: true,\n display_labels: 1,\n enable_exp: 1,\n enable_cvd: 1,\n css_body:\n style?.cssBody ||\n 'font-family: Arial, Helvetica,sans-serif;background: transparent;',\n css_textbox:\n style?.cssTextbox ||\n 'border-radius:4px;border: 2px solid rgb(00,00,00);width: 100%;font-weight: 600;padding: 8px 8px;outline: 0;',\n css_textbox_pan: style?.cssTextboxCardNumber || 'width: 240px;',\n css_textbox_exp:\n style?.cssTextboxExpiryDate || 'margin-bottom: 0;width: calc(30% - 12px);',\n css_textbox_cvd: style?.cssTextboxCVV || 'margin-bottom: 0;width: calc(30% - 12px);',\n css_input_label:\n style?.cssInputLabel ||\n '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;',\n pan_label: initializationData.creditCardLabel || 'Credit Card Number',\n exp_label: initializationData.expiryDateLabel || 'Expiration',\n cvd_label: initializationData.cvdLabel || 'CVD',\n };\n\n const queryString = map(monerisQueryParams, (value, key) => `${key}=${value}`).join('&');\n\n iframe.width = '100%';\n iframe.height = '100%';\n iframe.name = IFRAME_NAME;\n iframe.id = IFRAME_NAME;\n iframe.style.border = 'none';\n iframe.src = `${this._monerisURL(testMode)}?${queryString}`;\n\n container.appendChild(iframe);\n\n return iframe;\n }\n\n private _handleMonerisResponse(response: MessageEvent): string {\n const monerisResponse: MonerisResponseData = JSON.parse(response.data);\n\n if (monerisResponse.responseCode[0] !== RESPONSE_SUCCESS_CODE) {\n throw new Error(monerisResponse.errorMessage);\n }\n\n return monerisResponse.dataKey;\n }\n\n private _monerisURL(testMode: boolean): string {\n return `https://${testMode ? 'esqa' : 'www3'}.moneris.com/HPPtoken/index.php`;\n }\n}\n","import PaymentMethod from '../../payment-method';\n\nimport { OpyWidgetConfig } from './opy-library';\n\nexport enum ActionTypes {\n FORM_POST = 'FormPost',\n WAIT_FOR_CUSTOMER = 'WaitForCustomer',\n}\n\ninterface FormPost {\n type: ActionTypes.FORM_POST;\n formPost: {\n formPostUrl: string;\n formFields: [\n {\n fieldName: string;\n fieldValue: string;\n },\n ];\n };\n}\n\ninterface WaitForCustomer {\n type: ActionTypes.WAIT_FOR_CUSTOMER;\n}\n\nexport interface OpyPaymentMethod extends PaymentMethod {\n initializationData: {\n nextAction?: FormPost | WaitForCustomer;\n widgetConfig: OpyWidgetConfig;\n };\n}\n\nexport function isOpyPaymentMethod(\n paymentMethod: PaymentMethod,\n): paymentMethod is OpyPaymentMethod {\n return !!paymentMethod.initializationData?.widgetConfig;\n}\n","import { StandardError } from '../../../common/error/errors';\n\nexport enum OpyErrorType {\n InvalidCart = 'invalid_cart',\n}\nexport default class OpyError extends StandardError {\n subtype: string;\n\n constructor(subtype: OpyErrorType, displayName: string) {\n super(getErrorMessage(subtype, displayName));\n\n this.name = 'OpyError';\n this.type = 'opy_error';\n this.subtype = subtype;\n }\n}\n\nfunction getErrorMessage(type: OpyErrorType, displayName: string): string {\n switch (type) {\n case OpyErrorType.InvalidCart:\n return `Cart price is different to ${displayName} plan amount.`;\n\n default:\n return 'There was an error while processing your payment. Please try again or contact us.';\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotImplementedError,\n RequestError,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport StorefrontPaymentRequestSender from '../../storefront-payment-request-sender';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { ActionTypes, isOpyPaymentMethod } from './opy';\nimport { OpyWidgetConfig } from './opy-library';\nimport OpyError, { OpyErrorType } from './opy-payment-error';\nimport OpyScriptLoader from './opy-script-loader';\n\nexport default class OpyPaymentStrategy implements PaymentStrategy {\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _storefrontPaymentRequestSender: StorefrontPaymentRequestSender,\n private _paymentActionCreator: PaymentActionCreator,\n private _scriptLoader: OpyScriptLoader,\n ) {}\n\n async initialize(options?: PaymentInitializeOptions): Promise {\n if (options?.opy?.containerId) {\n const {\n methodId,\n opy: { containerId },\n } = options;\n\n const paymentMethod = this._store.getState().paymentMethods.getPaymentMethod(methodId);\n\n if (paymentMethod && isOpyPaymentMethod(paymentMethod)) {\n const {\n initializationData: { widgetConfig },\n } = paymentMethod;\n\n await this._installWidget(containerId, widgetConfig);\n }\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId } = payment;\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId, options),\n );\n const paymentMethod = getPaymentMethodOrThrow(methodId);\n\n if (!isOpyPaymentMethod(paymentMethod)) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const {\n clientToken: nonce,\n initializationData: { nextAction },\n } = paymentMethod;\n\n if (!nextAction) {\n const { displayName = 'Openpay' } = paymentMethod.config;\n\n throw new OpyError(OpyErrorType.InvalidCart, displayName);\n }\n\n if (!nonce) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n await this._storefrontPaymentRequestSender.saveExternalId(methodId, nonce);\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({ methodId, paymentData: { nonce } }),\n );\n } catch (error) {\n if (\n error instanceof RequestError &&\n error.body.status === 'additional_action_required'\n ) {\n if (nextAction.type === ActionTypes.FORM_POST) {\n const { formPostUrl, formFields } = nextAction.formPost;\n\n const url = new URL(formPostUrl.replace(/\\/$/, ''));\n\n formFields.forEach(({ fieldName, fieldValue }) => {\n url.searchParams.append(fieldName, fieldValue);\n });\n\n return new Promise(() => window.location.assign(decodeURI(url.href)));\n }\n\n throw new NotImplementedError(`Unsupported action type: ${nextAction.type}`);\n }\n\n throw error;\n }\n }\n\n finalize(_options?: PaymentRequestOptions): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(_options?: PaymentRequestOptions): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n private async _installWidget(containerId: string, config: OpyWidgetConfig): Promise {\n const widgetContainer = document.getElementById(containerId);\n\n if (widgetContainer) {\n try {\n const widget = await this._scriptLoader.loadOpyWidget(config.region);\n\n widget.Config(config);\n } catch (error) {\n return;\n }\n\n widgetContainer.appendChild(document.createElement('opy-learn-more-button'));\n }\n }\n}\n","export enum OpyRegion {\n AU = 'AU',\n UK = 'UK',\n US = 'US',\n}\n\n/**\n * https://widgets.openpay.com.au/config\n */\nexport interface OpyWidgetConfig {\n /**\n * The region your store is located in.\n */\n region: OpyRegion;\n /**\n * The currency symbol used in the widgets.\n */\n currency: '$' | '£';\n /**\n * An array of available plan tiers you have available in months.\n */\n planTiers: number[];\n /**\n * The minimum eligible amount required before Opy is eligible.\n */\n minEligibleAmount: number;\n /**\n * The maximum eligible amount required before Opy is eligible.\n */\n maxEligibleAmount: number;\n /**\n * Type of your store.\n */\n type: 'Online';\n}\n\nexport interface OpyWidget {\n /**\n * Initialize the library.\n *\n * @param config Properties with the correct purchase limits, plan tiers, etc.\n */\n Config(config: OpyWidgetConfig): void;\n}\n\nexport interface OpyHostWindow extends Window {\n /**\n * The Opy widgets library.\n */\n OpenpayWidgets?: OpyWidget;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { OpyHostWindow, OpyRegion, OpyWidget } from './opy-library';\n\nconst AU_REGION_URL = 'https://widgets.openpay.com.au/lib/openpay-widgets.min.js';\n\nconst SOURCES = {\n AU: AU_REGION_URL,\n UK: AU_REGION_URL,\n US: 'https://widgets.opy.com/lib/openpay-widgets.min.js',\n};\n\nexport default class OpyScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, private _window: OpyHostWindow = window) {}\n\n async loadOpyWidget(region = OpyRegion.AU): Promise {\n await this._scriptLoader.loadScript(SOURCES[region]);\n\n if (!this._window.OpenpayWidgets) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.OpenpayWidgets;\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { ACKNOWLEDGE } from '../../payment-status-types';\nimport { CardinalThreeDSecureFlow } from '../cardinal';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class PaypalProPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _threeDSecureFlow: CardinalThreeDSecureFlow,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n async initialize(options: PaymentInitializeOptions): Promise {\n await super.initialize(options);\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(options.methodId);\n\n if (paymentMethod.config.is3dsEnabled) {\n await this._threeDSecureFlow.prepare(paymentMethod);\n }\n\n return this._store.getState();\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment: { methodId = '' } = {} } = payload;\n const {\n payment: { getPaymentStatus },\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n\n if (getPaymentStatus() === ACKNOWLEDGE) {\n return this._store.dispatch(\n this._orderActionCreator.submitOrder(\n {\n ...payload,\n payment: { methodId },\n },\n options,\n ),\n );\n }\n\n if (getPaymentMethodOrThrow(methodId).config.is3dsEnabled) {\n return this._threeDSecureFlow.start(\n super.execute.bind(this),\n payload,\n options,\n this._hostedForm,\n );\n }\n\n return super.execute(payload, options);\n }\n}\n","import { noop } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport PaymentMethod from '../../payment-method';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport PaymentStrategy from '../payment-strategy';\n\nimport PaypalScriptLoader from './paypal-script-loader';\nimport { PaypalHostWindow, PaypalSDK } from './paypal-sdk';\n\nexport default class PaypalExpressPaymentStrategy implements PaymentStrategy {\n private _paypalSdk?: PaypalSDK;\n private _paymentMethod?: PaymentMethod;\n private _useRedirectFlow = false;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _scriptLoader: PaypalScriptLoader,\n private _window: PaypalHostWindow = window,\n ) {}\n\n initialize(options: PaymentInitializeOptions): Promise {\n const state = this._store.getState();\n\n this._paymentMethod = state.paymentMethods.getPaymentMethod(options.methodId);\n this._useRedirectFlow =\n (options.paypalexpress && options.paypalexpress.useRedirectFlow) === true;\n\n if (!this._isInContextEnabled()) {\n return Promise.resolve(this._store.getState());\n }\n\n return this._scriptLoader\n .loadPaypal()\n .then((paypal) => {\n this._paypalSdk = paypal;\n\n if (!this._paymentMethod || !this._paymentMethod.config.merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._paypalSdk.checkout.setup(this._paymentMethod.config.merchantId, {\n button: 'paypal-button',\n environment: this._paymentMethod.config.testMode ? 'sandbox' : 'production',\n });\n })\n .then(() => this._store.getState());\n }\n\n deinitialize(): Promise {\n if (this._isInContextEnabled() && this._paypalSdk) {\n this._paypalSdk.checkout.closeFlow();\n this._paypalSdk = undefined;\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const paypal = this._paypalSdk;\n\n if (this._isAcknowledgedOrFinalized()) {\n return this._store.dispatch(this._orderActionCreator.submitOrder(payload, options));\n }\n\n if (!this._isInContextEnabled() || this._useRedirectFlow) {\n return this._store\n .dispatch(this._orderActionCreator.submitOrder(payload, options))\n .then((state) => {\n const redirectUrl = state.payment.getPaymentRedirectUrl();\n\n if (redirectUrl) {\n this._window.top.location.href = redirectUrl;\n }\n\n // We need to hold execution so the consumer does not redirect us somewhere else\n return new Promise(noop);\n });\n }\n\n if (!paypal) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n paypal.checkout.initXO();\n\n return this._store\n .dispatch(this._orderActionCreator.submitOrder(payload, options))\n .then((state) => {\n const redirectUrl = state.payment.getPaymentRedirectUrl();\n\n if (redirectUrl) {\n paypal.checkout.startFlow(redirectUrl);\n }\n\n // We need to hold execution so the consumer does not redirect us somewhere else\n return new Promise(noop);\n })\n .catch((error) => {\n paypal.checkout.closeFlow();\n\n return Promise.reject(error);\n });\n }\n\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this._store.getState();\n const order = state.order.getOrder();\n\n if (order && this._isAcknowledgedOrFinalized()) {\n return this._store.dispatch(\n this._orderActionCreator.finalizeOrder(order.orderId, options),\n );\n }\n\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n private _isAcknowledgedOrFinalized(): boolean {\n const state = this._store.getState();\n\n return (\n state.payment.getPaymentStatus() === paymentStatusTypes.ACKNOWLEDGE ||\n state.payment.getPaymentStatus() === paymentStatusTypes.FINALIZE\n );\n }\n\n private _isInContextEnabled(): boolean {\n return !!(this._paymentMethod && this._paymentMethod.config.merchantId);\n }\n}\n","import { LoadScriptOptions, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { PaypalHostWindow, PaypalSDK } from './paypal-sdk';\n\nexport default class PaypalScriptLoader {\n private _window: PaypalHostWindow;\n\n constructor(private _scriptLoader: ScriptLoader) {\n this._window = window;\n }\n\n async loadPaypal(merchantId = ''): Promise {\n const scriptSrc = '//www.paypalobjects.com/api/checkout.min.js';\n const options: LoadScriptOptions = {\n async: true,\n attributes: { 'data-merchant-id': merchantId },\n };\n\n merchantId\n ? await this._scriptLoader.loadScript(scriptSrc, options)\n : await this._scriptLoader.loadScript(scriptSrc);\n\n if (!this._window.paypal) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.paypal;\n }\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"query-string\");","import { exclude, ParsedUrl, parseUrl, stringifyUrl } from 'query-string';\n\nexport const PENDING_REDIRECT_PARAM = 'redirecting';\n\nexport class RedirectionState {\n private _isRedirecting: boolean;\n\n constructor() {\n this._isRedirecting = this.currentUrlHasRedirectingParam();\n }\n\n isRedirecting() {\n return this._isRedirecting;\n }\n\n setRedirecting(value: boolean) {\n if (value) {\n this.setRedirectingParamOnUrl();\n } else {\n this.removeRedirectingParamFromUrl();\n }\n\n this._isRedirecting = value;\n }\n\n private currentUrlHasRedirectingParam(): boolean {\n return PENDING_REDIRECT_PARAM in this.getCurrentUrl().query;\n }\n\n private getCurrentUrl(): ParsedUrl {\n return parseUrl(window.location.href);\n }\n\n private replaceCurrentUrl(url: string) {\n window.history.replaceState(null, '', url);\n }\n\n private setRedirectingParamOnUrl() {\n if (this.currentUrlHasRedirectingParam()) {\n return;\n }\n\n const currentUrl = this.getCurrentUrl();\n const updatedUrl = {\n ...currentUrl,\n query: {\n ...currentUrl.query,\n [PENDING_REDIRECT_PARAM]: 'true',\n },\n };\n\n this.replaceCurrentUrl(stringifyUrl(updatedUrl));\n }\n\n private removeRedirectingParamFromUrl() {\n if (!this.currentUrlHasRedirectingParam()) {\n return;\n }\n\n this.replaceCurrentUrl(exclude(window.location.href, [PENDING_REDIRECT_PARAM]));\n }\n}\n","export enum SubStrategyType {\n CARD = 'card_ui',\n NONE = 'none',\n UNSUPPORTED = 'unsupported',\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { overSome } from 'lodash';\n\nimport { PaymentHumanVerificationHandler } from '../../../../../spam-protection';\nimport PaymentAdditionalAction from '../../../../payment-additional-action';\nimport { PaymentsAPIResponse } from '../../ppsdk-payments-api-response';\n\nimport {\n handleHumanVerification,\n HumanVerification,\n isHumanVerification,\n} from './human-verification';\nimport { handleRedirect, isRedirect, Redirect } from './redirect';\n\nexport type Continue = Redirect | HumanVerification;\n\nconst isAnyContinue = overSome([isRedirect, isHumanVerification]);\n\nexport const isContinue = (body: PaymentsAPIResponse['body']): body is Continue =>\n isAnyContinue(body);\n\nexport interface ContinueCallbacks {\n humanVerification?(additionalAction: PaymentAdditionalAction): Promise;\n}\n\nexport class ContinueHandler {\n constructor(\n private _formPoster: FormPoster,\n private _humanVerificationHandler: PaymentHumanVerificationHandler,\n ) {}\n\n handle(body: Continue, callbacks?: ContinueCallbacks): Promise {\n switch (body.code) {\n case 'redirect':\n return handleRedirect(body.parameters, this._formPoster);\n\n case 'resubmit_with_human_verification':\n return handleHumanVerification(\n body.parameters,\n this._humanVerificationHandler,\n callbacks?.humanVerification,\n );\n }\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { get, isObject, isString, isUndefined, noop } from 'lodash';\n\nimport { PaymentMethodCancelledError } from '../../../../../errors';\nimport { PaymentsAPIResponse } from '../../../ppsdk-payments-api-response';\n\nimport { RedirectionState } from './RedirectionState';\n\ninterface Parameters {\n url: string;\n form_fields?: Record;\n}\n\nexport interface Redirect {\n type: 'continue';\n code: 'redirect';\n parameters: Parameters;\n}\n\nconst isParameters = (x: unknown): x is Parameters => {\n const formFields = get(x, 'form_fields');\n\n return isString(get(x, 'url')) && (isUndefined(formFields) || isObject(formFields));\n};\n\nexport const isRedirect = (body: PaymentsAPIResponse['body']): body is Redirect =>\n get(body, 'type') === 'continue' &&\n get(body, 'code') === 'redirect' &&\n isParameters(get(body, 'parameters'));\n\nexport const handleRedirect = (\n { url, form_fields }: Parameters,\n formPoster: FormPoster,\n): Promise => {\n const redirectionState = new RedirectionState();\n\n if (redirectionState.isRedirecting()) {\n redirectionState.setRedirecting(false);\n\n return Promise.reject(new PaymentMethodCancelledError());\n }\n\n redirectionState.setRedirecting(true);\n\n if (form_fields) {\n formPoster.postForm(url, form_fields);\n } else {\n window.location.assign(url);\n }\n\n return new Promise(noop);\n};\n","import { get, isArray } from 'lodash';\n\nimport { PaymentHumanVerificationHandler } from '../../../../../../spam-protection';\nimport PaymentAdditionalAction from '../../../../../payment-additional-action';\nimport { PaymentsAPIResponse } from '../../../ppsdk-payments-api-response';\n\ninterface VerificationMethod {\n id: string;\n parameters: Record;\n}\n\ninterface Parameters {\n available_methods: VerificationMethod[];\n}\n\nexport interface HumanVerification {\n type: 'continue';\n code: 'resubmit_with_human_verification';\n parameters: Parameters;\n}\n\nconst isParameters = (x: unknown): x is Parameters => {\n const availableMethods = get(x, 'available_methods');\n\n return isArray(availableMethods);\n};\n\nexport const isHumanVerification = (body: PaymentsAPIResponse['body']): body is HumanVerification =>\n get(body, 'type') === 'continue' &&\n get(body, 'code') === 'resubmit_with_human_verification' &&\n isParameters(get(body, 'parameters'));\n\nexport const handleHumanVerification = async (\n { available_methods }: Parameters,\n humanVerificationHandler?: PaymentHumanVerificationHandler,\n callback?: (additionalAction: PaymentAdditionalAction) => Promise,\n): Promise => {\n if (!callback) {\n throw new Error('PPSDK human verification callback function is missing.');\n }\n\n if (!humanVerificationHandler) {\n throw new Error('PPSDK human verification handler is missing.');\n }\n\n if (available_methods.length === 0) {\n throw Error('Human verification method is missing.');\n }\n\n // Only one method is expected because google recaptcha only is supported\n const { id, parameters } = available_methods[0];\n\n const additionalAction: PaymentAdditionalAction = await humanVerificationHandler.handle(\n id,\n parameters.key,\n );\n\n return callback(additionalAction);\n};\n","import { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\n\nimport { ContinueCallbacks, ContinueHandler, isContinue } from './continue-handler';\nimport { handleError, isError } from './error';\nimport { handleFailure, isFailure } from './failure';\nimport { handleSuccess, isSuccess } from './success';\nimport { handleUnsupported } from './unsupported';\n\ninterface StepHandlerCallbacks {\n continue?: ContinueCallbacks;\n}\n\nexport class StepHandler {\n constructor(private _continueHandler: ContinueHandler) {}\n\n handle(response: PaymentsAPIResponse, callbacks?: StepHandlerCallbacks): Promise {\n const { body } = response;\n\n if (isSuccess(body)) {\n return handleSuccess();\n }\n\n if (isContinue(body)) {\n return this._continueHandler.handle(body, callbacks?.continue);\n }\n\n if (isFailure(response)) {\n return handleFailure(response);\n }\n\n if (isError(response)) {\n return handleError(response);\n }\n\n return handleUnsupported(response);\n }\n}\n","import { get } from 'lodash';\n\nimport { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\n\nexport interface Success {\n type: 'success';\n}\n\nexport const isSuccess = (body: PaymentsAPIResponse['body']): body is Success =>\n get(body, 'type') === 'success';\n\nexport const handleSuccess = () => Promise.resolve();\n","import { get, isString } from 'lodash';\n\nimport { RequestError } from '../../../../common/error/errors';\nimport { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\n\nexport interface FailureResponse extends PaymentsAPIResponse {\n body: {\n type: 'failure';\n code: string;\n };\n}\n\nexport const isFailure = (response: PaymentsAPIResponse): response is FailureResponse =>\n get(response.body, 'type') === 'failure' && isString(get(response.body, 'code'));\n\nconst toRequestErrorFormat = (failureResponse: FailureResponse) => ({\n ...failureResponse,\n body: {\n errors: [{ code: failureResponse.body.code }],\n },\n});\n\nexport const handleFailure = (response: FailureResponse): Promise =>\n Promise.reject(new RequestError(toRequestErrorFormat(response)));\n","import { get } from 'lodash';\n\nimport { RequestError } from '../../../../common/error/errors';\nimport { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\n\nexport interface ErrorResponse extends PaymentsAPIResponse {\n body: {\n type: 'error';\n };\n}\n\nexport const isError = (response: PaymentsAPIResponse): response is ErrorResponse =>\n get(response.body, 'type') === 'error';\n\nexport const handleError = (response: ErrorResponse) => Promise.reject(new RequestError(response));\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { PaymentHumanVerificationHandler } from '../../../../spam-protection';\n\nimport { ContinueHandler } from './continue-handler';\nimport { StepHandler } from './step-handler';\n\nexport const createStepHandler = (\n formPoster: FormPoster,\n humanVerificationHandler: PaymentHumanVerificationHandler,\n) => new StepHandler(new ContinueHandler(formPoster, humanVerificationHandler));\n","import { BrowserStorage } from '../../../common/storage';\n\ntype CompletedPayments = string[];\n\nconst COMPLETED_PAYMENTS_KEY = 'completed-payments';\n\nexport class PPSDKCompletedPayments {\n constructor(private _browserStorage: BrowserStorage) {}\n\n isCompleted(paymentId: string): boolean {\n return this.getCompletedPayments().indexOf(paymentId) >= 0;\n }\n\n setCompleted(paymentId: string): void {\n const completedPayments = this.getCompletedPayments();\n\n completedPayments.push(paymentId);\n\n this.setCompletedPayments(completedPayments);\n }\n\n private getCompletedPayments(): CompletedPayments {\n return this._browserStorage.getItem(COMPLETED_PAYMENTS_KEY) || [];\n }\n\n private setCompletedPayments(completedPayments: CompletedPayments): void {\n this._browserStorage.setItem(COMPLETED_PAYMENTS_KEY, completedPayments);\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { BrowserStorage } from '../../../common/storage';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport { getPPSDKMethod } from './get-ppsdk-payment-method';\nimport { PPSDKCompletedPayments } from './ppsdk-completed-payments';\nimport { PaymentResumer } from './ppsdk-payment-resumer';\nimport { SubStrategy } from './ppsdk-sub-strategy';\nimport { SubStrategyRegistry } from './ppsdk-sub-strategy-registry';\n\nexport class PPSDKStrategy implements PaymentStrategy {\n private _subStrategy?: SubStrategy;\n private _completedPayments: PPSDKCompletedPayments;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _subStrategyRegistry: SubStrategyRegistry,\n private _paymentResumer: PaymentResumer,\n browserStorage: BrowserStorage,\n ) {\n this._completedPayments = new PPSDKCompletedPayments(browserStorage);\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { bigpayBaseUrl } = this._store\n .getState()\n .config.getStoreConfigOrThrow().paymentSettings;\n\n if (!options?.methodId) {\n throw new InvalidArgumentError(\n 'Unable to submit payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n const { methodId } = options;\n const { payment, ...order } = payload;\n const { _subStrategy: subStrategy } = this;\n\n if (!subStrategy) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n const token = this._store.getState().order.getOrderMeta()?.token;\n\n if (!token) {\n throw new MissingDataError(MissingDataErrorType.MissingOrder);\n }\n\n await subStrategy.execute({ methodId, payment, bigpayBaseUrl, token });\n\n return this._store.getState();\n }\n\n async finalize(options?: PaymentRequestOptions): Promise {\n const order = this._store.getState().order.getOrderOrThrow();\n\n if (order.isComplete) {\n return this._store.getState();\n }\n\n const { bigpayBaseUrl } = this._store\n .getState()\n .config.getStoreConfigOrThrow().paymentSettings;\n\n if (!options?.methodId) {\n throw new InvalidArgumentError(\n 'Unable to submit payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n const paymentId = this._store.getState().order.getPaymentId(options.methodId);\n\n if (!paymentId || !order || this._completedPayments.isCompleted(paymentId)) {\n throw new OrderFinalizationNotRequiredError();\n }\n\n const { orderId } = order;\n\n await this._paymentResumer.resume({ paymentId, bigpayBaseUrl, orderId }).catch((error) => {\n this._completedPayments.setCompleted(paymentId);\n throw error;\n });\n\n return this._store.getState();\n }\n\n async initialize(options?: PaymentInitializeOptions): Promise {\n if (!options?.methodId) {\n throw new InvalidArgumentError(\n 'Unable to submit payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n const paymentMethod = getPPSDKMethod(this._store, options.methodId);\n\n if (!paymentMethod) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._subStrategy = this._subStrategyRegistry.getByMethod(paymentMethod);\n\n if (!this._subStrategy) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n await this._subStrategy.initialize(options);\n\n return this._store.getState();\n }\n\n async deinitialize(_options?: PaymentRequestOptions): Promise {\n this._subStrategy?.deinitialize();\n\n return this._store.getState();\n }\n}\n","import { CheckoutStore } from '../../../checkout';\nimport { isPPSDKPaymentMethod, PPSDKPaymentMethod } from '../../ppsdk-payment-method';\n\ntype GetPPSDKMethod = (store: CheckoutStore, methodId: string) => PPSDKPaymentMethod | undefined;\n\nexport const getPPSDKMethod: GetPPSDKMethod = (store, methodId) => {\n const paymentMethod = store.getState().paymentMethods.getPaymentMethod(methodId);\n\n if (!paymentMethod || !isPPSDKPaymentMethod(paymentMethod)) {\n return;\n }\n\n return paymentMethod;\n};\n","import { cond, constant, stubTrue } from 'lodash';\n\nimport { Registry } from '../../../common/registry';\nimport { PPSDKPaymentMethod } from '../../ppsdk-payment-method';\n\nimport { isCard, isNone } from './initialization-strategies';\nimport { SubStrategy } from './ppsdk-sub-strategy';\nimport { SubStrategyType } from './ppsdk-sub-strategy-type';\n\nconst getToken = cond([\n [isCard, constant(SubStrategyType.CARD)],\n [isNone, constant(SubStrategyType.NONE)],\n [stubTrue, constant(SubStrategyType.UNSUPPORTED)],\n]);\n\nexport class SubStrategyRegistry extends Registry {\n getByMethod(paymentMethod: PPSDKPaymentMethod): SubStrategy | undefined {\n const token = getToken(paymentMethod.initializationStrategy);\n\n return this.get(token);\n }\n}\n","import { InitializationStrategy } from '../../../';\n\ninterface Card {\n type: 'card_ui';\n}\n\nexport const isCard = (strategy: Pick): strategy is Card =>\n strategy.type === 'card_ui';\n","import { InitializationStrategy } from '../../../';\n\ninterface None {\n type: 'none';\n}\n\nexport const isNone = (strategy: Pick): strategy is None =>\n strategy.type === 'none';\n","import { CheckoutStore } from '../../../../checkout';\nimport {\n InvalidArgumentError,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../../common/error/errors';\nimport { HostedForm, HostedFormFactory } from '../../../../hosted-form';\nimport { OrderActionCreator } from '../../../../order';\nimport { PaymentArgumentInvalidError } from '../../../errors';\nimport PaymentAdditionalAction from '../../../payment-additional-action';\nimport { PaymentInitializeOptions } from '../../../payment-request-options';\nimport { SubStrategy, SubStrategySettings } from '../ppsdk-sub-strategy';\nimport { StepHandler } from '../step-handler';\n\nexport class CardSubStrategy implements SubStrategy {\n protected _hostedForm?: HostedForm;\n\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _hostedFormFactory: HostedFormFactory,\n private _ppsdkStepHandler: StepHandler,\n ) {}\n\n async execute(settings: SubStrategySettings): Promise {\n const form = this._hostedForm;\n\n if (!form) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { additionalAction, payment } = settings;\n\n if (!payment || !payment.methodId) {\n throw new PaymentArgumentInvalidError(['payment.methodId']);\n }\n\n await form.validate();\n\n const { payload } = await form.submit(payment, additionalAction);\n\n const { response } = payload;\n\n const humanVerificationCallback = async (\n additionalAction: PaymentAdditionalAction,\n ): Promise => this.execute({ additionalAction, ...settings });\n\n await this._ppsdkStepHandler.handle(response, {\n continue: {\n humanVerification: humanVerificationCallback,\n },\n });\n\n await this._store.dispatch(this._orderActionCreator.loadCurrentOrder());\n }\n\n async initialize(options?: PaymentInitializeOptions): Promise {\n const formOptions = options && options.creditCard && options.creditCard.form;\n const { config } = this._store.getState();\n const { paymentSettings: { bigpayBaseUrl: host = '' } = {} } =\n config.getStoreConfig() || {};\n\n if (!formOptions) {\n throw new InvalidArgumentError();\n }\n\n const form = formOptions && this._hostedFormFactory.create(host, formOptions);\n\n await form.attach();\n\n this._hostedForm = form;\n }\n\n deinitialize(): void {\n if (this._hostedForm) {\n this._hostedForm.detach();\n }\n }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { PaymentsAPIResponse } from '../ppsdk-payments-api-response';\nimport { SubStrategy, SubStrategySettings } from '../ppsdk-sub-strategy';\nimport { StepHandler } from '../step-handler';\n\nexport class NoneSubStrategy implements SubStrategy {\n constructor(private _requestSender: RequestSender, private _stepHandler: StepHandler) {}\n\n execute({ methodId, bigpayBaseUrl, token }: SubStrategySettings): Promise {\n const body = { payment_method_id: methodId };\n const options = {\n credentials: false,\n body,\n headers: {\n authorization: token,\n 'X-XSRF-TOKEN': null,\n },\n };\n\n return this._requestSender\n .post(`${bigpayBaseUrl}/payments`, options)\n .then((response) => this._stepHandler.handle(response));\n }\n\n initialize(): Promise {\n return Promise.resolve();\n }\n\n deinitialize(): void {}\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { CheckoutStore } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator } from '../../../order';\n\nimport { SubStrategyRegistry } from './ppsdk-sub-strategy-registry';\nimport { SubStrategyType } from './ppsdk-sub-strategy-type';\nimport { StepHandler } from './step-handler';\nimport { CardSubStrategy, NoneSubStrategy } from './sub-strategies';\n\nexport const createSubStrategyRegistry = (\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n requestSender: RequestSender,\n stepHandler: StepHandler,\n hostedFormFactory: HostedFormFactory,\n) => {\n const registry = new SubStrategyRegistry();\n\n registry.register(\n SubStrategyType.CARD,\n () => new CardSubStrategy(store, orderActionCreator, hostedFormFactory, stepHandler),\n );\n\n registry.register(SubStrategyType.NONE, () => new NoneSubStrategy(requestSender, stepHandler));\n\n registry.register(SubStrategyType.UNSUPPORTED, () => undefined);\n\n return registry;\n};\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\n\nimport { PaymentsAPIResponse } from './ppsdk-payments-api-response';\nimport { StepHandler } from './step-handler';\n\ninterface ResumeSettings {\n orderId: number;\n paymentId: string;\n bigpayBaseUrl: string;\n}\n\nexport class PaymentResumer {\n constructor(private _requestSender: RequestSender, private _stepHandler: StepHandler) {}\n\n async resume({ paymentId, bigpayBaseUrl, orderId }: ResumeSettings): Promise {\n const token = await this._getToken(orderId).catch(() => {\n throw new OrderFinalizationNotRequiredError();\n });\n\n const options = {\n credentials: false,\n headers: {\n authorization: token,\n 'X-XSRF-TOKEN': null,\n },\n };\n\n return this._requestSender\n .get(`${bigpayBaseUrl}/payments/${paymentId}`, options)\n .then((response) => this._stepHandler.handle(response));\n }\n\n private async _getToken(orderId: number): Promise {\n const url = `/api/storefront/payments/auth-token`;\n const options = {\n params: {\n order_id: orderId,\n },\n };\n\n return this._requestSender\n .get<{ auth_token: string }>(url, options)\n .then(({ body }) => body.auth_token);\n }\n}\n","import { noop } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { MissingDataError, MissingDataErrorType, RequestError } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport { StoreCreditActionCreator } from '../../../store-credit';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport StorefrontPaymentRequestSender from '../../storefront-payment-request-sender';\nimport PaymentStrategy from '../payment-strategy';\n\nexport default class QuadpayPaymentStrategy implements PaymentStrategy {\n constructor(\n private _store: CheckoutStore,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _storeCreditActionCreator: StoreCreditActionCreator,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n private _storefrontPaymentRequestSender: StorefrontPaymentRequestSender,\n ) {}\n\n initialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId } = payment;\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId, options),\n );\n const { clientToken, initializationData: { redirectUrl } = {} } =\n getPaymentMethodOrThrow(methodId);\n\n if (!clientToken || !redirectUrl) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { id: nonce } = JSON.parse(clientToken);\n\n if (!nonce) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n const paymentPayload = {\n methodId,\n paymentData: { nonce },\n };\n\n const { isStoreCreditApplied: useStoreCredit } = this._store\n .getState()\n .checkout.getCheckoutOrThrow();\n\n await this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(useStoreCredit));\n await this._store.dispatch(\n this._remoteCheckoutActionCreator.initializePayment(methodId, { useStoreCredit }),\n );\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n await this._prepareForReferredRegistration(methodId, nonce);\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentPayload),\n );\n } catch (error) {\n if (\n error instanceof RequestError &&\n error.body.status === 'additional_action_required'\n ) {\n window.location.replace(redirectUrl);\n\n return new Promise(noop);\n }\n\n throw error;\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n private _prepareForReferredRegistration(methodId: string, externalId: string): Promise {\n return this._storefrontPaymentRequestSender.saveExternalId(methodId, externalId);\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { some } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { getBrowserInfo } from '../../../common/browser-info';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport * as paymentStatusTypes from '../../payment-status-types';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nexport default class SagePayPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _formPoster: FormPoster,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment } = payload;\n\n if (!payment) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { paymentData } = payment;\n\n if (!paymentData) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n if (this._isThreeDSTwoExperimentOn()) {\n const newPaymentData = {\n ...paymentData,\n browser_info: getBrowserInfo(),\n };\n\n if (payload.payment) {\n payload.payment.paymentData = newPaymentData;\n }\n }\n\n return super.execute(payload, options).catch((error: Error) => {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return Promise.reject(error);\n }\n\n return new Promise(() => {\n let payload;\n\n if (this._isThreeDSTwoExperimentOn() && !error.body.three_ds_result.merchant_data) {\n payload = {\n creq: error.body.three_ds_result.payer_auth_request,\n };\n } else {\n payload = {\n PaReq: error.body.three_ds_result.payer_auth_request,\n TermUrl: error.body.three_ds_result.callback_url,\n MD: error.body.three_ds_result.merchant_data,\n };\n }\n\n this._formPoster.postForm(\n error.body.three_ds_result.acs_url,\n payload,\n undefined,\n '_top',\n );\n });\n });\n }\n\n finalize(options?: PaymentRequestOptions): Promise {\n const state = this._store.getState();\n const order = state.order.getOrder();\n\n if (order && state.payment.getPaymentStatus() === paymentStatusTypes.FINALIZE) {\n return this._store.dispatch(\n this._orderActionCreator.finalizeOrder(order.orderId, options),\n );\n }\n\n return super.finalize(options);\n }\n\n private _isThreeDSTwoExperimentOn(): boolean {\n return (\n this._store.getState().config.getStoreConfigOrThrow().checkoutSettings.features[\n 'INT-4994.Opayo_3DS2'\n ] === true\n );\n }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport RequestError from './request-error';\n\n/**\n * Throw this error if a request fails to complete within its required timeframe\n * because of a network issue.\n */\nexport default class TimeoutError extends RequestError {\n constructor(response?: Response) {\n super(response, {\n message: 'The request has timed out or aborted.',\n });\n\n this.name = 'TimeoutError';\n this.type = 'timeout';\n }\n}\n","import { NonceInstrument } from '../../payment';\n\nexport default interface SquarePaymentForm {\n build(): void;\n requestCardNonce(): void;\n setPostalCode(postalCode: string): void;\n verifyBuyer(\n source?: string,\n verificationDetails?: VerificationDetails,\n callback?: VerifyBuyerResponse,\n ): void;\n}\n\nexport type VerifyBuyerResponse = (\n errors: SquareVerificationError,\n verificationResult: SquareVerificationResult,\n) => void;\n\nexport interface SquareVerificationError {\n type: string;\n message: string;\n}\n\nexport interface SquareVerificationResult {\n token: string;\n userChallenged: boolean;\n}\n\nexport enum SquareIntent {\n CHARGE = 'CHARGE',\n STORE = 'STORE',\n}\n\nexport interface VerificationDetails {\n intent: string;\n amount?: string;\n currencyCode?: string;\n billingContact?: Contact;\n}\n\nexport type SquarePaymentFormConstructor = new (options: SquareFormOptions) => SquarePaymentForm;\n\nexport type SquareScriptCallBack = (options: SquareFormOptions) => SquarePaymentForm;\n\nexport interface SquareFormOptions {\n applicationId: string;\n env: string;\n locationId: string;\n inputClass?: string;\n inputStyles?: string[];\n callbacks?: SquareFormCallbacks;\n cardNumber: SquareFormElement;\n cvv: SquareFormElement;\n expirationDate: SquareFormElement;\n postalCode: SquareFormElement;\n}\nexport interface LineItem {\n label: string;\n amount: string;\n pending: boolean;\n}\n\nexport interface SquarePaymentRequest {\n requestShippingAddress: boolean;\n requestBillingInfo: boolean;\n shippingContact?: Contact;\n countryCode: string;\n currencyCode: string;\n lineItems?: LineItem[];\n total: LineItem;\n}\n\nexport interface NonceGenerationError {\n type: string;\n message: string;\n field: string;\n}\n\nexport interface CardData {\n card_brand: CardBrand;\n last_4: number;\n exp_month: number;\n exp_year: number;\n billing_postal_code: string;\n digital_wallet_type: DigitalWalletType;\n}\n\nexport interface Contact {\n familyName: string;\n givenName: string;\n email: string;\n country: string;\n countryName: string;\n region: string;\n city: string;\n addressLines: string[];\n postalCode: string;\n phone: string;\n}\n\nexport enum CardBrand {\n americanExpress = 'AMERICAN_EXPRESS',\n discover = 'DISCOVER',\n discoverDiners = 'DISCOVER_DINERS',\n JCB = 'JCB',\n masterCard = 'MASTERCARD',\n unionPay = 'CHINA_UNIONPAY',\n unknown = 'OTHER_BRAND',\n visa = 'VISA',\n squareGift = 'SQUARE_GIFT_CARD',\n}\n\nexport enum DigitalWalletType {\n applePay = 'APPLEPAY',\n none = 'NONE',\n}\n\n/**\n * Configures any form element provided by Square payment.\n */\nexport interface SquareFormElement {\n /**\n * The ID of the container which the form element should insert into.\n */\n elementId: string;\n\n /**\n * The placeholder text to use for the form element, if provided.\n */\n placeholder?: string;\n}\n\nexport interface SquareFormCallbacks {\n paymentFormLoaded?(form: SquarePaymentForm): void;\n unsupportedBrowserDetected?(): void;\n cardNonceResponseReceived?(\n errors?: NonceGenerationError[],\n nonce?: string,\n cardData?: CardData,\n billingContact?: Contact,\n shippingContact?: Contact,\n ): void;\n methodsSupported?(methods: { [key: string]: boolean }): void;\n createPaymentRequest?(): void;\n}\n\nexport type SquareFormFactory = (options: SquareFormOptions) => SquarePaymentForm;\n\nexport interface DeferredPromise {\n resolve(resolution?: SquareNonceInstrument): void;\n reject(reason?: any): void;\n}\n\nexport interface SquareNonceInstrument extends NonceInstrument {\n token?: string;\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\nimport { get, isEmpty, noop, omit } from 'lodash';\n\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n TimeoutError,\n UnsupportedBrowserError,\n} from '../../../common/error/errors';\nimport { SDK_VERSION_HEADERS } from '../../../common/http-request';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { PaymentMethodClientUnavailableError } from '../../errors';\nimport { NonceInstrument } from '../../payment';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategyActionCreator from '../../payment-strategy-action-creator';\nimport PaymentStrategy from '../payment-strategy';\n\nimport SquarePaymentForm, {\n CardData,\n Contact,\n DeferredPromise,\n DigitalWalletType,\n SquareFormOptions,\n SquareIntent,\n SquarePaymentRequest,\n SquareVerificationError,\n SquareVerificationResult,\n VerificationDetails,\n} from './square-form';\nimport SquarePaymentInitializeOptions from './square-payment-initialize-options';\nimport SquareScriptLoader from './square-script-loader';\n\nexport default class SquarePaymentStrategy implements PaymentStrategy {\n private _deferredRequestNonce?: DeferredPromise;\n private _paymentForm?: SquarePaymentForm;\n private _paymentMethod?: PaymentMethod;\n private _squareOptions?: SquarePaymentInitializeOptions;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _orderActionCreator: OrderActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentStrategyActionCreator: PaymentStrategyActionCreator,\n private _requestSender: RequestSender,\n private _scriptLoader: SquareScriptLoader,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const { methodId, gatewayId, square: squareOptions } = options;\n\n if (!squareOptions) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"options.square\" argument is not provided.',\n );\n }\n\n this._squareOptions = squareOptions;\n\n this._syncPaymentMethod(methodId);\n\n /* eslint-disable */\n return new Promise(async (resolve, reject) => {\n const state = this._store.getState();\n const { config: { testMode } } = state.paymentMethods.getPaymentMethodOrThrow(methodId, gatewayId);\n try {\n const createSquareForm = await this._scriptLoader.load(testMode);\n\n this._paymentForm = createSquareForm(\n this._getFormOptions({ resolve, reject })\n );\n\n this._getPaymentForm().build();\n } catch (e: unknown) {\n reject(new PaymentMethodClientUnavailableError());\n }\n }).then(() => this._store.getState());\n }\n\n async execute(orderRequest: OrderRequestBody, options?: PaymentRequestOptions): Promise {\n const { payment } = orderRequest;\n if (!payment || !payment.methodId) {\n throw new InvalidArgumentError('Unable to submit payment because \"payload.payment.methodId\" argument is not provided.');\n }\n\n this._syncPaymentMethod(payment.methodId);\n\n const paymentData = await this._getNonceInstrument(payment.methodId);\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(omit(orderRequest, 'payment'), options));\n await this._store.dispatch(this._paymentActionCreator.submitPayment({ ...payment, paymentData}));\n\n return this._store.getState();\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n private _syncPaymentMethod(methodId: string): void {\n const state = this._store.getState();\n this._paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n if (!this._paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n }\n\n private _getCountryCode(countryName: string) {\n switch (countryName.toUpperCase()) {\n case 'NEW ZELAND':\n return 'NZ';\n case 'AUSTRALIA':\n return 'AU';\n default:\n return 'US';\n }\n }\n\n private _getNonceInstrument(methodId: string): Promise {\n const state = this._store.getState();\n const paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n if (paymentMethod) {\n const { initializationData } = paymentMethod;\n if (initializationData && initializationData.paymentData.nonce) {\n return Promise.resolve({ nonce: paymentMethod.initializationData.paymentData.nonce });\n }\n }\n\n return new Promise((resolve, reject?) => {\n if (this._deferredRequestNonce) {\n this._deferredRequestNonce.reject(new TimeoutError());\n }\n\n this._deferredRequestNonce = { resolve, reject };\n this._getPaymentForm().requestCardNonce();\n });\n }\n\n private _getFormOptions(deferred: DeferredPromise): SquareFormOptions {\n return {\n ...this._getInitializeOptions(),\n ...this._paymentMethod?.initializationData,\n callbacks: {\n cardNonceResponseReceived: (errors, nonce, cardData, billingContact, shippingContact) => {\n const deferredRequest = this._getDeferredRequestNonce();\n const { onError = noop } = this._getInitializeOptions();\n\n if (!nonce) {\n onError(errors);\n\n return deferredRequest.reject(get(errors, '0', {}));\n }\n\n if (cardData && cardData.digital_wallet_type !== DigitalWalletType.none && nonce) {\n this._handleWalletNonceResponse(nonce, cardData, billingContact, shippingContact);\n } else {\n if (this._is3DSExperimentOn()) {\n this._getPaymentForm().verifyBuyer(\n nonce,\n this._getVerificationDetails(),\n (error: SquareVerificationError, verificationResults: SquareVerificationResult) => {\n\n if (!isEmpty(error)) {\n onError(error);\n\n return deferredRequest.reject(get(error, '0', {}));\n }\n\n deferredRequest.resolve({ nonce: JSON.stringify({ nonce, token: verificationResults.token }) });\n }\n );\n } else {\n deferredRequest.resolve({ nonce });\n }\n }\n },\n createPaymentRequest: this._paymentRequestPayload.bind(this),\n paymentFormLoaded: () => {\n deferred.resolve();\n this._setPostalCode();\n },\n unsupportedBrowserDetected: () => deferred.reject(new UnsupportedBrowserError()),\n },\n };\n }\n\n private _getInitializeOptions(): SquarePaymentInitializeOptions {\n if (!this._squareOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._squareOptions;\n }\n\n private _handleWalletNonceResponse(\n nonce?: string,\n cardData?: CardData,\n billingContact?: Contact,\n shippingContact?: Contact\n ): void {\n const { onError = noop, onPaymentSelect = noop } = this._getInitializeOptions();\n\n if (nonce && this._paymentMethod) {\n this._paymentInstrumentSelected(\n this._paymentMethod.id,\n nonce,\n cardData,\n billingContact,\n shippingContact\n )\n .then(onPaymentSelect)\n .catch(onError);\n }\n }\n\n private _paymentInstrumentSelected(\n methodId: string,\n nonce?: string,\n cardData?: CardData,\n billingContact?: Contact,\n shippingContact?: Contact): Promise {\n\n return this._store.dispatch(this._paymentStrategyActionCreator.widgetInteraction(() => {\n return this._setExternalCheckoutData(nonce, cardData, billingContact, shippingContact)\n .then(() =>\n Promise.all([\n this._store.dispatch(this._checkoutActionCreator.loadCurrentCheckout()),\n this._store.dispatch(this._paymentMethodActionCreator.loadPaymentMethod(methodId)),\n ]));\n }, { methodId }), { queueId: 'widgetInteraction' });\n }\n\n private _paymentRequestPayload(): SquarePaymentRequest {\n const state = this._store.getState();\n const checkout = state.checkout.getCheckout();\n const storeConfig = state.config.getStoreConfigOrThrow();\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n return {\n requestShippingAddress: true,\n requestBillingInfo: true,\n currencyCode: storeConfig.currency.code,\n countryCode: this._getCountryCode(storeConfig.storeProfile.storeCountry),\n total: {\n label: storeConfig.storeProfile.storeName,\n amount: String(checkout.subtotal),\n pending: false,\n },\n };\n }\n\n private _setExternalCheckoutData(nonce?: string, cardData?: CardData, billingContact?: Contact, shippingContact?: Contact): Promise> {\n return this._requestSender.post('/checkout.php', {\n headers: {\n Accept: 'text/html',\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...SDK_VERSION_HEADERS,\n },\n body: {\n nonce,\n provider: 'squarev2',\n action: 'set_external_checkout',\n cardData: JSON.stringify(cardData),\n billingContact: JSON.stringify(billingContact),\n shippingContact: JSON.stringify(shippingContact),\n },\n });\n }\n\n private _setPostalCode(): void {\n const state = this._store.getState();\n const billingAddress = state.billingAddress.getBillingAddress();\n\n if (billingAddress && billingAddress.postalCode) {\n this._getPaymentForm().setPostalCode(billingAddress.postalCode);\n }\n }\n\n private _getBillingContact(): Contact {\n const state = this._store.getState();\n const billingAddress = state.billingAddress.getBillingAddressOrThrow();\n\n return {\n givenName: billingAddress.firstName,\n familyName: billingAddress.lastName,\n email: billingAddress.email || '',\n country: billingAddress.countryCode,\n countryName: billingAddress.country,\n region: '',\n city: billingAddress.city,\n postalCode: billingAddress.postalCode,\n addressLines: [ billingAddress.address1, billingAddress.address2],\n phone: billingAddress.phone,\n };\n }\n\n private _getAmountAndCurrencyCode(): string[] {\n const state = this._store.getState();\n const cart = state.cart.getCartOrThrow();\n const checkout = state.checkout.getCheckoutOrThrow();\n\n return [String(checkout.grandTotal), cart.currency.code];\n }\n\n private _getVerificationDetails(): VerificationDetails {\n const billingContact = this._getBillingContact();\n const [ amount, currencyCode ] = this._getAmountAndCurrencyCode();\n\n return {\n intent: SquareIntent.CHARGE,\n currencyCode,\n amount,\n billingContact,\n };\n }\n\n private _getDeferredRequestNonce(): DeferredPromise {\n if (!this._deferredRequestNonce) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._deferredRequestNonce;\n }\n\n private _getPaymentForm(): SquarePaymentForm {\n if (!this._paymentForm) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._paymentForm;\n }\n\n private _is3DSExperimentOn(): boolean {\n const state = this._store.getState();\n const storeConfig = state.config.getStoreConfigOrThrow();\n\n return storeConfig.checkoutSettings.features['PROJECT-3828.add_3ds_support_on_squarev2'] === true;\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport SquarePaymentForm, { SquareFormOptions, SquareScriptCallBack } from './square-form';\nimport SquareWindow from './square-window';\n\nexport default class SquareScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, private _window: Window = window) {}\n\n _isSquareWindow(window: Window): window is SquareWindow {\n const squareWindow: SquareWindow = window as SquareWindow;\n\n return !!squareWindow.SqPaymentForm;\n }\n\n async load(testmode?: boolean): Promise {\n await this._scriptLoader.loadScript(\n testmode\n ? '//js.squareupsandbox.com/v2/paymentform'\n : '//js.squareup.com/v2/paymentform',\n );\n\n return (options: SquareFormOptions): SquarePaymentForm => {\n if (!this._isSquareWindow(this._window)) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return new this._window.SqPaymentForm(options);\n };\n }\n}\n","export const supportedLocales: { [language: string]: string[] } = {\n ar: ['ar'],\n bg: ['bg'],\n cs: ['cs'],\n da: ['da'],\n de: ['de'],\n el: ['el'],\n en: ['en', 'en-GB'],\n es: ['es', 'es-419'],\n et: ['et'],\n fi: ['fi'],\n fil: ['fil'],\n fr: ['fr', 'fr-CA'],\n he: ['he'],\n hr: ['hr'],\n hu: ['hu'],\n id: ['id'],\n it: ['it'],\n ja: ['ja'],\n ko: ['ko'],\n lt: ['lt'],\n lv: ['lv'],\n ms: ['ms'],\n mt: ['mt'],\n nb: ['nb'],\n nl: ['nl'],\n pl: ['pl'],\n pt: ['pt', 'pt-BR'],\n ro: ['ro'],\n ru: ['ru'],\n sk: ['sk'],\n sl: ['sl'],\n sv: ['sv'],\n th: ['th'],\n tr: ['tr'],\n vi: ['vi'],\n zh: ['zh', 'zh-HK', 'zh-TW'],\n};\n","import { supportedLocales } from './stripe-upe-supported-locales';\n\nexport default function formatLocale(localeLanguage: string): string {\n const [language, country] = localeLanguage.replace(/_/g, '-').toLowerCase().split('-');\n const countryLocales = supportedLocales[language];\n\n if (!countryLocales) {\n return 'auto';\n }\n\n const formattedLocale = country ? `${language}-${country.toUpperCase()}` : language;\n\n return countryLocales.indexOf(formattedLocale) > -1 ? formattedLocale : countryLocales[0];\n}\n","import { includes, some } from 'lodash';\n\nimport { PaymentMethodFailedError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { isHostedInstrumentLike } from '../..';\nimport { Address } from '../../../address';\nimport { BillingAddressActionCreator } from '../../../billing';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { StoreCreditActionCreator } from '../../../store-credit';\nimport { PaymentArgumentInvalidError, PaymentMethodCancelledError } from '../../errors';\nimport isVaultedInstrument from '../../is-vaulted-instrument';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport formatLocale from './format-locale';\nimport {\n AddressOptions,\n StripeConfirmPaymentData,\n StripeElement,\n StripeElements,\n StripeElementType,\n StripeError,\n StripePaymentMethodType,\n StripeStringConstants,\n StripeUPEAppearanceOptions,\n StripeUPEClient,\n} from './stripe-upe';\nimport StripeUPEScriptLoader from './stripe-upe-script-loader';\n\nimport { StripeUPEPaymentInitializeOptions } from './';\n\nconst APM_REDIRECT = [\n StripePaymentMethodType.SOFORT,\n StripePaymentMethodType.EPS,\n StripePaymentMethodType.GRABPAY,\n StripePaymentMethodType.BANCONTACT,\n StripePaymentMethodType.IDEAL,\n StripePaymentMethodType.GIROPAY,\n StripePaymentMethodType.ALIPAY,\n StripePaymentMethodType.KLARNA,\n];\n\nexport default class StripeUPEPaymentStrategy implements PaymentStrategy {\n private _stripeUPEClient?: StripeUPEClient;\n private _stripeElements?: StripeElements;\n private _isMounted = false;\n private _unsubscribe?: () => void;\n private _isDeinitialize?: boolean;\n\n constructor(\n private _store: CheckoutStore,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _orderActionCreator: OrderActionCreator,\n private _stripeScriptLoader: StripeUPEScriptLoader,\n private _storeCreditActionCreator: StoreCreditActionCreator,\n private _billingAddressActionCreator: BillingAddressActionCreator,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const { stripeupe, methodId, gatewayId } = options;\n\n if (!stripeupe?.containerId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"gatewayId\" argument is not provided.',\n );\n }\n\n this._isDeinitialize = false;\n\n this._loadStripeElement(stripeupe, gatewayId, methodId).catch((error) =>\n stripeupe.onError?.(error),\n );\n\n this._unsubscribe = await this._store.subscribe(\n async (_state) => {\n const payment = this._stripeElements?.getElement(StripeElementType.PAYMENT);\n\n if (payment) {\n let error;\n\n await this._store\n .dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n }),\n )\n .catch((err) => (error = err));\n\n if (error) {\n if (this._isMounted) {\n payment.unmount();\n this._isMounted = false;\n }\n\n stripeupe.onError?.(error);\n } else if (!this._isMounted) {\n await this._stripeElements?.fetchUpdates();\n payment.mount(`#${stripeupe.containerId}`);\n this._isMounted = true;\n }\n }\n },\n (state) => {\n const checkout = state.checkout.getCheckout();\n\n return checkout && checkout.outstandingBalance;\n },\n (state) => {\n const checkout = state.checkout.getCheckout();\n\n return checkout && checkout.coupons;\n },\n );\n\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n orderRequest: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = orderRequest;\n\n if (!payment || !payment.paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n if (!this._stripeUPEClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const { paymentData, methodId, gatewayId } = payment;\n const { shouldSaveInstrument = false, shouldSetAsDefaultInstrument = false } =\n isHostedInstrumentLike(paymentData) ? paymentData : {};\n const { isStoreCreditApplied: useStoreCredit } = this._store\n .getState()\n .checkout.getCheckoutOrThrow();\n\n if (useStoreCredit) {\n await this._store.dispatch(\n this._storeCreditActionCreator.applyStoreCredit(useStoreCredit),\n );\n }\n\n if (gatewayId) {\n const {\n customer: { getCustomerOrThrow },\n } = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n }),\n );\n const { email, isStripeLinkAuthenticated } = getCustomerOrThrow();\n\n if (isStripeLinkAuthenticated !== undefined && !email) {\n const billingAddress = this._store\n .getState()\n .billingAddress.getBillingAddressOrThrow();\n\n await this._store.dispatch(\n this._billingAddressActionCreator.updateAddress(billingAddress),\n );\n }\n }\n\n if (isVaultedInstrument(paymentData)) {\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n const { instrumentId } = paymentData;\n\n return this._executeWithVaulted(\n payment.methodId,\n instrumentId,\n shouldSetAsDefaultInstrument,\n );\n }\n\n if (includes(APM_REDIRECT, methodId)) {\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n return this._executeWithAPM(payment.methodId);\n }\n\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n return this._executeWithoutRedirect(\n payment.methodId,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n if (this._unsubscribe) {\n this._unsubscribe();\n }\n\n this._stripeElements?.getElement(StripeElementType.PAYMENT)?.unmount();\n this._isMounted = false;\n this._isDeinitialize = true;\n\n return Promise.resolve(this._store.getState());\n }\n\n private _isCancellationError(stripeError: StripeError | undefined) {\n return (\n stripeError &&\n stripeError.payment_intent.last_payment_error?.message?.indexOf('canceled') !== -1\n );\n }\n\n private _throwDisplayableStripeError(stripeError: StripeError) {\n if (\n includes(['card_error', 'invalid_request_error', 'validation_error'], stripeError.type)\n ) {\n throw new Error(stripeError.message);\n }\n }\n\n private async _executeWithAPM(methodId: string): Promise {\n const paymentMethod = this._store\n .getState()\n .paymentMethods.getPaymentMethodOrThrow(methodId);\n const paymentPayload = {\n methodId,\n paymentData: {\n formattedPayload: {\n credit_card_token: { token: paymentMethod.clientToken },\n vault_payment_instrument: false,\n confirm: false,\n set_as_default_stored_instrument: false,\n },\n },\n };\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentPayload),\n );\n } catch (error) {\n return await this._processAdditionalAction(error);\n }\n }\n\n private async _executeWithoutRedirect(\n methodId: string,\n shouldSaveInstrument: boolean,\n shouldSetAsDefaultInstrument: boolean,\n ): Promise {\n const paymentMethod = this._store\n .getState()\n .paymentMethods.getPaymentMethodOrThrow(methodId);\n const paymentPayload = {\n methodId,\n paymentData: {\n formattedPayload: {\n credit_card_token: { token: paymentMethod.clientToken },\n vault_payment_instrument: shouldSaveInstrument,\n confirm: false,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n },\n },\n };\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentPayload),\n );\n } catch (error) {\n return await this._processAdditionalAction(\n error,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n methodId,\n );\n }\n }\n\n private async _executeWithVaulted(\n methodId: string,\n token: string,\n shouldSetAsDefaultInstrument: boolean,\n ): Promise {\n const paymentMethod = this._store\n .getState()\n .paymentMethods.getPaymentMethodOrThrow(methodId);\n\n try {\n const paymentPayload = {\n methodId,\n paymentData: {\n formattedPayload: {\n bigpay_token: { token },\n confirm: false,\n client_token: paymentMethod.clientToken,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n },\n },\n };\n\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentPayload),\n );\n } catch (error) {\n return await this._processVaultedAdditionalAction(\n error,\n methodId,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n private async _loadStripeElement(\n stripeupe: StripeUPEPaymentInitializeOptions,\n gatewayId: string,\n methodId: string,\n ) {\n const { containerId, style, render } = stripeupe;\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n }),\n );\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n const {\n initializationData: { stripePublishableKey, stripeConnectedAccount, shopperLanguage },\n } = paymentMethod;\n\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._stripeUPEClient = await this._loadStripeJs(\n stripePublishableKey,\n stripeConnectedAccount,\n );\n\n let appearance: StripeUPEAppearanceOptions | undefined;\n\n if (style) {\n const styles = style;\n\n appearance = {\n variables: {\n colorPrimary: styles.fieldInnerShadow,\n colorBackground: styles.fieldBackground,\n colorText: styles.labelText,\n colorDanger: styles.fieldErrorText,\n colorTextSecondary: styles.labelText,\n colorTextPlaceholder: styles.fieldPlaceholderText,\n colorIcon: styles.fieldPlaceholderText,\n },\n rules: {\n '.Input': {\n borderColor: styles.fieldBorder,\n color: styles.fieldText,\n boxShadow: styles.fieldInnerShadow,\n },\n },\n };\n }\n\n this._stripeElements = this._stripeScriptLoader.getElements(this._stripeUPEClient, {\n clientSecret: paymentMethod.clientToken,\n locale: formatLocale(shopperLanguage),\n appearance,\n });\n\n const {\n billingAddress: { getBillingAddress },\n shippingAddress: { getShippingAddress },\n } = state;\n const { postalCode } = getShippingAddress() || getBillingAddress() || {};\n\n const stripeElement: StripeElement =\n this._stripeElements.getElement(StripeElementType.PAYMENT) ||\n this._stripeElements.create(StripeElementType.PAYMENT, {\n fields: {\n billingDetails: {\n email: StripeStringConstants.NEVER,\n address: {\n country: StripeStringConstants.NEVER,\n city: StripeStringConstants.NEVER,\n postalCode: postalCode\n ? StripeStringConstants.NEVER\n : StripeStringConstants.AUTO,\n },\n },\n },\n wallets: {\n applePay: StripeStringConstants.NEVER,\n googlePay: StripeStringConstants.NEVER,\n },\n });\n\n try {\n stripeElement.mount(`#${containerId}`);\n this._isMounted = true;\n } catch (error) {\n if (!this._isDeinitialize) {\n throw new InvalidArgumentError(\n 'Unable to mount Stripe component without valid container ID.',\n );\n }\n }\n\n stripeElement.on('ready', () => {\n render();\n });\n }\n\n private async _processAdditionalAction(\n error: Error,\n shouldSaveInstrument = false,\n shouldSetAsDefaultInstrument = false,\n methodId?: string,\n ): Promise {\n if (!(error instanceof RequestError)) {\n throw error;\n }\n\n if (!this._stripeUPEClient || !this._stripeElements) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (some(error.body.errors, { code: 'additional_action_required' })) {\n const {\n type,\n data: { token, redirect_url },\n } = error.body.additional_action_required;\n\n if (type === 'redirect_to_url' && redirect_url) {\n const { paymentIntent, error: stripeError } =\n await this._stripeUPEClient.confirmPayment(\n this._mapStripePaymentData(redirect_url),\n );\n\n if (stripeError) {\n this._throwDisplayableStripeError(stripeError);\n throw new PaymentMethodFailedError();\n }\n\n if (!paymentIntent) {\n throw new RequestError();\n }\n } else if (methodId && type === 'additional_action_requires_payment_method' && token) {\n let result;\n let catchedConfirmError = false;\n const stripePaymentData = this._mapStripePaymentData();\n\n try {\n result = await this._stripeUPEClient.confirmPayment(stripePaymentData);\n } catch (error) {\n try {\n result = await this._stripeUPEClient.retrievePaymentIntent(token);\n } catch (error) {\n catchedConfirmError = true;\n }\n }\n\n if (result?.error) {\n this._throwDisplayableStripeError(result.error);\n\n if (this._isCancellationError(result.error)) {\n throw new PaymentMethodCancelledError();\n }\n\n throw new PaymentMethodFailedError();\n }\n\n if (!result?.paymentIntent && !catchedConfirmError) {\n throw new RequestError();\n }\n\n const paymentPayload = {\n methodId,\n paymentData: {\n formattedPayload: {\n credit_card_token: {\n token: catchedConfirmError ? token : result?.paymentIntent?.id,\n },\n confirm: false,\n vault_payment_instrument: shouldSaveInstrument,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n },\n },\n };\n\n return this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentPayload),\n );\n }\n }\n\n throw error;\n }\n\n private async _processVaultedAdditionalAction(\n error: Error,\n methodId?: string,\n shouldSetAsDefaultInstrument = false,\n ): Promise {\n if (!(error instanceof RequestError)) {\n throw error;\n }\n\n if (!this._stripeUPEClient || !this._stripeElements) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (some(error.body.errors, { code: 'three_d_secure_required' }) && methodId) {\n const clientSecret = error.body.three_ds_result.token;\n let result;\n let catchedConfirmError = false;\n\n try {\n result = await this._stripeUPEClient.confirmCardPayment(clientSecret);\n } catch (error) {\n try {\n result = await this._stripeUPEClient.retrievePaymentIntent(clientSecret);\n } catch (error) {\n catchedConfirmError = true;\n }\n }\n\n if (result?.error) {\n this._throwDisplayableStripeError(result.error);\n\n if (this._isCancellationError(result.error)) {\n throw new PaymentMethodCancelledError();\n }\n\n throw new PaymentMethodFailedError();\n }\n\n if (!result?.paymentIntent && !catchedConfirmError) {\n throw new RequestError();\n }\n\n const paymentPayload = {\n methodId,\n paymentData: {\n formattedPayload: {\n credit_card_token: {\n token: catchedConfirmError ? clientSecret : result?.paymentIntent?.id,\n },\n confirm: false,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n },\n },\n };\n\n return this._store.dispatch(this._paymentActionCreator.submitPayment(paymentPayload));\n }\n\n throw error;\n }\n\n private _mapStripeAddress(address?: Address): AddressOptions {\n if (address) {\n const { city, countryCode: country, postalCode } = address;\n\n return { city, country, postal_code: postalCode };\n }\n\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n\n private _mapStripePaymentData(returnUrl?: string): StripeConfirmPaymentData {\n const billingAddress = this._store.getState().billingAddress.getBillingAddress();\n const address = this._mapStripeAddress(billingAddress);\n\n const email = billingAddress?.email;\n\n if (!this._stripeElements) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n if (!email || !address || !address.city || !address.country) {\n throw new MissingDataError(MissingDataErrorType.MissingBillingAddress);\n }\n\n return {\n elements: this._stripeElements,\n redirect: StripeStringConstants.IF_REQUIRED,\n confirmParams: {\n payment_method_data: {\n billing_details: {\n email,\n address,\n },\n },\n ...(returnUrl && { return_url: returnUrl }),\n },\n };\n }\n\n private async _loadStripeJs(\n stripePublishableKey: string,\n stripeConnectedAccount: string,\n ): Promise {\n if (this._stripeUPEClient) {\n return this._stripeUPEClient;\n }\n\n return this._stripeScriptLoader.getStripeClient(\n stripePublishableKey,\n stripeConnectedAccount,\n );\n }\n}\n","interface BaseElementOptions {\n /**\n * Customize the appearance of an element using CSS properties passed in a [Style](https://stripe.com/docs/js/appendix/style) object,\n * which consists of CSS properties nested under objects for each variant.\n */\n style?: StripeElementStyle;\n\n /**\n * Set custom class names on the container DOM element when the Stripe element is in a particular state.\n */\n classes?: StripeElementClasses;\n\n /**\n * Applies a disabled state to the Element such that user input is not accepted. Default is false.\n */\n disabled?: boolean;\n}\n\nexport interface CreatePaymentMethodCardData extends PaymentMethodCreateParams {\n card?: StripeElement;\n}\n\nexport interface CreatePaymentMethodIdealData extends PaymentMethodCreateParams {\n ideal?: StripeElement;\n}\n\nexport interface CreatePaymentMethodSepaData extends PaymentMethodCreateParams {\n sepa_debit?: StripeElement;\n}\n\n/**\n * The PaymentIntent object.\n */\nexport interface PaymentIntent {\n /**\n * Unique identifier for the object.\n */\n id: string;\n\n /**\n * Status of this PaymentIntent. Read more about each PaymentIntent [status](https://stripe.com/docs/payments/intents#intent-statuses).\n */\n status: 'succeeded' | string;\n\n /**\n * The payment error encountered in the previous PaymentIntent confirmation. It will be cleared if the PaymentIntent is later updated for any reason.\n */\n last_payment_error: LastPaymentError | null;\n}\n\n/**\n * The payment error encountered in the previous PaymentIntent confirmation. It will be cleared if the PaymentIntent is later updated for any reason.\n */\nexport interface LastPaymentError {\n /**\n * A human-readable message providing more details about the error. For card errors, these messages can be shown to your users.\n */\n message?: string;\n}\n\n/**\n * The PaymentMethod object\n */\nexport interface PaymentMethod {\n /**\n * Unique identifier for the object.\n */\n id: string;\n\n /**\n * The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value.\n * It contains additional information specific to the PaymentMethod type.\n */\n type: string;\n}\n\nexport interface PaymentMethodCreateParams {\n /**\n * Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods.\n */\n billing_details?: StripeBillingDetails;\n}\n\nexport interface StripeError {\n /**\n * A human-readable message providing more details about the error. For card errors, these messages can be shown to your users.\n */\n message?: string;\n\n /**\n * The PaymentIntent object.\n */\n payment_intent: PaymentIntent;\n\n /**\n * A human-readable code for the error obtained\n */\n code?: string;\n}\n\n/**\n * CSS properties supported by Stripe.js.\n */\ninterface StripeElementCSSProperties {\n /**\n * The [background-color](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color) CSS property.\n *\n * This property works best with the `::selection` pseudo-class.\n * In other cases, consider setting the background color on the element's container instaed.\n */\n backgroundColor?: string;\n\n /**\n * The [color](https://developer.mozilla.org/en-US/docs/Web/CSS/color) CSS property.\n */\n color?: string;\n\n /**\n * The [font-family](https://developer.mozilla.org/en-US/docs/Web/CSS/font-family) CSS property.\n */\n fontFamily?: string;\n\n /**\n * The [font-size](https://developer.mozilla.org/en-US/docs/Web/CSS/font-size) CSS property.\n */\n fontSize?: string;\n\n /**\n * The [font-smoothing](https://developer.mozilla.org/en-US/docs/Web/CSS/font-smoothing) CSS property.\n */\n fontSmoothing?: string;\n\n /**\n * The [font-style](https://developer.mozilla.org/en-US/docs/Web/CSS/font-style) CSS property.\n */\n fontStyle?: string;\n\n /**\n * The [font-variant](https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant) CSS property.\n */\n fontVariant?: string;\n\n /**\n * The [font-weight](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight) CSS property.\n */\n fontWeight?: string;\n\n /**\n * A custom property, used to set the color of the icons that are rendered in an element.\n */\n iconColor?: string;\n\n /**\n * The [line-height](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height) CSS property.\n *\n * To avoid cursors being rendered inconsistently across browsers, consider using a padding on the element's container instead.\n */\n lineHeight?: string;\n\n /**\n * The [letter-spacing](https://developer.mozilla.org/en-US/docs/Web/CSS/letter-spacing) CSS property.\n */\n letterSpacing?: string;\n\n /**\n * The [text-align](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align) CSS property.\n *\n * Available for the `cardNumber`, `cardExpiry`, and `cardCvc` elements.\n */\n textAlign?: string;\n\n /**\n * The [padding](https://developer.mozilla.org/en-US/docs/Web/CSS/padding) CSS property.\n *\n * Available for the `idealBank` element.\n * Accepts integer `px` values.\n */\n padding?: string;\n\n /**\n * The [text-decoration](https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration) CSS property.\n */\n textDecoration?: string;\n\n /**\n * The [text-shadow](https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow) CSS property.\n */\n textShadow?: string;\n\n /**\n * The [text-transform](https://developer.mozilla.org/en-US/docs/Web/CSS/text-transform) CSS property.\n */\n textTransform?: string;\n}\n\ninterface StripeElementStyleVariant extends StripeElementCSSProperties {\n ':hover'?: StripeElementCSSProperties;\n\n ':focus'?: StripeElementCSSProperties;\n\n '::placeholder'?: StripeElementCSSProperties;\n\n '::selection'?: StripeElementCSSProperties;\n\n ':-webkit-autofill'?: StripeElementCSSProperties;\n\n /**\n * Available for all elements except the `paymentRequestButton` element\n */\n ':disabled'?: StripeElementCSSProperties;\n\n /**\n * Available for the `cardNumber`, `cardExpiry`, and `cardCvc` elements.\n */\n '::-ms-clear'?: StripeElementCSSProperties & { display: string };\n}\n\nexport interface CardElementOptions extends BaseElementOptions {\n /**\n * A pre-filled set of values to include in the input (e.g., {postalCode: '94110'}).\n * Note that sensitive card information (card number, CVC, and expiration date)\n * cannot be pre-filled\n */\n value?: string;\n\n /**\n * Hide the postal code field. Default is false. If you are already collecting a\n * full billing address or postal code elsewhere, set this to true.\n */\n hidePostalCode?: boolean;\n\n /**\n * Appearance of the icon in the Element.\n */\n iconStyle?: IconStyle;\n\n /*\n * Hides the icon in the Element, Default is false\n */\n hideIcon?: boolean;\n}\n\ninterface BaseIndividualElementOptions extends BaseElementOptions {\n containerId: string;\n}\n\nexport interface CardNumberElementOptions extends BaseIndividualElementOptions {\n /*\n * Placeholder\n */\n placeholder?: string;\n\n showIcon?: boolean;\n /**\n * Appearance of the icon in the Element. Either `solid` or `default`\n */\n iconStyle?: IconStyle;\n}\n\nexport interface CardExpiryElementOptions extends BaseIndividualElementOptions {\n /*\n * Placeholder\n */\n placeholder?: string;\n}\n\nexport interface CardCvcElementOptions extends BaseIndividualElementOptions {\n /*\n * Placeholder\n */\n placeholder?: string;\n}\n\nexport interface IbanElementOptions extends BaseElementOptions {\n /**\n * Specify the list of countries or country-groups whose IBANs you want to allow.\n * Must be ['SEPA'].\n */\n supportedCountries?: string[];\n\n /**\n * Customize the country and format of the placeholder IBAN. Default is DE.\n */\n placeholderCountry?: string;\n\n /**\n * Appearance of the icon in the Element.\n */\n iconStyle?: IconStyle;\n}\n\nexport interface IdealElementOptions extends BaseElementOptions {\n value?: string;\n\n /**\n * Hides the icon in the Element. Default is false.\n */\n hideIcon?: boolean;\n}\n\nexport interface ZipCodeElementOptions {\n containerId: string;\n}\n\nexport enum IconStyle {\n Solid = 'solid',\n Default = 'default',\n}\n\nexport interface StripeElementStyle {\n /**\n * Base variant—all other variants inherit from these styles.\n */\n base?: StripeElementStyleVariant;\n\n /**\n * Applied when the element has valid input.\n */\n complete?: StripeElementStyleVariant;\n\n /**\n * Applied when the element has no customer input.\n */\n empty?: StripeElementStyleVariant;\n\n /**\n * Applied when the element has invalid input.\n */\n invalid?: StripeElementStyleVariant;\n}\n\nexport interface StripeElementClasses {\n /**\n * The base class applied to the container. Defaults to StripeElement.\n */\n base?: string;\n\n /**\n * The class name to apply when the Element is complete. Defaults to StripeElement--complete.\n */\n complete?: string;\n\n /**\n * The class name to apply when the Element is empty. Defaults to StripeElement--empty.\n */\n empty?: string;\n\n /**\n * The class name to apply when the Element is focused. Defaults to StripeElement--focus.\n */\n focus?: string;\n\n /**\n * The class name to apply when the Element is invalid. Defaults to StripeElement--invalid.\n */\n invalid?: string;\n\n /**\n * The class name to apply when the Element has its value autofilled by the browser\n * (only on Chrome and Safari). Defaults to StripeElement--webkit-autofill.\n */\n webkitAutoFill?: string;\n}\n\nexport interface StripeAddress {\n /**\n * City, district, suburb, town, or village.\n */\n city?: string;\n\n /**\n * Two-letter country code ([ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)).\n */\n country?: string;\n\n /**\n * Address line 1 (e.g., street, PO Box, or company name).\n */\n line1: string;\n\n /**\n * Address line 2 (e.g., apartment, suite, unit, or building).\n */\n line2?: string;\n\n /**\n * ZIP or postal code.\n */\n postal_code?: string;\n\n /**\n * State, county, province, or region.\n */\n state?: string;\n}\n\nexport interface StripeBillingDetails {\n /**\n * Billing address.\n */\n address?: StripeAddress;\n\n /**\n * Email address.\n */\n email?: string;\n\n /**\n * Full name.\n */\n name?: string;\n\n /**\n * Billing phone number (including extension).\n */\n phone?: string;\n}\n\nexport interface StripeShippingAddress {\n /**\n * Shipping Address\n */\n address: StripeAddress;\n\n /**\n * Recipient name\n */\n name: string;\n\n /**\n * The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc.\n */\n carrier?: string;\n\n /**\n * Recipient phone (including extension).\n */\n phone?: string;\n\n /**\n * The tracking number for a physical product, obtained from the delivery service.\n * If multiple tracking numbers were generated for this purchase, please separate them with commas.\n */\n tracking_number?: string;\n}\n\n/**\n * Data to be sent with a `stripe.confirmAlipayPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.\n */\nexport interface StripeConfirmAlipayPaymentData {\n /**\n * If you are [handling next actions yourself](https://stripe.com/docs/payments/payment-intents/verifying-status#next-actions), pass in a return_url. If the subsequent action\n * is redirect_to_url, this URL will be used on the return path for the redirect.\n *\n * @recommended\n */\n return_url?: string;\n}\n\n/**\n * Data to be sent with a `stripe.confirmCardPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.\n */\nexport interface StripeConfirmCardPaymentData {\n /*\n * Either the id of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a\n * PaymentMethod with. See the use case sections below for details.\n *\n * @recommended\n */\n payment_method?: CreatePaymentMethodCardData;\n\n /**\n * The [shipping details](https://stripe.com/docs/api/payment_intents/confirm#confirm_payment_intent-shipping) for the payment, if collected.\n *\n * @recommended\n */\n shipping?: StripeShippingAddress;\n\n /**\n * If you are [handling next actions yourself](https://stripe.com/docs/payments/payment-intents/verifying-status#next-actions), pass in a return_url. If the subsequent action\n * is redirect_to_url, this URL will be used on the return path for the redirect.\n *\n * @recommended\n */\n return_url?: string;\n\n /**\n * Indicates that you intend to make future payments with this PaymentIntent's payment method.\n *\n * If present, the payment method used with this PaymentIntent can be [attached](https://stripe.com/docs/api/payment_methods/attach) to a Customer, even after the transaction completes.\n *\n * Use `on_session` if you intend to only reuse the payment method when your customer is present in your checkout flow. Use `off_session` if your customer may or may not be in your checkout flow.\n */\n setup_future_usage?: 'off_session' | 'on_session' | null;\n}\n\n/**\n * Data to be sent with a `stripe.confirmIdealPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.\n */\nexport interface StripeConfirmIdealPaymentData {\n /*\n * Either the id of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a\n * PaymentMethod with. See the use case sections below for details.\n *\n * @recommended\n */\n payment_method?: CreatePaymentMethodIdealData;\n\n /**\n * If you are [handling next actions yourself](https://stripe.com/docs/payments/payment-intents/verifying-status#next-actions), pass in a return_url. If the subsequent action\n * is redirect_to_url, this URL will be used on the return path for the redirect.\n *\n * @recommended\n */\n return_url?: string;\n}\n\n/**\n * Data to be sent with a `stripe.confirmSEPAPayment` request.\n * Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.\n */\nexport interface StripeConfirmSepaPaymentData {\n /*\n * Either the id of an existing [PaymentMethod](https://stripe.com/docs/api/payment_methods), or an object containing data to create a\n * PaymentMethod with. See the use case sections below for details.\n *\n * @recommended\n */\n payment_method?: CreatePaymentMethodSepaData;\n}\n\nexport type StripeConfirmPaymentData =\n | StripeConfirmAlipayPaymentData\n | StripeConfirmCardPaymentData\n | StripeConfirmIdealPaymentData\n | StripeConfirmSepaPaymentData\n | undefined;\n\nexport type StripeElementOptions =\n | CardElementOptions\n | CardExpiryElementOptions\n | CardNumberElementOptions\n | CardCvcElementOptions\n | IdealElementOptions\n | IbanElementOptions\n | ZipCodeElementOptions;\n\nexport interface StripeElement {\n /**\n * The `element.mount` method attaches your element to the DOM.\n */\n mount(domElement: string | HTMLElement): void;\n\n /**\n * Removes the element from the DOM and destroys it.\n * A destroyed element can not be re-activated or re-mounted to the DOM.\n */\n destroy(): void;\n\n /**\n * Unmounts the element from the DOM.\n * Call `element.mount` to re-attach it to the DOM.\n */\n unmount(): void;\n}\n\nexport interface StripeElements {\n /**\n * Creates a `AlipayElement` | `CardElement` | `CardCvcElement` |`CardExpiryElement` | `CardExpiryElement` | `CardNumberElement` | `IdealBankElement` | `IbanElement`.\n */\n create(elementType: StripeElementType, options?: StripeElementOptions): StripeElement;\n\n /**\n * Looks up a previously created `Element` by its type.\n */\n getElement(elementType: StripeElementType): StripeElement | null;\n}\n\n/**\n * This object is used to pass custom fonts when creating an [Elements](https://stripe.com/docs/js/elements_object/create) object.\n */\nexport interface CssFontSource {\n /**\n * A relative or absolute URL pointing to a CSS file with [@font-face](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face) definitions, for example:\n * `https://fonts.googleapis.com/css?family=Open+Sans`\n * Note that if you are using a [content security policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) (CSP),\n * [additional directives](https://stripe.com/docs/security#content-security-policy) may be necessary.\n */\n cssSrc: string;\n}\n\n/**\n * This object is used to pass custom fonts when creating an [Elements](https://stripe.com/docs/js/elements_object/create) object.\n */\nexport interface CustomFontSource {\n /**\n * The name to give the font.\n */\n family: string;\n\n /**\n * A valid [src](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/src) value pointing to your\n * custom font file. This is usually (though not always) a link to a file with a .woff , .otf, or .svg suffix.\n */\n src: string;\n\n /**\n * A valid [font-display](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display) value.\n */\n display?: string;\n\n /**\n * One of normal, italic, oblique. Defaults to normal.\n */\n style?: string;\n\n /**\n * A valid [unicode-range](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/unicode-range) value.\n */\n unicodeRange?: string;\n\n /**\n * A valid [font-weight](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight). Note that this is a string, not a number.\n */\n weight?: string;\n}\n\nexport type CustomFont = CssFontSource | CustomFontSource;\n\nexport interface StripeElementsOptions {\n /**\n * An array of custom fonts, which elements created from the Elements object can use.\n * Fonts can be specified as [CssFontSource](https://stripe.com/docs/js/appendix/css_font_source_object)\n * or [CustomFontSource](https://stripe.com/docs/js/appendix/custom_font_source_object) objects.\n */\n fonts?: CustomFont[];\n\n /**\n * A [locale](https://stripe.com/docs/js/appendix/supported_locales) to display placeholders and\n * error strings in. Default is auto (Stripe detects the locale of the browser).\n * Setting the locale does not affect the behavior of postal code validation—a valid postal code\n * for the billing country of the card is still required.\n */\n locale?: string;\n}\n\nexport interface StripeConfirmPaymentOptions {\n /**\n * Set this to false if you want to [manually handle the authorization redirect](https://stripe.com/docs/payments/ideal#handle-redirect). Default is true.\n */\n handleActions?: boolean;\n}\n\nexport interface StripeV3Client {\n /**\n * Create an `Elements` instance, which manages a group of elements.\n */\n elements(options?: StripeElementsOptions): StripeElements;\n\n /**\n * @docs https://stripe.com/docs/js/payment_intents/confirm_alipay_payment\n *\n * Use `stripe.confirmAlipayPayment` in the Alipay payment method creation flow when the customer submits your payment form.\n * When called, it will confirm the [PaymentIntent](https://stripe.com/docs/api/payment_intents) with data you provide, and it will automatically\n * redirect the customer to the authorize the transaction. Once authorization is complete, the customer will be redirected\n * back to your specified `return_url`. When you confirm a `PaymentIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods).\n * In addition to confirming the `PaymentIntent`, this method can automatically create and attach a new `PaymentMethod` for you.\n * If you have already attached a `PaymentMethod` you can call this method without needing to provide any additional data.\n * These use cases are detailed in the sections that follow.\n *\n * @returns\n * `stripe.confirmAlipayPayment` by default, will trigger a redirect when successful. If there is an error, or when handling\n * `next_actions` manually by using the `handleActions: false` option, it will return a `Promise` which resolves with a `result` object.\n * This object has either:\n *\n * - result.paymentIntent: the successful PaymentIntent.\n * - result.error: an error. Refer to the API reference for all possible errors.\n *\n * Note that `stripe.confirmAlipayPayment` may take several seconds to complete. During that time, you should disable your\n * form from being resubmitted and show a waiting indicator like a spinner. If you receive an error result, you should\n * be sure to show that error to the customer, re-enable the form, and hide the waiting indicator.\n */\n confirmAlipayPayment(\n /**\n * The [client secret](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-client_secret) of the PaymentIntent.\n */\n clientSecret: string,\n\n /**\n * Data to be sent with the request. Refer to the Payment Intents API for a full list of parameters.\n */\n data?: StripeConfirmAlipayPaymentData,\n\n /**\n * An options object to control the behavior of this method.\n */\n options?: StripeConfirmPaymentOptions,\n ): Promise<{ paymentIntent?: PaymentIntent; error?: StripeError }>;\n\n /**\n * @docs https://stripe.com/docs/js/payment_intents/confirm_card_payment\n *\n * Use `stripe.confirmCardPayment` when the customer submits your payment form.\n * When called, it will confirm the [PaymentIntent](https://stripe.com/docs/api/payment_intents)\n * with `data` you provide and carry out 3DS or other next actions if they are required.\n *\n * If you are using [Dynamic 3D Secure](https://stripe.com/docs/payments/3d-secure#three-ds-radar), `stripe.confirmCardPayment` will\n * trigger your Radar rules to execute and may open a dialog for your customer to authenticate their payment.\n *\n * When you confirm a `PaymentIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods).\n * In addition to confirming the `PaymentIntent`, this method can automatically create and attach a new `PaymentMethod` for you.\n * It can also be called with an existing `PaymentMethod`, or if you have already attached a PaymentMethod you can call this\n * method without needing to provide any additional data. These use cases are detailed in the sections that follow.\n *\n * @returns\n * `stripe.confirmCardPayment` will return a Promise which resolves with a result object.\n * This object has either:\n *\n * - result.paymentIntent: the successful PaymentIntent.\n * - result.error: an error. Refer to the API reference for all possible errors.\n *\n * Note that stripe.confirmCardPayment may take several seconds to complete. During that time, you should disable\n * your form from being resubmitted and show a waiting indicator like a spinner. If you receive an error result,\n * you should be sure to show that error to the customer, re-enable the form, and hide the waiting indicator.\n *\n * Additionally, `stripe.confirmCardPayment may trigger` a [3D Secure](https://stripe.com/docs/payments/3d-secure) authentication\n * challenge. This will be shown in a modal dialog and may be confusing for customers using assistive technologies like\n * screen readers. You should make your form accessible by ensuring that success or error messages are clearly read out\n * after this method completes.\n *\n */\n confirmCardPayment(\n /**\n * The [client secret](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-client_secret) of the PaymentIntent.\n */\n clientSecret: string,\n\n /**\n * Data to be sent with the request. Refer to the Payment Intents API for a full list of parameters.\n */\n data?: StripeConfirmCardPaymentData,\n\n /**\n * An options object to control the behavior of this method.\n */\n options?: StripeConfirmPaymentOptions,\n ): Promise<{ paymentIntent?: PaymentIntent; error?: StripeError }>;\n\n /**\n * @docs https://stripe.com/docs/js/payment_intents/confirm_ideal_payment\n *\n * Use `stripe.confirmIdealPayment` in the [iDEAL Payments with Payment Methods](https://stripe.com/docs/payments/ideal)\n * flow when the customer submits your payment form. When called, it will confirm the `PaymentIntent` with `data` you\n * provide, and it will automatically redirect the customer to the authorize the transaction.\n * Once authorization is complete, the customer will be redirected back to your specified `return_url`.\n *\n * When you confirm a `PaymentIntent`, it needs to have an attached [PaymentMethod](https://stripe.com/docs/api/payment_methods).\n * In addition to confirming the `PaymentIntent`, this method can automatically create and attach a new `PaymentMethod` for you.\n * It can also be called with an existing `PaymentMethod`, or if you have already attached a PaymentMethod you can call this\n * method without needing to provide any additional data. These use cases are detailed in the sections that follow.\n *\n * @returns\n * By default, `stripe.confirmIdealPayment` will trigger a redirect when successful. If there is an error, or when handling\n * next actions manually by using the `handleActions: false` option, it will return a `Promise` which resolves with a `result`\n * object. This object has either:\n *\n * - result.paymentIntent: the successful PaymentIntent.\n * - result.error: an error. Refer to the API reference for all possible errors.\n *\n * Note that `stripe.confirmIdealPayment` may take several seconds to complete. During that time, you should disable\n * your form from being resubmitted and show a waiting indicator like a spinner. If you receive an error result,\n * you should be sure to show that error to the customer, re-enable the form, and hide the waiting indicator.\n */\n confirmIdealPayment(\n /**\n * The [client secret](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-client_secret) of the PaymentIntent.\n */\n clientSecret: string,\n\n /**\n * Data to be sent with the request. Refer to the Payment Intents API for a full list of parameters.\n */\n data?: StripeConfirmIdealPaymentData,\n\n /**\n * An options object to control the behavior of this method.\n */\n options?: StripeConfirmPaymentOptions,\n ): Promise<{ paymentIntent?: PaymentIntent; error?: StripeError }>;\n\n /**\n *\n * Use `stripe.confirmSepaDebitPayment` in the [SEPA Direct Debit Payments](https://stripe.com/docs/payments/sepa-debit)\n * with Payment Methods flow when the customer submits your payment form. When called, it will confirm the\n * [PaymentIntent](https://stripe.com/docs/api/payment_intents) with `data` you provide. Note that there are some additional\n * requirements to this flow that are not covered in this reference. Refer to our [integration guide](https://stripe.com/docs/payments/sepa-debit\n * for more details.\n *\n * When you confirm a PaymentIntent, it needs to have an attached PaymentMethod. In addition to confirming the PaymentIntent,\n * this method can automatically create and attach a new PaymentMethod for you. If you have already attached a\n * [PaymentMethod](https://stripe.com/docs/api/payment_methods) you can call this method without needing to provide any additional data.\n * These use cases are detailed in the sections that follow.\n *\n * @docs https://stripe.com/docs/js/payment_intents/confirm_sepa_debit_payment\n */\n confirmSepaDebitPayment(\n /**\n * The [client secret](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-client_secret) of the PaymentIntent.\n */\n clientSecret: string,\n\n /**\n * Data to be sent with the request. Refer to the [Payment Intents API](https://stripe.com/docs/api/payment_intents/confirm) for a full list of parameters.\n */\n data?: StripeConfirmSepaPaymentData,\n ): Promise<{ paymentIntent?: PaymentIntent; error?: StripeError }>;\n\n /**\n * Use stripe.createPaymentMethod to convert payment information collected by elements into a PaymentMethod\n * object that you safely pass to your server to use in an API call.\n *\n * @docs https://stripe.com/docs/js/payment_methods/create_payment_method\n *\n * @param type: String, The type of the PaymentMethod to create. Refer to the PaymentMethod API for all possible values.\n * @param card: StripeElement, A card or cardNumber Element.\n * @param billing_details: StripeBillingDetails, Billing information associated with the PaymentMethod that\n * may be used or required by particular types of payment methods.\n */\n createPaymentMethod(\n params: CreatePaymentMethodParams,\n ): Promise<{ paymentMethod?: PaymentMethod; error?: StripeError }>;\n\n /**\n * Use stripe.handleCardAction in the Payment Intents API manual confirmation flow to handle a PaymentIntent\n * with the requires_action status. It will throw an error if the PaymentIntent has a different status.\n *\n * @docs https://stripe.com/docs/js/payment_intents/handle_card_action\n *\n * @param paymentIntentClientSecret: String, The client secret of the PaymentIntent to handle.\n */\n handleCardAction(\n paymentIntentClientSecret: string,\n ): Promise<{ paymentIntent?: PaymentIntent; error?: StripeError }>;\n}\n\nexport interface CreatePaymentMethodParams {\n type: StripePaymentMethodType;\n card: StripeElement;\n billing_details?: StripeBillingDetails;\n}\n\nexport interface StripeHostWindow extends Window {\n Stripe?(stripePublishableKey: string, options?: StripeConfigurationOptions): StripeV3Client;\n}\n\nexport enum StripeElementType {\n Alipay = 'alipay',\n CardCvc = 'cardCvc',\n CardExpiry = 'cardExpiry',\n CardNumber = 'cardNumber',\n CreditCard = 'card',\n IDEAL = 'idealBank',\n Sepa = 'iban',\n}\n\nexport enum StripePaymentMethodType {\n Alipay = 'alipay',\n CreditCard = 'card',\n IDEAL = 'ideal',\n Sepa = 'sepa_debit',\n}\n\n/**\n * Initialization options.\n */\nexport interface StripeConfigurationOptions {\n /**\n * For usage with [Connect](https://stripe.com/docs/connect) only.\n * Specifying a connected account ID (e.g., acct_24BFMpJ1svR5A89k) allows you to perform actions on behalf of that account.\n */\n stripeAccount: string;\n\n /**\n * Override your account's [API version](https://stripe.com/docs/api/versioning)\n */\n apiVersion?: string;\n\n /**\n * A locale used to globally configure localization in Stripe. Setting the locale here will localize error strings for all Stripe.js methods. It will also configure the locale for Elements and Checkout. Default is auto (Stripe detects the locale of the browser).\n * Note that Checkout supports a slightly different set of locales than Stripe.js.\n */\n locale?: string;\n\n betas?: string[];\n}\n\nexport interface StripeAdditionalActionData {\n redirect_url?: string;\n intent?: string;\n}\n\nexport interface StripeAdditionalAction {\n type: string;\n data: StripeAdditionalActionData;\n}\n\nexport interface StripeCardElements {\n [index: number]: StripeElement;\n}\n\nexport interface IndividualCardElementOptions {\n cardCvcElementOptions: CardCvcElementOptions;\n cardExpiryElementOptions: CardExpiryElementOptions;\n cardNumberElementOptions: CardNumberElementOptions;\n zipCodeElementOptions?: ZipCodeElementOptions;\n}\n\nexport default function isIndividualCardElementOptions(\n individualCardElementOptions: unknown,\n): individualCardElementOptions is IndividualCardElementOptions {\n return (\n Boolean(\n (individualCardElementOptions as IndividualCardElementOptions).cardNumberElementOptions,\n ) &&\n Boolean(\n (individualCardElementOptions as IndividualCardElementOptions).cardCvcElementOptions,\n ) &&\n Boolean(\n (individualCardElementOptions as IndividualCardElementOptions).cardExpiryElementOptions,\n )\n );\n}\n","import { StandardError } from '../../../common/error/errors';\n\nexport enum StripeV3ErrorType {\n AuthFailure = 'auth_failure',\n}\n\nexport default class StripeV3Error extends StandardError {\n subtype: string;\n\n constructor(subtype: StripeV3ErrorType) {\n super(getErrorMessage(subtype));\n\n this.type = 'stripev3_error';\n this.subtype = subtype;\n }\n}\n\nfunction getErrorMessage(type: StripeV3ErrorType) {\n switch (type) {\n case StripeV3ErrorType.AuthFailure:\n return `User did not authenticate`;\n\n default:\n return 'There was an error while processing your payment. Please try again or contact us.';\n }\n}\n","import { includes, isEmpty, omitBy, some } from 'lodash';\n\nimport { isHostedInstrumentLike, Payment } from '../..';\nimport { Address } from '../../../address';\nimport { BillingAddress, isBillingAddressLike } from '../../../billing';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { Customer } from '../../../customer';\nimport { HostedForm, HostedFormFactory, HostedFormOptions } from '../../../hosted-form';\nimport { OrderActionCreator, OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { StoreCreditActionCreator } from '../../../store-credit';\nimport { PaymentArgumentInvalidError, PaymentMethodCancelledError } from '../../errors';\nimport isVaultedInstrument from '../../is-vaulted-instrument';\nimport { StripeV3FormattedPayload } from '../../payment';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethod from '../../payment-method';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport PaymentStrategy from '../payment-strategy';\n\nimport isIndividualCardElementOptions, {\n PaymentIntent,\n StripeAdditionalAction,\n StripeAddress,\n StripeBillingDetails,\n StripeCardElements,\n StripeConfirmIdealPaymentData,\n StripeConfirmPaymentData,\n StripeConfirmSepaPaymentData,\n StripeElement,\n StripeElementOptions,\n StripeElements,\n StripeElementType,\n StripeError,\n PaymentMethod as StripePaymentMethod,\n StripePaymentMethodType,\n StripeV3Client,\n} from './stripev3';\nimport StripeV3Error, { StripeV3ErrorType } from './stripev3-error';\nimport StripeV3PaymentInitializeOptions from './stripev3-initialize-options';\nimport StripeV3ScriptLoader from './stripev3-script-loader';\n\nconst APM_REDIRECT = [StripeElementType.Alipay, StripeElementType.IDEAL];\n\nexport default class StripeV3PaymentStrategy implements PaymentStrategy {\n private _initializeOptions?: StripeV3PaymentInitializeOptions;\n private _stripeV3Client?: StripeV3Client;\n private _stripeElements?: StripeElements;\n private _stripeElement?: StripeElement;\n private _stripeCardElements?: StripeCardElements;\n private _useIndividualCardFields?: boolean;\n private _hostedForm?: HostedForm;\n private _isDeinitialize?: boolean;\n\n constructor(\n private _store: CheckoutStore,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentActionCreator: PaymentActionCreator,\n private _orderActionCreator: OrderActionCreator,\n private _stripeScriptLoader: StripeV3ScriptLoader,\n private _storeCreditActionCreator: StoreCreditActionCreator,\n private _hostedFormFactory: HostedFormFactory,\n private _locale: string,\n ) {}\n\n async initialize(options: PaymentInitializeOptions): Promise {\n const { stripev3, methodId, gatewayId } = options;\n\n if (!gatewayId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"gatewayId\" argument is not provided.',\n );\n }\n\n this._initializeOptions = stripev3;\n this._isDeinitialize = false;\n\n const paymentMethod = this._store\n .getState()\n .paymentMethods.getPaymentMethodOrThrow(methodId);\n const {\n initializationData: {\n stripePublishableKey,\n stripeConnectedAccount,\n useIndividualCardFields,\n },\n } = paymentMethod;\n const form = this._getInitializeOptions().form;\n\n this._useIndividualCardFields = useIndividualCardFields;\n this._stripeV3Client = await this._loadStripeJs(\n stripePublishableKey,\n stripeConnectedAccount,\n );\n\n if (\n this._isCreditCard(methodId) &&\n this._shouldShowTSVHostedForm(methodId, gatewayId) &&\n form\n ) {\n this._hostedForm = await this._mountCardVerificationFields(form);\n } else {\n this._stripeElement = await this._mountCardFields(methodId);\n }\n\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n orderRequest: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = orderRequest;\n let formattedPayload: StripeV3FormattedPayload;\n let stripeError: StripeError | undefined;\n\n if (!payment || !payment.paymentData) {\n throw new PaymentArgumentInvalidError(['payment.paymentData']);\n }\n\n const { paymentData, gatewayId, methodId } = payment;\n const { shouldSaveInstrument, shouldSetAsDefaultInstrument } = isHostedInstrumentLike(\n paymentData,\n )\n ? paymentData\n : { shouldSaveInstrument: false, shouldSetAsDefaultInstrument: false };\n const shouldSubmitOrderBeforeLoadingAPM = includes(APM_REDIRECT, methodId);\n\n const { isStoreCreditApplied: useStoreCredit } = this._store\n .getState()\n .checkout.getCheckoutOrThrow();\n\n if (useStoreCredit) {\n await this._store.dispatch(\n this._storeCreditActionCreator.applyStoreCredit(useStoreCredit),\n );\n }\n\n try {\n if (shouldSubmitOrderBeforeLoadingAPM) {\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n }\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(`${gatewayId}`, {\n params: { method: methodId },\n }),\n );\n\n if (isVaultedInstrument(paymentData)) {\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n\n const { instrumentId } = paymentData;\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(\n payment.methodId,\n );\n const clientToken = paymentMethod.clientToken;\n\n if (!clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n return await this._executeWithVaulted(\n payment,\n instrumentId,\n shouldSetAsDefaultInstrument,\n clientToken,\n );\n }\n\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n const result = await this._confirmStripePayment(paymentMethod);\n const { clientToken, method } = paymentMethod;\n const { id: token } = result.paymentIntent ?? result.paymentMethod ?? { id: '' };\n\n stripeError = result.error;\n\n formattedPayload = {\n credit_card_token: { token },\n vault_payment_instrument: shouldSaveInstrument,\n confirm: false,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n };\n\n if (method === StripeElementType.CreditCard) {\n formattedPayload.client_token = clientToken;\n }\n\n if (!shouldSubmitOrderBeforeLoadingAPM) {\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n }\n\n const paymentPayload = this._buildPaymentPayload(\n methodId,\n formattedPayload,\n shouldSetAsDefaultInstrument,\n );\n\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentPayload),\n );\n } catch (error) {\n return await this._processAdditionalAction(\n this._handleEmptyPaymentIntentError(error, stripeError),\n methodId,\n shouldSaveInstrument,\n shouldSetAsDefaultInstrument,\n );\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n if (this._hostedForm) {\n this._hostedForm.detach();\n }\n\n this._isDeinitialize = true;\n this._unmountElement();\n\n return Promise.resolve(this._store.getState());\n }\n\n private _buildPaymentPayload(\n methodId: string,\n formattedPayload: StripeV3FormattedPayload,\n shouldSetAsDefaultInstrument: boolean | undefined,\n ): Payment {\n const paymentData = shouldSetAsDefaultInstrument\n ? {\n formattedPayload: {\n ...formattedPayload,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n },\n }\n : { formattedPayload };\n\n return { methodId, paymentData };\n }\n\n private _isCancellationError(stripeError: StripeError | undefined) {\n return (\n stripeError &&\n stripeError.payment_intent.last_payment_error?.message?.indexOf('canceled') !== -1\n );\n }\n\n private _isAuthError(stripeError: StripeError | undefined) {\n return stripeError?.code === 'payment_intent_authentication_failure';\n }\n\n private _isCreditCard(methodId: string): boolean {\n return methodId === StripePaymentMethodType.CreditCard;\n }\n\n private _isHostedFieldAvailable(): boolean {\n const options = this._getInitializeOptions();\n const definedFields = omitBy(options.form?.fields, isEmpty);\n\n return !isEmpty(definedFields);\n }\n\n private _isHostedPaymentFormEnabled(methodId: string, gatewayId?: string): boolean {\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n const paymentMethod = getPaymentMethodOrThrow(methodId, gatewayId);\n\n return Boolean(paymentMethod.config.isHostedFormEnabled);\n }\n\n private async _confirmStripePayment(paymentMethod: PaymentMethod): Promise<{\n paymentIntent?: PaymentIntent | undefined;\n paymentMethod?: StripePaymentMethod | undefined;\n error?: StripeError | undefined;\n }> {\n const { clientToken: clientSecret, method, returnUrl } = paymentMethod;\n\n if (!clientSecret) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n switch (method) {\n case StripeElementType.Alipay:\n return this._getStripeJs().confirmAlipayPayment(\n clientSecret,\n { return_url: returnUrl },\n { handleActions: false },\n );\n\n case StripeElementType.IDEAL: {\n const data = this._mapStripePaymentData(StripePaymentMethodType.IDEAL, returnUrl);\n\n return this._getStripeJs().confirmIdealPayment(clientSecret, data, {\n handleActions: false,\n });\n }\n\n case StripeElementType.Sepa: {\n const data = this._mapStripePaymentData(StripePaymentMethodType.Sepa);\n\n return this._getStripeJs().confirmSepaDebitPayment(clientSecret, data);\n }\n\n default: {\n const card = this._useIndividualCardFields\n ? this._getStripeCardElements()[0]\n : this._getStripeElement();\n const billingDetails = this._mapStripeBillingDetails(\n this._store.getState().billingAddress.getBillingAddress(),\n this._store.getState().customer.getCustomer(),\n );\n\n return this._getStripeJs().createPaymentMethod({\n type: StripePaymentMethodType.CreditCard,\n card,\n billing_details: billingDetails,\n });\n }\n }\n }\n\n private async _executeWithVaulted(\n payment: OrderPaymentRequestBody,\n token: string,\n shouldSetAsDefaultInstrument: boolean | undefined,\n clientToken: string,\n ): Promise {\n const formattedPayload = {\n bigpay_token: { token },\n confirm: true,\n client_token: clientToken,\n set_as_default_stored_instrument: shouldSetAsDefaultInstrument,\n };\n\n if (\n this._isHostedPaymentFormEnabled(payment.methodId, payment.gatewayId) &&\n this._hostedForm\n ) {\n const form = this._hostedForm;\n\n if (payment.paymentData && isVaultedInstrument(payment.paymentData)) {\n payment.paymentData = {\n ...payment.paymentData,\n instrumentId: JSON.stringify({\n token: payment.paymentData?.instrumentId || '',\n client_token: clientToken,\n }),\n };\n }\n\n await form.validate();\n await form.submit(payment);\n\n return this._store.dispatch(this._orderActionCreator.loadCurrentOrder());\n }\n\n const paymentPayload = this._buildPaymentPayload(\n payment.methodId,\n formattedPayload,\n shouldSetAsDefaultInstrument,\n );\n\n return this._store.dispatch(this._paymentActionCreator.submitPayment(paymentPayload));\n }\n\n private _getInitializeOptions(): StripeV3PaymentInitializeOptions {\n if (!this._initializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._initializeOptions;\n }\n\n private _getStripeCardElements(): StripeCardElements {\n if (!this._stripeCardElements) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._stripeCardElements;\n }\n\n private _getStripeElement(): StripeElement {\n if (!this._stripeElement) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._stripeElement;\n }\n\n private _getStripeJs(): StripeV3Client {\n if (!this._stripeV3Client) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._stripeV3Client;\n }\n\n private _handleEmptyPaymentIntentError(error: Error, stripeError: StripeError | undefined) {\n if (!(error instanceof RequestError)) {\n return error;\n }\n\n return some(error.body.errors, { code: 'required_field' }) && stripeError\n ? new Error(stripeError.message)\n : error;\n }\n\n private async _loadStripeJs(\n stripePublishableKey: string,\n stripeConnectedAccount: string,\n ): Promise {\n if (this._stripeV3Client) {\n return Promise.resolve(this._stripeV3Client);\n }\n\n return this._stripeScriptLoader.load(\n stripePublishableKey,\n stripeConnectedAccount,\n this._locale,\n );\n }\n\n private _mapStripeAddress(address?: Address): StripeAddress {\n if (address) {\n const {\n city,\n countryCode: country,\n address1: line1,\n address2: line2,\n postalCode,\n stateOrProvinceCode: state,\n } = address;\n\n return { city, country, line1, line2, postal_code: postalCode, state };\n }\n\n return { line1: '' };\n }\n\n private _mapStripeBillingDetails(\n billingAddress?: BillingAddress,\n customer?: Customer,\n ): StripeBillingDetails {\n const { firstName, lastName } = billingAddress ||\n customer || { firstName: 'Guest', lastName: '' };\n const name = `${firstName} ${lastName}`.trim();\n const { options } = this._getInitializeOptions();\n\n if (this._useIndividualCardFields && isIndividualCardElementOptions(options)) {\n const { zipCodeElementOptions } = options;\n\n if (zipCodeElementOptions) {\n const postalCode = document.getElementById(zipCodeElementOptions.containerId)\n ? (\n document.getElementById(\n zipCodeElementOptions.containerId,\n ) as HTMLInputElement\n ).value\n : '';\n\n if (postalCode && billingAddress) {\n billingAddress = { ...billingAddress, postalCode };\n }\n }\n }\n\n const address = {\n address: this._mapStripeAddress(billingAddress),\n };\n\n if (customer && customer.addresses[0] && isBillingAddressLike(customer.addresses[0])) {\n const customerAddress = customer.addresses[0];\n const { email } = customer;\n const { phone } = customerAddress;\n\n return phone ? { ...address, email, name, phone } : { ...address, email, name };\n }\n\n if (billingAddress) {\n const { email, phone } = billingAddress;\n\n return phone ? { ...address, email, name, phone } : { ...address, email, name };\n }\n\n return { ...address, name };\n }\n\n private _mapStripePaymentData(\n stripePaymentMethodType: StripePaymentMethodType.IDEAL,\n returnUrl?: string,\n ): StripeConfirmIdealPaymentData;\n private _mapStripePaymentData(\n stripePaymentMethodType: StripePaymentMethodType.Sepa,\n ): StripeConfirmSepaPaymentData;\n private _mapStripePaymentData(\n stripePaymentMethodType: StripePaymentMethodType,\n returnUrl?: string,\n ): StripeConfirmPaymentData {\n const customer = this._store.getState().customer.getCustomer();\n const billingAddress = this._store.getState().billingAddress.getBillingAddress();\n\n const result: Partial = {\n payment_method: {\n [stripePaymentMethodType]: this._getStripeElement(),\n billing_details: this._mapStripeBillingDetails(billingAddress, customer),\n },\n };\n\n if (stripePaymentMethodType === StripePaymentMethodType.IDEAL) {\n return { ...result, return_url: returnUrl };\n }\n\n return result;\n }\n\n private _mountCardFields(methodId: string): Promise {\n const { options, containerId } = this._getInitializeOptions();\n\n let stripeElement: StripeElement;\n\n return new Promise((resolve, reject) => {\n if (!this._stripeElements) {\n this._stripeElements = this._getStripeJs().elements();\n }\n\n switch (methodId) {\n case StripeElementType.CreditCard:\n if (this._useIndividualCardFields && isIndividualCardElementOptions(options)) {\n const {\n cardNumberElementOptions,\n cardExpiryElementOptions,\n cardCvcElementOptions,\n } = options;\n\n const cardNumberElement =\n this._stripeElements.getElement(StripeElementType.CardNumber) ||\n this._stripeElements.create(\n StripeElementType.CardNumber,\n cardNumberElementOptions,\n );\n const cardExpiryElement =\n this._stripeElements.getElement(StripeElementType.CardExpiry) ||\n this._stripeElements.create(\n StripeElementType.CardExpiry,\n cardExpiryElementOptions,\n );\n const cardCvcElement =\n this._stripeElements.getElement(StripeElementType.CardCvc) ||\n this._stripeElements.create(\n StripeElementType.CardCvc,\n cardCvcElementOptions,\n );\n\n this._stripeCardElements = [\n cardNumberElement,\n cardExpiryElement,\n cardCvcElement,\n ];\n stripeElement = this._stripeCardElements[0];\n\n try {\n cardNumberElement.mount(`#${cardNumberElementOptions.containerId}`);\n cardExpiryElement.mount(`#${cardExpiryElementOptions.containerId}`);\n cardCvcElement.mount(`#${cardCvcElementOptions.containerId}`);\n } catch (error) {\n if (!this._isDeinitialize) {\n reject(\n new InvalidArgumentError(\n 'Unable to mount Stripe component without valid container ID.',\n ),\n );\n }\n }\n } else {\n stripeElement =\n this._stripeElements.getElement(methodId) ||\n this._stripeElements.create(methodId, options as StripeElementOptions);\n\n try {\n stripeElement.mount(`#${containerId}`);\n } catch (error) {\n if (!this._isDeinitialize) {\n reject(\n new InvalidArgumentError(\n 'Unable to mount Stripe component without valid container ID.',\n ),\n );\n }\n }\n }\n\n break;\n\n case StripeElementType.IDEAL:\n case StripeElementType.Sepa:\n stripeElement =\n this._stripeElements.getElement(methodId) ||\n this._stripeElements.create(methodId, options as StripeElementOptions);\n\n try {\n stripeElement.mount(`#${containerId}`);\n } catch (error) {\n if (!this._isDeinitialize) {\n reject(\n new InvalidArgumentError(\n 'Unable to mount Stripe component without valid container ID.',\n ),\n );\n }\n }\n\n break;\n\n case StripeElementType.Alipay:\n break;\n }\n\n resolve(stripeElement);\n });\n }\n\n private async _mountCardVerificationFields(\n formOptions: HostedFormOptions,\n ): Promise {\n const { config } = this._store.getState();\n const storeConfig = config.getStoreConfig();\n\n if (!storeConfig) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const bigpayBaseUrl = storeConfig.paymentSettings.bigpayBaseUrl;\n\n const form = this._hostedFormFactory.create(bigpayBaseUrl, formOptions);\n\n await form.attach();\n\n return form;\n }\n\n private async _processAdditionalAction(\n error: Error,\n methodId: string,\n shouldSaveInstrument = false,\n shouldSetAsDefaultInstrument = false,\n ): Promise {\n if (!(error instanceof RequestError)) {\n throw error;\n }\n\n const isAdditionalActionError = some(error.body.errors, {\n code: 'additional_action_required',\n });\n const isThreeDSecureRequiredError = some(error.body.errors, {\n code: 'three_d_secure_required',\n });\n\n if (isAdditionalActionError) {\n const action: StripeAdditionalAction = error.body.additional_action_required;\n\n if (action && action.type === 'redirect_to_url') {\n return new Promise(() => {\n if (action.data.redirect_url) {\n window.location.replace(action.data.redirect_url);\n }\n });\n }\n }\n\n if (isThreeDSecureRequiredError) {\n const clientSecret = error.body.three_ds_result.token;\n const needsConfirm = false;\n let catchedConfirmError = false;\n let result;\n\n try {\n result = await this._getStripeJs().confirmCardPayment(clientSecret);\n } catch (error) {\n catchedConfirmError = true;\n }\n\n if (result?.error) {\n if (this._isCancellationError(result.error)) {\n throw new PaymentMethodCancelledError();\n }\n\n if (this._isAuthError(result.error)) {\n throw new StripeV3Error(StripeV3ErrorType.AuthFailure);\n }\n\n throw new Error(result.error.message);\n }\n\n const token = this._getPaymentToken(\n result?.paymentIntent,\n clientSecret,\n catchedConfirmError,\n );\n\n const formattedPayload = {\n credit_card_token: { token },\n vault_payment_instrument: shouldSaveInstrument,\n confirm: needsConfirm,\n };\n\n const paymentPayload = this._buildPaymentPayload(\n methodId,\n formattedPayload,\n shouldSetAsDefaultInstrument,\n );\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment(paymentPayload),\n );\n } catch (error) {\n throw this._handleEmptyPaymentIntentError(error, result?.error);\n }\n }\n\n throw error;\n }\n\n private _getPaymentToken(\n paymentIntent: PaymentIntent | undefined,\n clientSecret: string,\n catchedConfirmError: boolean,\n ): string {\n if (!paymentIntent || catchedConfirmError) {\n return clientSecret;\n }\n\n return paymentIntent.id;\n }\n\n private _shouldShowTSVHostedForm(methodId: string, gatewayId: string): boolean {\n return (\n this._isHostedFieldAvailable() && this._isHostedPaymentFormEnabled(methodId, gatewayId)\n );\n }\n\n private _unmountElement(): void {\n if (this._stripeElement) {\n this._stripeElement.unmount();\n this._stripeElement = undefined;\n }\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '../../errors';\n\nimport { StripeHostWindow, StripeV3Client } from './stripev3';\n\nexport default class StripeV3ScriptLoader {\n constructor(private _scriptLoader: ScriptLoader, private _window: StripeHostWindow = window) {}\n\n load(\n stripePublishableKey: string,\n stripeAccount: string,\n locale?: string,\n ): Promise {\n return this._scriptLoader.loadScript('https://js.stripe.com/v3/').then(() => {\n if (!this._window.Stripe) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this._window.Stripe(stripePublishableKey, {\n stripeAccount,\n locale,\n betas: ['payment_intent_beta_3', 'alipay_pm_beta_1'],\n apiVersion: '2020-03-02;alipay_beta=v1',\n });\n });\n }\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { NotInitializedError, NotInitializedErrorType } from '../../../common/error/errors';\n\nimport WepayRisk from './wepay-risk';\nimport WepayWindow from './wepay-window';\n\nconst SCRIPT_SRC = '//static.wepay.com/min/js/risk.1.latest.js';\n\nexport default class WepayRiskClient {\n private _riskClient?: WepayRisk;\n\n constructor(private _scriptLoader: ScriptLoader) {}\n\n initialize(): Promise {\n return this._scriptLoader\n .loadScript(SCRIPT_SRC)\n .then(() => (this._riskClient = (window as unknown as WepayWindow).WePay.risk))\n .then(() => this);\n }\n\n getRiskToken(): string {\n if (!this._riskClient) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n this._riskClient.generate_risk_token();\n\n return this._riskClient.get_risk_token();\n }\n}\n","import { merge } from 'lodash';\n\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { HostedFormFactory } from '../../../hosted-form';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nimport WepayRiskClient from './wepay-risk-client';\n\nexport default class WepayPaymentStrategy extends CreditCardPaymentStrategy {\n constructor(\n store: CheckoutStore,\n orderActionCreator: OrderActionCreator,\n paymentActionCreator: PaymentActionCreator,\n hostedFormFactory: HostedFormFactory,\n private _wepayRiskClient: WepayRiskClient,\n ) {\n super(store, orderActionCreator, paymentActionCreator, hostedFormFactory);\n }\n\n initialize(options: PaymentInitializeOptions): Promise {\n void this._wepayRiskClient.initialize();\n\n return super.initialize(options);\n }\n\n execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const token = this._wepayRiskClient.getRiskToken();\n const payloadWithToken = merge({}, payload, {\n payment: {\n paymentData: {\n deviceSessionId: token,\n },\n },\n });\n\n return super.execute(payloadWithToken, options);\n }\n}\n","import { merge, some } from 'lodash';\n\nimport { InternalCheckoutSelectors } from '../../../checkout';\nimport {\n NotInitializedError,\n NotInitializedErrorType,\n RequestError,\n} from '../../../common/error/errors';\nimport { OrderPaymentRequestBody, OrderRequestBody } from '../../../order';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport { PaymentInitializeOptions } from '../../payment-request-options';\nimport { CreditCardPaymentStrategy } from '../credit-card';\n\nimport {\n WorldpayAccess3DSOptions,\n WorldpayAccessAdditionalAction,\n WorldpayAccessPaymentInitializeOptions,\n} from './worldpayaccess-payment-options';\n\nconst IFRAME_NAME = 'worldpay_hosted_payment_page';\nconst IFRAME_HIDDEN_NAME = 'worldpay_hosted_hidden_payment_page';\nconst PAYMENT_CANNOT_CONTINUE = 'Payment cannot continue';\n\nlet submit: (paymentPayload: OrderPaymentRequestBody) => Promise;\n\nexport default class WorldpayaccessPaymetStrategy extends CreditCardPaymentStrategy {\n private _initializeOptions?: WorldpayAccessPaymentInitializeOptions;\n\n async initialize(options?: PaymentInitializeOptions): Promise {\n this._initializeOptions = options && options.worldpay;\n\n if (!this._initializeOptions) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return super.initialize(options);\n }\n\n async execute(\n orderRequest: OrderRequestBody,\n options?: PaymentInitializeOptions,\n ): Promise {\n const { payment } = orderRequest;\n\n submit = this._submitAdditionalAction();\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n try {\n return await super.execute(orderRequest, options);\n } catch (error) {\n return await this._processAdditionalAction(error, payment);\n }\n }\n\n private async _processAdditionalAction(\n error: unknown,\n payment: OrderPaymentRequestBody,\n ): Promise {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'additional_action_required' })\n ) {\n return Promise.reject(error);\n }\n\n return new Promise((resolve, reject) => {\n const messageEvent = async (event: MessageEvent) => {\n if (typeof event.data !== 'string' || !this._isValidJsonWithSessionId(event.data)) {\n return reject(new Error(PAYMENT_CANNOT_CONTINUE));\n }\n\n window.removeEventListener('message', messageEvent);\n window.removeEventListener('remove_event_message', removeEvent);\n iframeHidden.remove();\n\n const data = JSON.parse(event.data);\n const paymentPayload = merge({}, payment, {\n paymentData: { threeDSecure: { token: data.SessionId } },\n });\n\n try {\n resolve(await submit(paymentPayload));\n } catch (error) {\n if (\n !(error instanceof RequestError) ||\n !some(error.body.errors, { code: 'three_d_secure_required' })\n ) {\n return reject(error);\n }\n\n if (!this._initializeOptions) {\n return reject(\n new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized),\n );\n }\n\n const { onLoad } = this._initializeOptions;\n const frame = this._createIframe(error.body.three_ds_result);\n\n try {\n onLoad(frame, () => reject(new Error('Payment was cancelled')));\n } catch (e) {\n reject(new Error(PAYMENT_CANNOT_CONTINUE));\n }\n }\n };\n\n const removeEvent = () => {\n window.removeEventListener('remove_event_message', removeEvent);\n window.removeEventListener('message', messageEvent);\n iframeHidden.remove();\n\n return reject(new Error(PAYMENT_CANNOT_CONTINUE));\n };\n\n window.addEventListener('message', messageEvent);\n window.addEventListener('remove_event_message', removeEvent);\n\n let iframeHidden: HTMLIFrameElement;\n\n try {\n iframeHidden = this._createHiddenIframe(error.body);\n } catch (e) {\n window.removeEventListener('remove_event_message', removeEvent);\n window.removeEventListener('message', messageEvent);\n throw new Error(PAYMENT_CANNOT_CONTINUE);\n }\n });\n }\n\n private _createHiddenIframe(body: WorldpayAccessAdditionalAction): HTMLIFrameElement {\n const iframe = document.createElement('iframe');\n\n if (!iframe) {\n throw new Error();\n }\n\n document.body.appendChild(iframe);\n\n if (!iframe.contentWindow) {\n throw new Error();\n }\n\n iframe.id = IFRAME_HIDDEN_NAME;\n iframe.height = '0px';\n iframe.width = '0px';\n\n const form = document.createElement('form');\n const formId = 'collectionForm';\n\n form.id = formId;\n form.name = 'devicedata';\n form.method = 'post';\n\n const url = body.additional_action_required.data.redirect_url;\n\n form.action = url;\n\n const inputBin = document.createElement('input');\n\n inputBin.name = 'Bin';\n inputBin.type = 'hidden';\n inputBin.value = body.provider_data.source_id;\n form.appendChild(inputBin);\n\n const inputJWT = document.createElement('input');\n\n inputJWT.name = 'JWT';\n inputJWT.type = 'hidden';\n inputJWT.value = body.provider_data.data;\n form.appendChild(inputJWT);\n\n const button = document.createElement('button');\n\n button.type = 'submit';\n button.id = 'btnsubmit';\n form.appendChild(button);\n\n if (navigator.userAgent.match('Firefox')) {\n iframe.srcdoc = form.outerHTML;\n } else {\n iframe.contentWindow.document.body.appendChild(form);\n }\n\n const script = document.createElement('script');\n\n script.innerHTML = `\n const data = new URLSearchParams()\n data.append('Bin', '${body.provider_data.source_id}');\n data.append('JWT', '${body.provider_data.data}');\n\n window.parent.fetch('${url}', {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: data\n })\n .then((response) => {\n if (!response.ok) {\n window.parent.dispatchEvent(new Event('remove_event_message'));\n } else {\n document.getElementById('${formId}').submit();\n }\n })\n .catch((error) => {\n window.parent.dispatchEvent(new Event('remove_event_message'));\n })\n `;\n iframe.contentWindow.document.body.appendChild(script);\n\n return iframe;\n }\n\n private _createIframe(data: WorldpayAccess3DSOptions): HTMLIFrameElement {\n const form = document.createElement('form');\n\n form.id = 'challengeForm';\n form.method = 'POST';\n form.action = data.acs_url;\n\n const inputJWT = document.createElement('input');\n\n inputJWT.name = 'JWT';\n inputJWT.type = 'hidden';\n inputJWT.value = data.payer_auth_request;\n form.appendChild(inputJWT);\n\n const merchant = document.createElement('input');\n\n merchant.name = 'MD';\n merchant.type = 'hidden';\n merchant.value = `merchantSessionId=${data.merchant_data}`;\n form.appendChild(merchant);\n\n const script = document.createElement('script');\n\n script.type = 'text/javascript';\n script.innerHTML =\n \"window.onload = function() { document.getElementById('challengeForm').submit(); }\";\n\n const iframe = document.createElement('iframe');\n\n iframe.name = IFRAME_NAME;\n iframe.height = '400';\n iframe.width = '100%';\n iframe.srcdoc = `${form.outerHTML} ${script.outerHTML}`;\n\n return iframe;\n }\n\n private _submitAdditionalAction() {\n if (this._shouldRenderHostedForm) {\n if (!this._hostedForm || !this._hostedForm.submit) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n const hostedForm = this._hostedForm;\n\n return async (paymentPayload: OrderPaymentRequestBody) => {\n await hostedForm.submit(paymentPayload);\n\n return this._store.getState();\n };\n }\n\n return async (paymentPayload: OrderPaymentRequestBody) => {\n return this._store.dispatch(this._paymentActionCreator.submitPayment(paymentPayload));\n };\n }\n\n private _isValidJsonWithSessionId(str: string) {\n try {\n const data = JSON.parse(str);\n\n if (data.SessionId) {\n return true;\n }\n\n return false;\n } catch (e) {\n return false;\n }\n }\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport { MissingDataError, MissingDataErrorType, RequestError } from '../../../common/error/errors';\nimport { OrderActionCreator, OrderRequestBody } from '../../../order';\nimport { OrderFinalizationNotRequiredError } from '../../../order/errors';\nimport { RemoteCheckoutActionCreator } from '../../../remote-checkout';\nimport { StoreCreditActionCreator } from '../../../store-credit';\nimport { PaymentArgumentInvalidError } from '../../errors';\nimport PaymentActionCreator from '../../payment-action-creator';\nimport PaymentMethodActionCreator from '../../payment-method-action-creator';\nimport { PaymentRequestOptions } from '../../payment-request-options';\nimport StorefrontPaymentRequestSender from '../../storefront-payment-request-sender';\nimport PaymentStrategy from '../payment-strategy';\n\nexport default class ZipPaymentStrategy implements PaymentStrategy {\n constructor(\n private _store: CheckoutStore,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _storeCreditActionCreator: StoreCreditActionCreator,\n private _remoteCheckoutActionCreator: RemoteCheckoutActionCreator,\n private _orderActionCreator: OrderActionCreator,\n private _storefrontPaymentRequestSender: StorefrontPaymentRequestSender,\n private _paymentActionCreator: PaymentActionCreator,\n ) {}\n\n initialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n async execute(\n payload: OrderRequestBody,\n options?: PaymentRequestOptions,\n ): Promise {\n const { payment, ...order } = payload;\n\n if (!payment) {\n throw new PaymentArgumentInvalidError(['payment']);\n }\n\n const { methodId } = payment;\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId, options),\n );\n const { clientToken, initializationData: { redirectUrl } = {} } =\n getPaymentMethodOrThrow(methodId);\n\n if (!clientToken || !redirectUrl) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { id: nonce } = JSON.parse(clientToken);\n\n if (!nonce) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentToken);\n }\n\n const { isStoreCreditApplied: useStoreCredit } = this._store\n .getState()\n .checkout.getCheckoutOrThrow();\n\n await this._store.dispatch(this._storeCreditActionCreator.applyStoreCredit(useStoreCredit));\n await this._store.dispatch(\n this._remoteCheckoutActionCreator.initializePayment(methodId, { useStoreCredit }),\n );\n await this._store.dispatch(this._orderActionCreator.submitOrder(order, options));\n await this._prepareForReferredRegistration(methodId, nonce);\n\n try {\n return await this._store.dispatch(\n this._paymentActionCreator.submitPayment({ methodId, paymentData: { nonce } }),\n );\n } catch (error) {\n if (\n error instanceof RequestError &&\n error.body.status === 'additional_action_required'\n ) {\n return new Promise(() => window.location.replace(redirectUrl));\n }\n\n throw error;\n }\n }\n\n finalize(): Promise {\n return Promise.reject(new OrderFinalizationNotRequiredError());\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n private _prepareForReferredRegistration(methodId: string, externalId: string): Promise {\n return this._storefrontPaymentRequestSender.saveExternalId(methodId, externalId);\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { VaultAccessToken } from './instrument';\nimport { InstrumentsResponseBody } from './instrument-response-body';\n\nexport enum InstrumentActionType {\n LoadInstrumentsRequested = 'LOAD_INSTRUMENTS_REQUESTED',\n LoadInstrumentsSucceeded = 'LOAD_INSTRUMENTS_SUCCEEDED',\n LoadInstrumentsFailed = 'LOAD_INSTRUMENTS_FAILED',\n\n DeleteInstrumentRequested = 'DELETE_INSTRUMENT_REQUESTED',\n DeleteInstrumentSucceeded = 'DELETE_INSTRUMENT_SUCCEEDED',\n DeleteInstrumentFailed = 'DELETE_INSTRUMENT_FAILED',\n}\n\nexport type InstrumentAction = LoadInstrumentsAction | DeleteInstrumentAction;\n\nexport type LoadInstrumentsAction =\n | LoadInstrumentsRequestedAction\n | LoadInstrumentsSucceededAction\n | LoadInstrumentsFailedAction;\n\nexport type DeleteInstrumentAction =\n | DeleteInstrumentRequestedAction\n | DeleteInstrumentSucceededAction\n | DeleteInstrumentFailedAction;\n\nexport interface LoadInstrumentsRequestedAction extends Action {\n type: InstrumentActionType.LoadInstrumentsRequested;\n}\n\nexport interface LoadInstrumentsSucceededAction\n extends Action {\n type: InstrumentActionType.LoadInstrumentsSucceeded;\n}\n\nexport interface LoadInstrumentsFailedAction extends Action {\n type: InstrumentActionType.LoadInstrumentsFailed;\n}\n\nexport interface DeleteInstrumentRequestedAction extends Action {\n type: InstrumentActionType.DeleteInstrumentRequested;\n}\n\nexport interface DeleteInstrumentSucceededAction\n extends Action {\n type: InstrumentActionType.DeleteInstrumentSucceeded;\n}\n\nexport interface DeleteInstrumentFailedAction extends Action {\n type: InstrumentActionType.DeleteInstrumentFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { Address } from '../../address';\nimport { InternalCheckoutSelectors, ReadableCheckoutStore } from '../../checkout';\nimport { addMinutes, isFuture } from '../../common/date-time';\nimport { MissingDataError, MissingDataErrorType } from '../../common/error/errors';\n\nimport { SessionContext, VaultAccessToken } from './instrument';\nimport {\n DeleteInstrumentAction,\n InstrumentActionType,\n LoadInstrumentsAction,\n} from './instrument-actions';\nimport InstrumentRequestSender from './instrument-request-sender';\n\nexport default class InstrumentActionCreator {\n constructor(private _instrumentRequestSender: InstrumentRequestSender) {}\n\n loadInstruments(): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n observer.next(createAction(InstrumentActionType.LoadInstrumentsRequested));\n\n const session = this._getSessionContext(store);\n const token = this._getCurrentAccessToken(store);\n const shippingAddress = this._getShippingAddress(store);\n\n return this._getValidAccessToken(token)\n .then((currentToken) =>\n this._instrumentRequestSender\n .loadInstruments(\n {\n ...session,\n authToken: currentToken.vaultAccessToken,\n },\n shippingAddress,\n )\n .then(({ body }) => {\n observer.next(\n createAction(\n InstrumentActionType.LoadInstrumentsSucceeded,\n body,\n currentToken,\n ),\n );\n observer.complete();\n }),\n )\n .catch((response) => {\n observer.error(\n createErrorAction(InstrumentActionType.LoadInstrumentsFailed, response),\n );\n });\n });\n }\n\n deleteInstrument(\n instrumentId: string,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n observer.next(\n createAction(InstrumentActionType.DeleteInstrumentRequested, undefined, {\n instrumentId,\n }),\n );\n\n const session = this._getSessionContext(store);\n const token = this._getCurrentAccessToken(store);\n\n return this._getValidAccessToken(token)\n .then((currentToken) =>\n this._instrumentRequestSender\n .deleteInstrument(\n {\n ...session,\n authToken: currentToken.vaultAccessToken,\n },\n instrumentId,\n )\n .then(({ body }) => {\n observer.next(\n createAction(\n InstrumentActionType.DeleteInstrumentSucceeded,\n body,\n {\n instrumentId,\n ...currentToken,\n },\n ),\n );\n observer.complete();\n }),\n )\n .catch((response) => {\n observer.error(\n createErrorAction(\n InstrumentActionType.DeleteInstrumentFailed,\n response,\n { instrumentId },\n ),\n );\n });\n });\n }\n\n private _isValidVaultAccessToken(token: VaultAccessToken): boolean {\n if (!token || !token.vaultAccessToken) {\n return false;\n }\n\n const expiryBuffer = 2;\n const expiry = addMinutes(new Date(token.vaultAccessExpiry), expiryBuffer);\n\n return isFuture(expiry);\n }\n\n private _getCurrentAccessToken(store: ReadableCheckoutStore): VaultAccessToken | undefined {\n const { instruments } = store.getState();\n const meta = instruments.getInstrumentsMeta();\n\n if (!meta) {\n return;\n }\n\n return {\n vaultAccessToken: meta.vaultAccessToken,\n vaultAccessExpiry: meta.vaultAccessExpiry,\n };\n }\n\n private _getValidAccessToken(token?: VaultAccessToken): Promise {\n return token && this._isValidVaultAccessToken(token)\n ? Promise.resolve(token)\n : this._instrumentRequestSender.getVaultAccessToken().then(({ body }) => body);\n }\n\n private _getShippingAddress(store: ReadableCheckoutStore): Address | Address[] | undefined {\n const state = store.getState();\n const addresses = state.shippingAddress.getShippingAddresses();\n\n return addresses.length > 1 ? addresses : state.shippingAddress.getShippingAddress();\n }\n\n private _getSessionContext(store: ReadableCheckoutStore): SessionContext {\n const state = store.getState();\n const config = state.config.getStoreConfig();\n const cart = state.cart.getCart();\n\n if (!config) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n const { customerId } = cart;\n const { storeId } = config.storeProfile;\n const { code } = config.shopperCurrency.isTransactional\n ? config.shopperCurrency\n : config.currency;\n\n return {\n customerId,\n storeId,\n currencyCode: code,\n };\n }\n}\n","export default function isFuture(date: Date): boolean {\n return date.valueOf() > Date.now();\n}\n","export default function addMinutes(date: Date, amount: number): Date {\n const newDate = new Date(date.getTime());\n\n newDate.setMinutes(date.getMinutes() + amount);\n\n return newDate;\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport PaymentResponse from '../payment-response';\n\nimport PaymentInstrument, { VaultAccessToken } from './instrument';\nimport {\n BankInternalInstrument,\n InstrumentErrorResponseBody,\n InstrumentsResponseBody,\n InternalInstrument,\n InternalInstrumentErrorResponseBody,\n InternalInstrumentsResponseBody,\n InternalVaultAccessTokenResponseBody,\n PayPalInternalInstrument,\n} from './instrument-response-body';\nimport { mapToBankInstrument } from './map-to-bank-instrument';\nimport { mapToCardInstrument } from './map-to-card-instrument';\nimport { mapToPayPalInstrument } from './map-to-paypal-instrument';\n\nexport default class InstrumentResponseTransformer {\n transformResponse(\n response: PaymentResponse,\n ): Response {\n const { body, ...payload } = this._transformResponse(response);\n\n return {\n ...payload,\n body: {\n vaultedInstruments: this._transformVaultedInstruments(body.vaulted_instruments),\n },\n };\n }\n\n transformErrorResponse(\n response: PaymentResponse,\n ): Response {\n return this._transformResponse(response);\n }\n\n transformVaultAccessResponse(\n response: Response,\n ): Response {\n return {\n ...response,\n body: {\n vaultAccessToken: response.body.data.token,\n vaultAccessExpiry: response.body.data.expires_at,\n },\n };\n }\n\n private _transformVaultedInstruments(\n vaultedInstruments: InternalInstrument[] = [],\n ): PaymentInstrument[] {\n return vaultedInstruments.map((instrument) => {\n if (this._isPayPalInstrument(instrument)) {\n return mapToPayPalInstrument(instrument);\n }\n\n if (this._isBankInstrument(instrument)) {\n return mapToBankInstrument(instrument);\n }\n\n return mapToCardInstrument(instrument);\n });\n }\n\n private _isPayPalInstrument(\n instrument: InternalInstrument,\n ): instrument is PayPalInternalInstrument {\n return instrument.method_type === 'paypal';\n }\n\n private _isBankInstrument(\n instrument: InternalInstrument,\n ): instrument is BankInternalInstrument {\n return instrument.method_type === 'bank';\n }\n\n private _transformResponse(response: PaymentResponse): Response {\n const { data: body, ...payload } = response;\n\n return {\n ...payload,\n body,\n };\n }\n}\n","import { PayPalInstrument } from './instrument';\nimport { PayPalInternalInstrument } from './instrument-response-body';\n\nexport function mapToPayPalInstrument(instrument: PayPalInternalInstrument): PayPalInstrument {\n return {\n bigpayToken: instrument.bigpay_token,\n defaultInstrument: instrument.default_instrument,\n provider: instrument.provider,\n externalId: instrument.external_id,\n trustedShippingAddress: instrument.trusted_shipping_address,\n method: 'paypal',\n type: 'account',\n };\n}\n","import { BankInstrument } from './instrument';\nimport { BankInternalInstrument } from './instrument-response-body';\n\nexport function mapToBankInstrument(instrument: BankInternalInstrument): BankInstrument {\n return {\n bigpayToken: instrument.bigpay_token,\n defaultInstrument: instrument.default_instrument,\n provider: instrument.provider,\n trustedShippingAddress: instrument.trusted_shipping_address,\n accountNumber: instrument.account_number,\n issuer: instrument.issuer,\n iban: instrument.iban,\n method: instrument.method,\n type: 'bank',\n };\n}\n","import { CardInstrument } from './instrument';\nimport { CardInternalInstrument } from './instrument-response-body';\n\nexport function mapToCardInstrument(instrument: CardInternalInstrument): CardInstrument {\n return {\n bigpayToken: instrument.bigpay_token,\n defaultInstrument: instrument.default_instrument,\n provider: instrument.provider,\n iin: instrument.iin,\n last4: instrument.last_4,\n expiryMonth: instrument.expiry_month,\n expiryYear: instrument.expiry_year,\n brand: instrument.brand,\n trustedShippingAddress: instrument.trusted_shipping_address,\n untrustedShippingCardVerificationMode:\n instrument.untrusted_shipping_address_card_verification_mode,\n method: instrument.method,\n type: 'card',\n };\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { Address, mapToInternalAddress } from '../../address';\nimport { RequestOptions } from '../../common/http-request';\nimport PaymentResponse from '../payment-response';\n\nimport { InstrumentRequestContext, VaultAccessToken } from './instrument';\nimport {\n InstrumentsResponseBody,\n InternalInstrumentErrorResponseBody,\n InternalInstrumentsResponseBody,\n InternalVaultAccessTokenResponseBody,\n} from './instrument-response-body';\nimport InstrumentResponseTransformer from './instrument-response-transformer';\n\nexport default class InstrumentRequestSender {\n private _transformer: InstrumentResponseTransformer;\n\n constructor(private _client: any, private _requestSender: RequestSender) {\n this._transformer = new InstrumentResponseTransformer();\n }\n\n getVaultAccessToken({ timeout }: RequestOptions = {}): Promise> {\n const url = '/internalapi/v1/checkout/payments/vault-access-token';\n\n return this._requestSender\n .get(url, { timeout })\n .then((response) => ({\n ...response,\n body: {\n vaultAccessToken: response.body.data.token,\n vaultAccessExpiry: response.body.data.expires_at,\n },\n }));\n }\n\n loadInstruments(\n requestContext: InstrumentRequestContext,\n shippingAddress?: Address | Address[],\n ): Promise> {\n return shippingAddress\n ? this._loadInstrumentsWithAddress(requestContext, shippingAddress)\n : this._loadInstruments(requestContext);\n }\n\n deleteInstrument(\n requestContext: InstrumentRequestContext,\n instrumentId: string,\n ): Promise> {\n const payload = {\n ...requestContext,\n instrumentId,\n };\n\n return new Promise((resolve, reject) => {\n this._client.deleteShopperInstrument(\n payload,\n (\n errorResponse: PaymentResponse,\n response: PaymentResponse,\n ) =>\n errorResponse\n ? reject(this._transformer.transformErrorResponse(errorResponse))\n : resolve(this._transformer.transformResponse(response)),\n );\n });\n }\n\n private _loadInstruments(\n requestContext: InstrumentRequestContext,\n ): Promise> {\n return new Promise((resolve, reject) => {\n this._client.loadInstruments(\n requestContext,\n (\n errorResponse: PaymentResponse,\n response: PaymentResponse,\n ) =>\n errorResponse\n ? reject(this._transformer.transformErrorResponse(errorResponse))\n : resolve(this._transformer.transformResponse(response)),\n );\n });\n }\n\n private _loadInstrumentsWithAddress(\n requestContext: InstrumentRequestContext,\n shippingAddress: Address | Address[],\n ): Promise> {\n const payload = {\n ...requestContext,\n shippingAddress: Array.isArray(shippingAddress)\n ? shippingAddress.map((address) => mapToInternalAddress(address))\n : mapToInternalAddress(shippingAddress),\n };\n\n return new Promise((resolve, reject) => {\n this._client.loadInstrumentsWithAddress(\n payload,\n (\n errorResponse: PaymentResponse,\n response: PaymentResponse,\n ) =>\n errorResponse\n ? reject(this._transformer.transformErrorResponse(errorResponse))\n : resolve(this._transformer.transformResponse(response)),\n );\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { PickupOptionMeta, PickupOptionResult } from './pickup-option';\n\nexport enum PickupOptionActionType {\n LoadPickupOptionsRequested = 'LOAD_PICKUP_OPTIONS_REQUESTED',\n LoadPickupOptionsSucceeded = 'LOAD_PICKUP_OPTIONS_SUCCEEDED',\n LoadPickupOptionsFailed = 'LOAD_PICKUP_OPTIONS_FAILED',\n}\n\nexport type LoadPickupOptionsAction =\n | PickupOptionRequestedAction\n | LoadPickupOptionsSucceededAction\n | LoadPickupOptionsFailedAction;\n\nexport interface PickupOptionRequestedAction extends Action {\n type: PickupOptionActionType.LoadPickupOptionsRequested;\n}\n\nexport interface LoadPickupOptionsSucceededAction\n extends Action {\n type: PickupOptionActionType.LoadPickupOptionsSucceeded;\n}\n\nexport interface LoadPickupOptionsFailedAction extends Action {\n type: PickupOptionActionType.LoadPickupOptionsFailed;\n}\n","import {\n createAction,\n createErrorAction,\n ReadableDataStore,\n ThunkAction,\n} from '@bigcommerce/data-store';\nimport { includes } from 'lodash';\nimport { Observable, Observer } from 'rxjs';\n\nimport { LineItem } from '../cart';\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\n\nimport { PickupOptionAPIRequestBody, PickupOptionRequestBody } from './pickup-option';\nimport { LoadPickupOptionsAction, PickupOptionActionType } from './pickup-option-actions';\nimport PickupOptionRequestSender from './pickup-option-request-sender';\n\nexport default class PickupOptionActionCreator {\n constructor(private _pickupOptionRequestSender: PickupOptionRequestSender) {}\n\n loadPickupOptions(\n query: PickupOptionRequestBody,\n ): ThunkAction {\n return (store) =>\n new Observable((observer: Observer) => {\n const apiQuery = this._hydrateApiQuery(store, query);\n\n observer.next(createAction(PickupOptionActionType.LoadPickupOptionsRequested));\n\n this._pickupOptionRequestSender\n .fetchPickupOptions(apiQuery)\n .then((response) => {\n observer.next(\n createAction(\n PickupOptionActionType.LoadPickupOptionsSucceeded,\n response.body.results,\n query,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n PickupOptionActionType.LoadPickupOptionsFailed,\n response,\n ),\n );\n });\n });\n }\n\n private _hydrateApiQuery(\n store: ReadableDataStore,\n query: PickupOptionRequestBody,\n ): PickupOptionAPIRequestBody {\n const state = store.getState();\n const cart = state.cart.getCartOrThrow();\n\n if (!cart) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n const consignment = state.consignments.getConsignmentById(query.consignmentId);\n\n if (!consignment) {\n throw new MissingDataError(MissingDataErrorType.MissingConsignments);\n }\n\n const consignmentLineItems = consignment.lineItemIds;\n const physicalItems = cart.lineItems.physicalItems;\n const cartItems = physicalItems\n .filter((item: LineItem) => includes(consignmentLineItems, item.id))\n .map((item) => ({\n variantId: item.variantId,\n quantity: item.quantity,\n }));\n\n return {\n searchArea: query.searchArea,\n items: cartItems,\n };\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { ContentType, SDK_VERSION_HEADERS } from '../common/http-request';\n\nimport { PickupOptionAPIRequestBody, PickupOptionResponse } from './pickup-option';\n\nconst url = '/api/storefront/pickup-options';\n\nexport default class PickupOptionRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n fetchPickupOptions(query: PickupOptionAPIRequestBody): Promise> {\n return this._requestSender.post(url, {\n headers: { Accept: ContentType.Json, ...SDK_VERSION_HEADERS },\n body: query,\n });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { Country } from '../geography';\n\nexport enum ShippingCountryActionType {\n LoadShippingCountriesRequested = 'LOAD_SHIPPING_COUNTRIES_REQUESTED',\n LoadShippingCountriesSucceeded = 'LOAD_SHIPPING_COUNTRIES_SUCCEEDED',\n LoadShippingCountriesFailed = 'LOAD_SHIPPING_COUNTRIES_FAILED',\n}\n\nexport type LoadShippingCountriesAction =\n | LoadShippingCountriesRequestedAction\n | LoadShippingCountriesSucceededAction\n | LoadShippingCountriesFailedAction;\n\nexport interface LoadShippingCountriesRequestedAction extends Action {\n type: ShippingCountryActionType.LoadShippingCountriesRequested;\n}\n\nexport interface LoadShippingCountriesSucceededAction extends Action {\n type: ShippingCountryActionType.LoadShippingCountriesSucceeded;\n}\n\nexport interface LoadShippingCountriesFailedAction extends Action {\n type: ShippingCountryActionType.LoadShippingCountriesFailed;\n}\n","import { createAction, createErrorAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { RequestOptions } from '../common/http-request';\n\nimport { LoadShippingCountriesAction, ShippingCountryActionType } from './shipping-country-actions';\nimport ShippingCountryRequestSender from './shipping-country-request-sender';\n\nexport default class ShippingCountryActionCreator {\n constructor(private _shippingCountryRequestSender: ShippingCountryRequestSender) {}\n\n loadCountries(options?: RequestOptions): Observable {\n return Observable.create((observer: Observer) => {\n observer.next(createAction(ShippingCountryActionType.LoadShippingCountriesRequested));\n\n this._shippingCountryRequestSender\n .loadCountries(options)\n .then((response) => {\n observer.next(\n createAction(\n ShippingCountryActionType.LoadShippingCountriesSucceeded,\n response.body.data,\n ),\n );\n observer.complete();\n })\n .catch((response) => {\n observer.error(\n createErrorAction(\n ShippingCountryActionType.LoadShippingCountriesFailed,\n response,\n ),\n );\n });\n });\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\nimport { CountryResponseBody } from '../geography';\n\nexport default class ShippingCountryRequestSender {\n constructor(private _requestSender: RequestSender, private _config: { locale?: string }) {}\n\n loadCountries({ timeout }: RequestOptions = {}): Promise> {\n const url = '/internalapi/v1/shipping/countries';\n const headers = {\n 'Accept-Language': this._config.locale,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.get(url, { headers, timeout });\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nexport enum ShippingStrategyActionType {\n UpdateAddressFailed = 'SHIPPING_STRATEGY_UPDATE_ADDRESS_FAILED',\n UpdateAddressRequested = 'SHIPPING_STRATEGY_UPDATE_ADDRESS_REQUESTED',\n UpdateAddressSucceeded = 'SHIPPING_STRATEGY_UPDATE_ADDRESS_SUCCEEDED',\n SelectOptionFailed = 'SHIPPING_STRATEGY_SELECT_OPTION_FAILED',\n SelectOptionRequested = 'SHIPPING_STRATEGY_SELECT_OPTION_REQUESTED',\n SelectOptionSucceeded = 'SHIPPING_STRATEGY_SELECT_OPTION_SUCCEEDED',\n InitializeFailed = 'SHIPPING_STRATEGY_INITIALIZE_FAILED',\n InitializeRequested = 'SHIPPING_STRATEGY_INITIALIZE_REQUESTED',\n InitializeSucceeded = 'SHIPPING_STRATEGY_INITIALIZE_SUCCEEDED',\n DeinitializeFailed = 'SHIPPING_STRATEGY_DEINITIALIZE_FAILED',\n DeinitializeRequested = 'SHIPPING_STRATEGY_DEINITIALIZE_REQUESTED',\n DeinitializeSucceeded = 'SHIPPING_STRATEGY_DEINITIALIZE_SUCCEEDED',\n WidgetInteractionStarted = 'SHIPPING_STRATEGY_WIDGET_INTERACTION_STARTED',\n WidgetInteractionFinished = 'SHIPPING_STRATEGY_WIDGET_INTERACTION_FINISHED',\n WidgetInteractionFailed = 'SHIPPING_STRATEGY_WIDGET_INTERACTION_FAILED',\n}\n\nexport type ShippingStrategyAction =\n | ShippingStrategyUpdateAddressAction\n | ShippingStrategySelectOptionAction\n | ShippingStrategyInitializeAction\n | ShippingStrategyDeinitializeAction\n | ShippingStrategyWidgetAction;\n\nexport type ShippingStrategyUpdateAddressAction =\n | UpdateAddressRequestedAction\n | UpdateAddressSucceededAction\n | UpdateAddressFailedAction;\n\nexport type ShippingStrategySelectOptionAction =\n | SelectOptionRequestedAction\n | SelectOptionSucceededAction\n | SelectOptionFailedAction;\n\nexport type ShippingStrategyInitializeAction =\n | InitializeRequestedAction\n | InitializeSucceededAction\n | InitializeFailedAction;\n\nexport type ShippingStrategyDeinitializeAction =\n | DeinitializeRequestedAction\n | DeinitializeSucceededAction\n | DeinitializeFailedAction;\n\nexport type ShippingStrategyWidgetAction =\n | WidgetInteractionStartedAction\n | WidgetInteractionFinishedAction\n | WidgetInteractionFailedAction;\n\nexport interface UpdateAddressRequestedAction extends Action {\n type: ShippingStrategyActionType.UpdateAddressRequested;\n}\n\nexport interface UpdateAddressSucceededAction extends Action {\n type: ShippingStrategyActionType.UpdateAddressSucceeded;\n}\n\nexport interface UpdateAddressFailedAction extends Action {\n type: ShippingStrategyActionType.UpdateAddressFailed;\n}\n\nexport interface SelectOptionRequestedAction extends Action {\n type: ShippingStrategyActionType.SelectOptionRequested;\n}\n\nexport interface SelectOptionSucceededAction extends Action {\n type: ShippingStrategyActionType.SelectOptionSucceeded;\n}\n\nexport interface SelectOptionFailedAction extends Action {\n type: ShippingStrategyActionType.SelectOptionFailed;\n}\n\nexport interface InitializeRequestedAction extends Action {\n type: ShippingStrategyActionType.InitializeRequested;\n}\n\nexport interface InitializeSucceededAction extends Action {\n type: ShippingStrategyActionType.InitializeSucceeded;\n}\n\nexport interface InitializeFailedAction extends Action {\n type: ShippingStrategyActionType.InitializeFailed;\n}\n\nexport interface DeinitializeRequestedAction extends Action {\n type: ShippingStrategyActionType.DeinitializeRequested;\n}\n\nexport interface DeinitializeSucceededAction extends Action {\n type: ShippingStrategyActionType.DeinitializeSucceeded;\n}\n\nexport interface DeinitializeFailedAction extends Action {\n type: ShippingStrategyActionType.DeinitializeFailed;\n}\n\nexport interface WidgetInteractionStartedAction extends Action {\n type: ShippingStrategyActionType.WidgetInteractionStarted;\n}\n\nexport interface WidgetInteractionFinishedAction extends Action {\n type: ShippingStrategyActionType.WidgetInteractionFinished;\n}\n\nexport interface WidgetInteractionFailedAction extends Action {\n type: ShippingStrategyActionType.WidgetInteractionFailed;\n}\n","import { createAction, createErrorAction, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable, Observer } from 'rxjs';\n\nimport { AddressRequestBody } from '../address';\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { Registry } from '../common/registry';\n\nimport { ShippingInitializeOptions, ShippingRequestOptions } from './shipping-request-options';\nimport {\n ShippingStrategyAction,\n ShippingStrategyActionType,\n ShippingStrategyDeinitializeAction,\n ShippingStrategyInitializeAction,\n ShippingStrategySelectOptionAction,\n ShippingStrategyUpdateAddressAction,\n} from './shipping-strategy-actions';\nimport { ShippingStrategy } from './strategies';\n\nexport default class ShippingStrategyActionCreator {\n constructor(private _strategyRegistry: Registry) {}\n\n updateAddress(\n address: Partial,\n options?: ShippingRequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const payment = store.getState().payment.getPaymentId();\n const methodId = (options && options.methodId) || (payment && payment.providerId);\n\n observer.next(\n createAction(ShippingStrategyActionType.UpdateAddressRequested, undefined, {\n methodId,\n }),\n );\n\n this._strategyRegistry\n .get(methodId)\n .updateAddress(address, { ...options, methodId })\n .then(() => {\n observer.next(\n createAction(\n ShippingStrategyActionType.UpdateAddressSucceeded,\n undefined,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n ShippingStrategyActionType.UpdateAddressFailed,\n error,\n { methodId },\n ),\n );\n });\n });\n }\n\n selectOption(\n shippingOptionId: string,\n options?: ShippingRequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const payment = store.getState().payment.getPaymentId();\n const methodId = (options && options.methodId) || (payment && payment.providerId);\n\n observer.next(\n createAction(ShippingStrategyActionType.SelectOptionRequested, undefined, {\n methodId,\n }),\n );\n\n this._strategyRegistry\n .get(methodId)\n .selectOption(shippingOptionId, { ...options, methodId })\n .then(() => {\n observer.next(\n createAction(\n ShippingStrategyActionType.SelectOptionSucceeded,\n undefined,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n ShippingStrategyActionType.SelectOptionFailed,\n error,\n { methodId },\n ),\n );\n });\n });\n }\n\n initialize(\n options?: ShippingInitializeOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const payment = state.payment.getPaymentId();\n const methodId = (options && options.methodId) || (payment && payment.providerId);\n const mergedOptions = { ...options, methodId };\n\n if (methodId && state.shippingStrategies.isInitialized(methodId)) {\n return observer.complete();\n }\n\n observer.next(\n createAction(ShippingStrategyActionType.InitializeRequested, undefined, {\n methodId,\n }),\n );\n\n this._strategyRegistry\n .get(methodId)\n .initialize(mergedOptions)\n .then(() => {\n observer.next(\n createAction(\n ShippingStrategyActionType.InitializeSucceeded,\n undefined,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(ShippingStrategyActionType.InitializeFailed, error, {\n methodId,\n }),\n );\n });\n });\n }\n\n deinitialize(\n options?: ShippingRequestOptions,\n ): ThunkAction {\n return (store) =>\n Observable.create((observer: Observer) => {\n const state = store.getState();\n const payment = state.payment.getPaymentId();\n const methodId = (options && options.methodId) || (payment && payment.providerId);\n\n if (methodId && !state.shippingStrategies.isInitialized(methodId)) {\n return observer.complete();\n }\n\n observer.next(\n createAction(ShippingStrategyActionType.DeinitializeRequested, undefined, {\n methodId,\n }),\n );\n\n this._strategyRegistry\n .get(methodId)\n .deinitialize({ ...options, methodId })\n .then(() => {\n observer.next(\n createAction(\n ShippingStrategyActionType.DeinitializeSucceeded,\n undefined,\n { methodId },\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n ShippingStrategyActionType.DeinitializeFailed,\n error,\n { methodId },\n ),\n );\n });\n });\n }\n\n widgetInteraction(\n method: () => Promise,\n options?: ShippingRequestOptions,\n ): Observable {\n return Observable.create((observer: Observer) => {\n const methodId = options && options.methodId;\n const meta = { methodId };\n\n observer.next(\n createAction(ShippingStrategyActionType.WidgetInteractionStarted, undefined, meta),\n );\n\n method()\n .then(() => {\n observer.next(\n createAction(\n ShippingStrategyActionType.WidgetInteractionFinished,\n undefined,\n meta,\n ),\n );\n observer.complete();\n })\n .catch((error) => {\n observer.error(\n createErrorAction(\n ShippingStrategyActionType.WidgetInteractionFailed,\n error,\n meta,\n ),\n );\n });\n });\n }\n}\n","import { noop } from 'rxjs';\n\nimport { ConsignmentActionCreator, ShippingStrategyActionCreator } from '../..';\nimport { AddressRequestBody } from '../../../address';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../../../common/error/errors';\nimport { PaymentMethodActionCreator } from '../../../payment';\nimport {\n AmazonPayV2ChangeActionType,\n AmazonPayV2PaymentProcessor,\n} from '../../../payment/strategies/amazon-pay-v2';\nimport { ShippingInitializeOptions, ShippingRequestOptions } from '../../shipping-request-options';\nimport ShippingStrategy from '../shipping-strategy';\n\nexport default class AmazonPayV2ShippingStrategy implements ShippingStrategy {\n constructor(\n private _store: CheckoutStore,\n private _consignmentActionCreator: ConsignmentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _amazonPayV2PaymentProcessor: AmazonPayV2PaymentProcessor,\n private _shippingStrategyActionCreator: ShippingStrategyActionCreator,\n ) {}\n\n updateAddress(\n address: AddressRequestBody,\n options?: ShippingRequestOptions,\n ): Promise {\n const shippingAddress = this._store.getState().shippingAddress.getShippingAddress();\n\n if (!shippingAddress) {\n throw new MissingDataError(MissingDataErrorType.MissingShippingAddress);\n }\n\n const updateAddressRequestBody = {\n ...shippingAddress,\n customFields: address.customFields,\n };\n\n return this._store.dispatch(\n this._consignmentActionCreator.updateAddress(updateAddressRequestBody, options),\n );\n }\n\n selectOption(\n optionId: string,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(\n this._consignmentActionCreator.selectShippingOption(optionId, options),\n );\n }\n\n async initialize(options: ShippingInitializeOptions): Promise {\n const { amazonpay, methodId } = options;\n\n if (!amazonpay || !methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"options.amazonpay\" argument is not provided.',\n );\n }\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n await this._amazonPayV2PaymentProcessor.initialize(paymentMethod);\n\n const { paymentToken, region } = paymentMethod.initializationData;\n const buttonId = amazonpay.editAddressButtonId;\n\n if (paymentToken && buttonId) {\n const shouldShowLoadingSpinner = this._shouldShowLoadingSpinner(region);\n\n this._bindEditButton(buttonId, paymentToken, 'changeAddress', shouldShowLoadingSpinner);\n }\n\n return this._store.getState();\n }\n\n async deinitialize(): Promise {\n await this._amazonPayV2PaymentProcessor.deinitialize();\n\n return Promise.resolve(this._store.getState());\n }\n\n private _bindEditButton(\n id: string,\n sessionId: string,\n changeAction: AmazonPayV2ChangeActionType,\n shouldShowLoadingSpinner: boolean,\n ): void {\n const button = document.getElementById(id);\n\n if (!button || !button.parentNode) {\n return;\n }\n\n if (shouldShowLoadingSpinner) {\n const clone = button.cloneNode(true);\n\n button.parentNode.replaceChild(clone, button);\n\n clone.addEventListener('click', () => this._showLoadingSpinner());\n }\n\n this._amazonPayV2PaymentProcessor.bindButton(id, sessionId, changeAction);\n }\n\n private _showLoadingSpinner(): Promise {\n return this._store.dispatch(\n this._shippingStrategyActionCreator.widgetInteraction(() => new Promise(noop)),\n { queueId: 'widgetInteraction' },\n );\n }\n\n private _shouldShowLoadingSpinner(region: string) {\n return region !== 'us';\n }\n}\n","import { AddressRequestBody } from '../../../address';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport ConsignmentActionCreator from '../../consignment-action-creator';\nimport { ShippingRequestOptions } from '../../shipping-request-options';\nimport ShippingStrategy from '../shipping-strategy';\n\nexport default class DefaultShippingStrategy implements ShippingStrategy {\n constructor(\n private _store: CheckoutStore,\n private _consignmentActionCreator: ConsignmentActionCreator,\n ) {}\n\n updateAddress(\n address: AddressRequestBody,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(this._consignmentActionCreator.updateAddress(address, options));\n }\n\n selectOption(\n optionId: string,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(\n this._consignmentActionCreator.selectShippingOption(optionId, options),\n );\n }\n\n initialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n return Promise.resolve(this._store.getState());\n }\n}\n","import { AddressRequestBody } from '../../../address';\nimport { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../../../common/error/errors';\nimport { PaymentMethodActionCreator } from '../../../payment';\nimport {\n DisplayName,\n StripeElements,\n StripeElementsCreateOptions,\n StripeElementType,\n StripeEventType,\n StripeFormMode,\n StripeScriptLoader,\n StripeUPEAppearanceOptions,\n StripeUPEClient,\n} from '../../../payment/strategies/stripe-upe';\nimport ConsignmentActionCreator from '../../consignment-action-creator';\nimport { ShippingInitializeOptions, ShippingRequestOptions } from '../../shipping-request-options';\nimport ShippingStrategy from '../shipping-strategy';\n\nexport default class StripeUPEShippingStrategy implements ShippingStrategy {\n private _stripeUPEClient?: StripeUPEClient;\n private _stripeElements?: StripeElements;\n private sendData?: ReturnType;\n\n constructor(\n private _store: CheckoutStore,\n private _stripeUPEScriptLoader: StripeScriptLoader,\n private _consignmentActionCreator: ConsignmentActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n ) {}\n\n updateAddress(\n address: AddressRequestBody,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(this._consignmentActionCreator.updateAddress(address, options));\n }\n\n selectOption(\n optionId: string,\n options?: ShippingRequestOptions,\n ): Promise {\n return this._store.dispatch(\n this._consignmentActionCreator.selectShippingOption(optionId, options),\n );\n }\n\n async initialize(options: ShippingInitializeOptions): Promise {\n if (!options.stripeupe) {\n throw new InvalidArgumentError(\n `Unable to proceed because \"options\" argument is not provided.`,\n );\n }\n\n const {\n container,\n gatewayId,\n methodId,\n onChangeShipping,\n getStyles,\n availableCountries,\n getStripeState,\n } = options.stripeupe;\n\n Object.entries(options.stripeupe).forEach(([key, value]) => {\n if (!value) {\n throw new InvalidArgumentError(\n `Unable to proceed because \"${key}\" argument is not provided.`,\n );\n }\n });\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(gatewayId, {\n params: { method: methodId },\n }),\n );\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId, gatewayId);\n const {\n initializationData: { stripePublishableKey, stripeConnectedAccount },\n } = paymentMethod;\n\n if (\n !paymentMethod ||\n !paymentMethod.initializationData.stripePublishableKey ||\n !paymentMethod.clientToken\n ) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n this._stripeUPEClient = await this._stripeUPEScriptLoader.getStripeClient(\n stripePublishableKey,\n stripeConnectedAccount,\n );\n\n let appearance: StripeUPEAppearanceOptions;\n const styles = getStyles && getStyles();\n\n const {\n form: { getShippingAddressFields },\n shippingAddress: { getShippingAddress },\n } = this._store.getState();\n\n const shippingFields = getShippingAddressFields([], '');\n\n if (styles) {\n appearance = {\n variables: {\n colorPrimary: styles.fieldInnerShadow,\n colorBackground: styles.fieldBackground,\n colorText: styles.labelText,\n colorDanger: styles.fieldErrorText,\n colorTextSecondary: styles.labelText,\n colorTextPlaceholder: styles.fieldPlaceholderText,\n spacingUnit: '4px',\n borderRadius: '4px',\n },\n rules: {\n '.Input': {\n borderColor: styles.fieldBorder,\n color: styles.fieldText,\n boxShadow: styles.fieldInnerShadow,\n },\n },\n };\n } else {\n appearance = {\n variables: {\n spacingUnit: '4px',\n borderRadius: '4px',\n },\n };\n }\n\n this._stripeElements = this._stripeUPEScriptLoader.getElements(this._stripeUPEClient, {\n clientSecret: paymentMethod.clientToken,\n appearance,\n });\n\n const shipping = getShippingAddress();\n const shippingPhoneField = shippingFields.find((field) => field.name === 'phone');\n let option: StripeElementsCreateOptions = {\n mode: StripeFormMode.SHIPPING,\n allowedCountries: [availableCountries],\n fields: {\n phone: 'always',\n },\n validation: {\n phone: {\n required:\n shippingPhoneField && shippingPhoneField.required ? 'always' : 'never',\n },\n },\n display: {\n name: DisplayName.SPLIT,\n },\n };\n\n if (shipping) {\n const {\n stateOrProvinceCode,\n countryCode,\n lastName,\n firstName,\n phone,\n address1,\n address2,\n city,\n postalCode,\n } = shipping;\n const stripeState =\n stateOrProvinceCode && countryCode\n ? getStripeState(countryCode, stateOrProvinceCode)\n : stateOrProvinceCode;\n\n option = {\n ...option,\n defaultValues: {\n firstName,\n lastName,\n phone,\n address: {\n line1: address1,\n line2: address2,\n city,\n state: stripeState,\n postal_code: postalCode,\n country: countryCode,\n },\n },\n };\n }\n\n let shippingAddressElement = this._stripeElements.getElement(StripeElementType.SHIPPING);\n\n if (shippingAddressElement) {\n shippingAddressElement.destroy();\n }\n\n shippingAddressElement = this._stripeElements.create(StripeElementType.SHIPPING, option);\n\n shippingAddressElement.on('change', (event: StripeEventType) => {\n if (!('isNewAddress' in event)) {\n throw new MissingDataError(MissingDataErrorType.MissingShippingAddress);\n }\n\n if (event.complete || event.isNewAddress) {\n if (this.sendData) {\n clearTimeout(this.sendData);\n }\n\n this.sendData = setTimeout(() => {\n onChangeShipping({\n ...event,\n phoneFieldRequired: shippingPhoneField\n ? shippingPhoneField.required\n : false,\n });\n }, 1000);\n }\n });\n\n shippingAddressElement.mount(`#${container}`);\n\n return Promise.resolve(this._store.getState());\n }\n\n deinitialize(): Promise {\n /* The new shipping component by StripeLink has a small bug, when the component is unmounted,\n Stripe does not save the shipping, to solve this, we will leave it mounted,\n and once it is fixed will be unmounted again */\n\n // this._stripeElements?.getElement(StripeElementType.SHIPPING)?.unmount();\n\n return Promise.resolve(this._store.getState());\n }\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { SignInEmail } from './signin-email';\n\nexport enum SignInEmailActionType {\n SendSignInEmailRequested = 'SEND_SIGNIN_EMAIL_REQUESTED',\n SendSignInEmailSucceeded = 'SEND_SIGNIN_EMAIL_SUCCEEDED',\n SendSignInEmailFailed = 'SEND_SIGNIN_EMAIL_FAILED',\n}\nexport type SendSignInEmailAction =\n | SendSignInEmailRequestedAction\n | SendSignInEmailSucceededAction\n | SendSignInEmailFailedAction;\n\nexport interface SendSignInEmailRequestedAction extends Action {\n type: SignInEmailActionType.SendSignInEmailRequested;\n}\n\nexport interface SendSignInEmailSucceededAction extends Action {\n type: SignInEmailActionType.SendSignInEmailSucceeded;\n}\n\nexport interface SendSignInEmailFailedAction extends Action {\n type: SignInEmailActionType.SendSignInEmailFailed;\n}\n","import { createAction } from '@bigcommerce/data-store';\nimport { concat, defer, Observable, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { throwErrorAction } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\n\nimport { SignInEmailRequestBody } from './signin-email';\nimport { SendSignInEmailAction, SignInEmailActionType } from './signin-email-actions';\nimport SignInEmailRequestSender from './signin-email-request-sender';\n\nexport default class SignInEmailActionCreator {\n constructor(private _requestSender: SignInEmailRequestSender) {}\n\n sendSignInEmail(\n emailRequest: SignInEmailRequestBody,\n options?: RequestOptions,\n ): Observable {\n return concat(\n of(createAction(SignInEmailActionType.SendSignInEmailRequested)),\n defer(async () => {\n const { body } = await this._requestSender.sendSignInEmail(emailRequest, options);\n\n return createAction(SignInEmailActionType.SendSignInEmailSucceeded, body);\n }),\n ).pipe(\n catchError((error) =>\n throwErrorAction(SignInEmailActionType.SendSignInEmailFailed, error),\n ),\n );\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { ContentType, RequestOptions, SDK_VERSION_HEADERS } from '../common/http-request';\nimport { parseUrl } from '../common/url';\n\nimport { SignInEmail, SignInEmailRequestBody } from './signin-email';\n\nexport default class SignInEmailRequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n sendSignInEmail(\n { email, redirectUrl }: SignInEmailRequestBody,\n { timeout }: RequestOptions = {},\n ): Promise> {\n const url = '/login.php?action=passwordless_login';\n const headers = {\n Accept: ContentType.JsonV1,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post(url, {\n body: {\n email,\n redirect_url: redirectUrl || parseUrl(window.top.location.href).pathname,\n },\n headers,\n timeout,\n });\n }\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"reselect\");","import { memoize } from '@bigcommerce/memoize';\nimport { createSelector as defaultSelectorCreator } from 'reselect';\n\n/**\n * Decorate selector creators with the ability to memoize the return value of\n * their combiner if it is a function (which effectively works as a partially\n * applied combiner).\n */\nexport default function withMemoizedCombiner(\n creator: T,\n): T {\n return ((...args: any[]) => {\n const combiner = args.pop();\n\n // Reselect's default `createSelector` has many overloads. To avoid having\n // to redefine all of them, we're using `any` to bypass the typechecker.\n return (creator as any)(...args, (...combinerArgs: any[]) => {\n // Although there are many overloads, all of them have the last argument\n // as the combiner.\n const result = combiner(...combinerArgs);\n\n if (typeof result === 'function') {\n return memoize(result);\n }\n\n return result;\n });\n }) as T;\n}\n","import { createSelector as defaultSelectorCreator } from 'reselect';\n\nimport withMemoizedCombiner from './with-memoized-combiner';\n\n/**\n * This is a decorated version of Reselect's default `createSelector` function.\n * If the return value of the combiner function is a function, it will create a\n * memorized version of that function and return it instead.\n */\nexport default withMemoizedCombiner(defaultSelectorCreator);\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"shallowequal\");","import { createSelectorCreator, defaultMemoize } from 'reselect';\nimport shallowEqual from 'shallowequal';\n\nimport withMemoizedCombiner from './with-memoized-combiner';\n\nconst createShallowEqualSelector = createSelectorCreator(defaultMemoize, (a: any, b: any) =>\n shallowEqual(a, b),\n);\n\nexport default withMemoizedCombiner(createShallowEqualSelector);\n","import { toSingleLine } from '../utility';\n\nexport default class ErrorMessageTransformer {\n constructor(private _messageCustomizer: (type: TError) => string) {}\n\n transform(error: TError): TError {\n error.message = toSingleLine(this._messageCustomizer(error));\n\n return error;\n }\n}\n","export default function toSingleLine(input?: string) {\n if (!input) {\n return '';\n }\n\n return input\n .split(/(?:\\r\\n|\\n|\\r)/)\n .map((line) => line.replace(/^\\s+/gm, ''))\n .join(' ')\n .trim();\n}\n","import { Action, ThunkAction } from '@bigcommerce/data-store';\nimport { Observable } from 'rxjs';\n\nimport { AddressRequestBody } from '../address';\nimport { BillingAddressActionCreator, BillingAddressRequestBody } from '../billing';\nimport { createDataStoreProjection, DataStoreProjection } from '../common/data-store';\nimport { ErrorActionCreator, ErrorMessageTransformer } from '../common/error';\nimport { RequestOptions } from '../common/http-request';\nimport { bindDecorator as bind } from '../common/utility';\nimport { ConfigActionCreator } from '../config';\nimport { CouponActionCreator, GiftCertificateActionCreator } from '../coupon';\nimport {\n CustomerAccountRequestBody,\n CustomerActionCreator,\n CustomerAddressRequestBody,\n CustomerCredentials,\n CustomerInitializeOptions,\n CustomerRequestOptions,\n CustomerStrategyActionCreator,\n ExecutePaymentMethodCheckoutOptions,\n GuestCredentials,\n} from '../customer';\nimport { ExtensionActionCreator, ExtensionRegion } from '../extension';\nimport { FormFieldsActionCreator } from '../form';\nimport { CountryActionCreator } from '../geography';\nimport { OrderActionCreator, OrderRequestBody } from '../order';\nimport {\n PaymentInitializeOptions,\n PaymentMethodActionCreator,\n PaymentRequestOptions,\n PaymentStrategyActionCreator,\n} from '../payment';\nimport { InstrumentActionCreator } from '../payment/instrument';\nimport {\n ConsignmentActionCreator,\n ConsignmentAssignmentRequestBody,\n ConsignmentsRequestBody,\n ConsignmentUpdateRequestBody,\n PickupOptionActionCreator,\n PickupOptionRequestBody,\n ShippingCountryActionCreator,\n ShippingInitializeOptions,\n ShippingRequestOptions,\n ShippingStrategyActionCreator,\n} from '../shipping';\nimport { SignInEmailActionCreator, SignInEmailRequestBody } from '../signin-email';\nimport { SpamProtectionActionCreator, SpamProtectionOptions } from '../spam-protection';\nimport { StoreCreditActionCreator } from '../store-credit';\nimport { Subscriptions, SubscriptionsActionCreator } from '../subscription';\n\nimport { CheckoutRequestBody } from './checkout';\nimport CheckoutActionCreator from './checkout-action-creator';\nimport CheckoutParams from './checkout-params';\nimport CheckoutSelectors from './checkout-selectors';\nimport CheckoutStore from './checkout-store';\nimport {\n CheckoutSelectorsFactory,\n createCheckoutSelectorsFactory,\n} from './create-checkout-selectors';\nimport createCheckoutServiceErrorTransformer from './create-checkout-service-error-transformer';\n\n/**\n * Responsible for completing the checkout process for the current customer.\n *\n * This object can be used to collect all information that is required for\n * checkout, such as shipping and billing information. It can also be used to\n * retrieve the current checkout state and subscribe to its changes.\n */\n@bind\nexport default class CheckoutService {\n private _storeProjection: DataStoreProjection;\n private _errorTransformer: ErrorMessageTransformer;\n private _selectorsFactory: CheckoutSelectorsFactory;\n\n /**\n * @internal\n */\n constructor(\n private _store: CheckoutStore,\n private _billingAddressActionCreator: BillingAddressActionCreator,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _configActionCreator: ConfigActionCreator,\n private _customerActionCreator: CustomerActionCreator,\n private _consignmentActionCreator: ConsignmentActionCreator,\n private _countryActionCreator: CountryActionCreator,\n private _couponActionCreator: CouponActionCreator,\n private _customerStrategyActionCreator: CustomerStrategyActionCreator,\n private _errorActionCreator: ErrorActionCreator,\n private _giftCertificateActionCreator: GiftCertificateActionCreator,\n private _instrumentActionCreator: InstrumentActionCreator,\n private _orderActionCreator: OrderActionCreator,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _paymentStrategyActionCreator: PaymentStrategyActionCreator,\n private _pickupOptionActionCreator: PickupOptionActionCreator,\n private _shippingCountryActionCreator: ShippingCountryActionCreator,\n private _shippingStrategyActionCreator: ShippingStrategyActionCreator,\n private _signInEmailActionCreator: SignInEmailActionCreator,\n private _spamProtectionActionCreator: SpamProtectionActionCreator,\n private _storeCreditActionCreator: StoreCreditActionCreator,\n private _subscriptionsActionCreator: SubscriptionsActionCreator,\n private _formFieldsActionCreator: FormFieldsActionCreator,\n private _extensionActionCreator: ExtensionActionCreator,\n ) {\n this._errorTransformer = createCheckoutServiceErrorTransformer();\n this._selectorsFactory = createCheckoutSelectorsFactory();\n this._storeProjection = createDataStoreProjection(this._store, this._selectorsFactory);\n }\n\n /**\n * Returns a snapshot of the current checkout state.\n *\n * The method returns a new instance every time there is a change in the\n * checkout state. You can query the state by calling any of its getter\n * methods.\n *\n * ```js\n * const state = service.getState();\n *\n * console.log(state.data.getOrder());\n * console.log(state.errors.getSubmitOrderError());\n * console.log(state.statuses.isSubmittingOrder());\n * ```\n *\n * @returns The current customer's checkout state\n */\n getState(): CheckoutSelectors {\n return this._storeProjection.getState();\n }\n\n /**\n * Notifies all subscribers with the current state.\n *\n * When this method gets called, the subscribers get called regardless if\n * they have any filters applied.\n */\n notifyState(): void {\n this._storeProjection.notifyState();\n }\n\n /**\n * Subscribes to any changes to the current state.\n *\n * The method registers a callback function and executes it every time there\n * is a change in the checkout state.\n *\n * ```js\n * service.subscribe(state => {\n * console.log(state.data.getCart());\n * });\n * ```\n *\n * The method can be configured to notify subscribers only regarding\n * relevant changes, by providing a filter function.\n *\n * ```js\n * const filter = state => state.data.getCart();\n *\n * // Only trigger the subscriber when the cart changes.\n * service.subscribe(state => {\n * console.log(state.data.getCart())\n * }, filter);\n * ```\n *\n * @param subscriber - The function to subscribe to state changes.\n * @param filters - One or more functions to filter out irrelevant state\n * changes. If more than one function is provided, the subscriber will only\n * be triggered if all conditions are met.\n * @returns A function, if called, will unsubscribe the subscriber.\n */\n subscribe(\n subscriber: (state: CheckoutSelectors) => void,\n ...filters: Array<(state: CheckoutSelectors) => any>\n ): () => void {\n return this._storeProjection.subscribe(subscriber, ...filters);\n }\n\n /**\n * Loads the current checkout.\n *\n * This method can only be called if there is an active checkout. Also, it\n * can only retrieve data that belongs to the current customer. When it is\n * successfully executed, you can retrieve the data by calling\n * `CheckoutStoreSelector#getCheckout`.\n *\n * ```js\n * const state = await service.loadCheckout('0cfd6c06-57c3-4e29-8d7a-de55cc8a9052');\n *\n * console.log(state.data.getCheckout());\n * ```\n *\n * @param id - The identifier of the checkout to load, or the default checkout if not provided.\n * @param options - Options for loading the current checkout.\n * @returns A promise that resolves to the current state.\n */\n loadCheckout(\n id?: string,\n options?: RequestOptions,\n ): Promise {\n return this._dispatch(\n id\n ? this._checkoutActionCreator.loadCheckout(id, options)\n : this._checkoutActionCreator.loadDefaultCheckout(options),\n );\n }\n\n /**\n * Updates specific properties of the current checkout.\n *\n * ```js\n * const state = await service.updateCheckout(checkout);\n *\n * console.log(state.data.getCheckout());\n * ```\n *\n * @param payload - The checkout properties to be updated.\n * @param options - Options for loading the current checkout.\n * @returns A promise that resolves to the current state.\n */\n updateCheckout(\n payload: CheckoutRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._checkoutActionCreator.updateCheckout(payload, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Loads an order by an id.\n *\n * The method can only retrieve an order if the order belongs to the current\n * customer. If it is successfully executed, the data can be retrieved by\n * calling `CheckoutStoreSelector#getOrder`.\n *\n * ```js\n * const state = await service.loadOrder(123);\n *\n * console.log(state.data.getOrder());\n * ```\n *\n * @param orderId - The identifier of the order to load.\n * @param options - Options for loading the order.\n * @returns A promise that resolves to the current state.\n */\n loadOrder(orderId: number, options?: RequestOptions): Promise {\n const loadCheckoutAction = this._orderActionCreator.loadOrder(orderId, options);\n const formFieldsAction = this._formFieldsActionCreator.loadFormFields(options);\n const loadConfigAction = this._configActionCreator.loadConfig(options);\n\n return Promise.all([\n this._dispatch(loadCheckoutAction),\n this._dispatch(loadConfigAction, { queueId: 'config' }),\n this._dispatch(formFieldsAction, { queueId: 'formFields' }),\n ]).then(() => this.getState());\n }\n\n /**\n * Submits an order, thereby completing a checkout process.\n *\n * Before you can submit an order, you must initialize the payment method\n * chosen by the customer by calling `CheckoutService#initializePayment`.\n *\n * ```js\n * await service.initializePayment({ methodId: 'braintree' });\n * await service.submitOrder({\n * payment: {\n * methodId: 'braintree',\n * paymentData: {\n * ccExpiry: { month: 10, year: 20 },\n * ccName: 'BigCommerce',\n * ccNumber: '4111111111111111',\n * ccCvv: 123,\n * },\n * },\n * });\n * ```\n *\n * You are not required to include `paymentData` if the order does not\n * require additional payment details. For example, the customer has already\n * entered their payment details on the cart page using one of the hosted\n * payment methods, such as PayPal. Or the customer has applied a gift\n * certificate that exceeds the grand total amount.\n *\n * If the order is submitted successfully, you can retrieve the newly\n * created order by calling `CheckoutStoreSelector#getOrder`.\n *\n * ```js\n * const state = await service.submitOrder(payload);\n *\n * console.log(state.data.getOrder());\n * ```\n *\n * @param payload - The request payload to submit for the current order.\n * @param options - Options for submitting the current order.\n * @returns A promise that resolves to the current state.\n */\n submitOrder(payload: OrderRequestBody, options?: RequestOptions): Promise {\n const action = this._paymentStrategyActionCreator.execute(payload, options);\n\n return this._dispatch(action, { queueId: 'paymentStrategy' });\n }\n\n /**\n * Finalizes the submission process for an order.\n *\n * This method is only required for certain hosted payment methods that\n * require a customer to enter their credit card details on their website.\n * You need to call this method once the customer has redirected back to\n * checkout in order to complete the checkout process.\n *\n * If the method is called before order finalization is required or for a\n * payment method that does not require order finalization, an error will be\n * thrown. Conversely, if the method is called successfully, you should\n * immediately redirect the customer to the order confirmation page.\n *\n * ```js\n * try {\n * await service.finalizeOrderIfNeeded();\n *\n * window.location.assign('/order-confirmation');\n * } catch (error) {\n * if (error.type !== 'order_finalization_not_required') {\n * throw error;\n * }\n * }\n * ```\n *\n * @param options - Options for finalizing the current order.\n * @returns A promise that resolves to the current state.\n * @throws `OrderFinalizationNotRequiredError` error if order finalization\n * is not required for the current order at the time of execution.\n */\n finalizeOrderIfNeeded(options?: RequestOptions): Promise {\n const action = this._paymentStrategyActionCreator.finalize(options);\n\n return this._dispatch(action, { queueId: 'paymentStrategy' });\n }\n\n /**\n * Loads a list of payment methods available for checkout.\n *\n * If a customer enters their payment details before navigating to the\n * checkout page (i.e.: using PayPal checkout button on the cart page), only\n * one payment method will be available for the customer - the selected\n * payment method. Otherwise, by default, all payment methods configured by\n * the merchant will be available for the customer.\n *\n * Once the method is executed successfully, you can call\n * `CheckoutStoreSelector#getPaymentMethods` to retrieve the list of payment\n * methods.\n *\n * ```js\n * const state = service.loadPaymentMethods();\n *\n * console.log(state.data.getPaymentMethods());\n * ```\n *\n * @param options - Options for loading the payment methods that are\n * available to the current customer.\n * @returns A promise that resolves to the current state.\n */\n loadPaymentMethods(options?: RequestOptions): Promise {\n const action = this._paymentMethodActionCreator.loadPaymentMethods(options);\n\n return this._dispatch(action, { queueId: 'paymentMethods' });\n }\n\n /**\n * Loads a payment method by an id.\n *\n * This method does not work with multi-option payment providers. Due to its\n * limitation, it is deprecated and will be removed in the future.\n *\n * @deprecated\n * @internal\n * @param methodId - The identifier for the payment method to load.\n * @param options - Options for loading the payment method.\n * @returns A promise that resolves to the current state.\n */\n loadPaymentMethod(methodId: string, options?: RequestOptions): Promise {\n const action = this._paymentMethodActionCreator.loadPaymentMethod(methodId, options);\n\n return this._dispatch(action, { queueId: 'paymentMethods' });\n }\n\n /**\n * Initializes the payment step of a checkout process.\n *\n * Before a payment method can accept payment details, it must first be\n * initialized. Some payment methods require you to provide additional\n * initialization options. For example, you can provide an element ID for\n * Amazon Pay if you want users to be able to select a different payment\n * method by clicking on the element.\n *\n * ```js\n * await service.initializePayment({\n * methodId: 'amazonpay',\n * amazonpay: {\n * editButtonId: 'edit-button',\n * },\n * });\n * ```\n *\n * @param options - Options for initializing the payment step of checkout.\n * @returns A promise that resolves to the current state.\n */\n initializePayment(options: PaymentInitializeOptions): Promise {\n const action = this._paymentStrategyActionCreator.initialize(options);\n\n return this._dispatch(action, { queueId: 'paymentStrategy' });\n }\n\n /**\n * De-initializes the payment step of a checkout process.\n *\n * The method should be called once you no longer require a payment method\n * to be initialized. It can perform any necessary clean-up behind the\n * scene, i.e.: remove DOM nodes or event handlers that are attached as a\n * result of payment initialization.\n *\n * ```js\n * await service.deinitializePayment({\n * methodId: 'amazonpay',\n * });\n * ```\n *\n * @param options - Options for deinitializing the payment step of checkout.\n * @returns A promise that resolves to the current state.\n */\n deinitializePayment(options: PaymentRequestOptions): Promise {\n const action = this._paymentStrategyActionCreator.deinitialize(options);\n\n return this._dispatch(action, { queueId: 'paymentStrategy' });\n }\n\n /**\n * Loads a list of countries available for billing.\n *\n * Once you make a successful request, you will be able to retrieve the list\n * of countries by calling `CheckoutStoreSelector#getBillingCountries`.\n *\n * ```js\n * const state = await service.loadBillingCountries();\n *\n * console.log(state.data.getBillingCountries());\n * ```\n *\n * @param options - Options for loading the available billing countries.\n * @returns A promise that resolves to the current state.\n */\n loadBillingCountries(options?: RequestOptions): Promise {\n const action = this._countryActionCreator.loadCountries(options);\n\n return this._dispatch(action, { queueId: 'billingCountries' });\n }\n\n /**\n * Loads a list of countries available for shipping.\n *\n * The list is determined based on the shipping zones configured by a\n * merchant. Once you make a successful call, you will be able to retrieve\n * the list of available shipping countries by calling\n * `CheckoutStoreSelector#getShippingCountries`.\n *\n * ```js\n * const state = await service.loadShippingCountries();\n *\n * console.log(state.data.getShippingCountries());\n * ```\n *\n * @param options - Options for loading the available shipping countries.\n * @returns A promise that resolves to the current state.\n */\n loadShippingCountries(options?: RequestOptions): Promise {\n const action = this._shippingCountryActionCreator.loadCountries(options);\n\n return this._dispatch(action, { queueId: 'shippingCountries' });\n }\n\n /**\n * Loads a list of pickup options for a given criteria.\n *\n * ```js\n * const consignmentId = '1';\n * const searchArea = {\n * radius: {\n * value: 1.4,\n * unit: 'KM'\n * },\n * coordinates: {\n * latitude: 1.4,\n * longitude: 0\n * },\n * };\n * const state = await service.loadPickupOptions({ consignmentId, searchArea });\n *\n * console.log(state.data.getPickupOptions(consignmentId, searchArea));\n * ```\n *\n * @alpha\n * @param options - Options for loading the available shipping countries.\n * @returns A promise that resolves to the current state.\n */\n loadPickupOptions(query: PickupOptionRequestBody): Promise {\n const action = this._pickupOptionActionCreator.loadPickupOptions(query);\n\n return this._dispatch(action, { queueId: 'pickupOptions' });\n }\n\n /**\n * Loads a set of form fields that should be presented to customers in order\n * to capture their billing address.\n *\n * Once the method has been executed successfully, you can call\n * `CheckoutStoreSelector#getBillingAddressFields` to retrieve the set of\n * form fields.\n *\n * ```js\n * const state = service.loadBillingAddressFields();\n *\n * console.log(state.data.getBillingAddressFields('US'));\n * ```\n *\n * @param options - Options for loading the billing address form fields.\n * @returns A promise that resolves to the current state.\n */\n loadBillingAddressFields(options?: RequestOptions): Promise {\n return this.loadBillingCountries(options);\n }\n\n /**\n * Loads a set of form fields that should be presented to customers in order\n * to capture their shipping address.\n *\n * Once the method has been executed successfully, you can call\n * `CheckoutStoreSelector#getShippingAddressFields` to retrieve the set of\n * form fields.\n *\n * ```js\n * const state = service.loadShippingAddressFields();\n *\n * console.log(state.data.getShippingAddressFields('US'));\n * ```\n *\n * @param options - Options for loading the shipping address form fields.\n * @returns A promise that resolves to the current state.\n */\n loadShippingAddressFields(options?: RequestOptions): Promise {\n return this.loadShippingCountries(options);\n }\n\n /**\n * Initializes the sign-in step of a checkout process.\n *\n * Some payment methods, such as Amazon Pay, have their own sign-in flow. In\n * order to support them, this method must be called.\n *\n * ```js\n * await service.initializeCustomer({\n * methodId: 'amazonpay',\n * amazonpay: {\n * container: 'signInButton',\n * },\n * });\n * ```\n *\n * @param options - Options for initializing the customer step of checkout.\n * @returns A promise that resolves to the current state.\n */\n initializeCustomer(options?: CustomerInitializeOptions): Promise {\n const action = this._customerStrategyActionCreator.initialize(options);\n\n return this._dispatch(action, { queueId: 'customerStrategy' });\n }\n\n /**\n * De-initializes the sign-in step of a checkout process.\n *\n * It should be called once you no longer want to prompt customers to sign\n * in. It can perform any necessary clean-up behind the scene, i.e.: remove\n * DOM nodes or event handlers that are attached as a result of customer\n * initialization.\n *\n * ```js\n * await service.deinitializeCustomer({\n * methodId: 'amazonpay',\n * });\n * ```\n *\n * @param options - Options for deinitializing the customer step of checkout.\n * @returns A promise that resolves to the current state.\n */\n deinitializeCustomer(options?: CustomerRequestOptions): Promise {\n const action = this._customerStrategyActionCreator.deinitialize(options);\n\n return this._dispatch(action, { queueId: 'customerStrategy' });\n }\n\n /**\n * Sends a email that contains a single-use sign-in link. When a valid links is clicked,\n * signs in the customer without requiring any password, redirecting them to the account page if no redirectUrl is provided.\n *\n *\n * ```js\n * checkoutService.sendSignInEmail({ email: 'foo@bar.com', redirectUrl: 'checkout' });\n * ```\n *\n * @param signInEmailRequest - The sign-in email request values.\n * @param options - Options for the send email request.\n * @returns A promise that resolves to the current state.\n */\n sendSignInEmail(\n signInEmailRequest: SignInEmailRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._signInEmailActionCreator.sendSignInEmail(signInEmailRequest, options);\n\n return this._dispatch(action, { queueId: 'signInEmail' });\n }\n\n /**\n * Creates a customer account.\n *\n * @remarks\n * ```js\n * checkoutService.createCustomerAccount({\n * email: 'foo@bar.com',\n * firstName: 'Foo',\n * lastName: 'Bar',\n * password: 'password',\n * acceptsMarketingEmails: true,\n * customFields: [],\n * });\n * ```\n * Please note that `createCustomerAccount` is currently in an early stage\n * of development. Therefore the API is unstable and not ready for public\n * consumption.\n *\n * @alpha\n * @param customerAccount - The customer account data.\n * @param options - Options for creating customer account.\n * @returns A promise that resolves to the current state.\n */\n createCustomerAccount(\n customerAccount: CustomerAccountRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._customerActionCreator.createCustomer(customerAccount, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Creates a customer account address.\n *\n * @remarks\n * ```js\n * checkoutService.createCustomerAddress({\n * firstName: 'Foo',\n * lastName: 'Bar',\n * address1: '55 Market St',\n * stateOrProvinceCode: 'CA',\n * countryCode: 'US',\n * postalCode: '90110',\n * customFields: [],\n * });\n * ```\n * Please note that `createCustomerAccountAddress` is currently in an early stage\n * of development. Therefore the API is unstable and not ready for public\n * consumption.\n *\n * @alpha\n * @param customerAddress - The customer account data.\n * @param options - Options for creating customer account.\n * @returns A promise that resolves to the current state.\n */\n createCustomerAddress(\n customerAddress: CustomerAddressRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._customerActionCreator.createAddress(customerAddress, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Updates the subscriptions associated to an email.\n *\n * @param subscriptions - The email and associated subscriptions to update.\n * @param options - Options for continuing as a guest.\n * @returns A promise that resolves to the current state.\n */\n updateSubscriptions(\n subscriptions: Subscriptions,\n options?: RequestOptions,\n ): Promise {\n const action = this._subscriptionsActionCreator.updateSubscriptions(subscriptions, options);\n\n return this._dispatch(action, { queueId: 'subscriptions' });\n }\n\n /**\n * Continues to check out as a guest.\n *\n * If your Checkout Settings allow it, your customers could continue the checkout as guests (without signing in).\n * If you have enabled the checkout setting \"Prompt existing accounts to sign in\", this information is\n * exposed as part of the [Customer](../interfaces/customer.md) object.\n *\n * Once they provide their email address, it will be stored as\n * part of their [billing address](../interfaces/billingaddress.md).\n *\n * @param credentials - The guest credentials to use, with optional subscriptions.\n * @param options - Options for continuing as a guest.\n * @returns A promise that resolves to the current state.\n */\n continueAsGuest(\n credentials: GuestCredentials,\n options?: RequestOptions,\n ): Promise {\n const action = this._billingAddressActionCreator.continueAsGuest(credentials, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Signs into a customer's registered account.\n *\n * Once the customer is signed in successfully, the checkout state will be\n * populated with information associated with the customer, such as their\n * saved addresses. You can call `CheckoutStoreSelector#getCustomer` to\n * retrieve the data.\n *\n * ```js\n * const state = await service.signInCustomer({\n * email: 'foo@bar.com',\n * password: 'password123',\n * });\n *\n * console.log(state.data.getCustomer());\n * ```\n *\n * @param credentials - The credentials to be used for signing in the customer.\n * @param options - Options for signing in the customer.\n * @returns A promise that resolves to the current state.\n */\n signInCustomer(\n credentials: CustomerCredentials,\n options?: CustomerRequestOptions,\n ): Promise {\n const action = this._customerStrategyActionCreator.signIn(credentials, options);\n\n return this._dispatch(action, { queueId: 'customerStrategy' });\n }\n\n /**\n * Signs out the current customer if they are previously signed in.\n *\n * Once the customer is successfully signed out, the checkout state will be\n * reset automatically.\n *\n * ```js\n * const state = await service.signOutCustomer();\n *\n * // The returned object should not contain information about the previously signed-in customer.\n * console.log(state.data.getCustomer());\n * ```\n *\n * When a store has \"Allow customers to access their cart across multiple devices\" enabled, signing out\n * will remove the cart/checkout data from the current session. An error with type=\"checkout_not_available\" will be thrown.\n *\n * ```js\n * try {\n * await service.signOutCustomer();\n * } catch (error) {\n * if (error.type === 'checkout_not_available') {\n * window.top.location.assign('/');\n * }\n * }\n * ```\n *\n * @param options - Options for signing out the customer.\n * @returns A promise that resolves to the current state.\n */\n signOutCustomer(options?: CustomerRequestOptions): Promise {\n const action = this._customerStrategyActionCreator.signOut(options);\n\n return this._dispatch(action, { queueId: 'customerStrategy' });\n }\n\n /**\n * Executes custom checkout of the priority payment method.\n *\n * Some payment methods, such as Bolt, can use their own checkout\n * with autofilled customers data, to make checkout passing process\n * easier and faster for customers with Bolt account.\n *\n * ```js\n * await service.executePaymentMethodCheckout({\n * methodId: 'bolt',\n * fallback: () => {},\n * });\n * ```\n *\n * @param options - Options for executing payment method checkout.\n * @returns A promise that resolves to the current state.\n */\n executePaymentMethodCheckout(\n options?: ExecutePaymentMethodCheckoutOptions,\n ): Promise {\n const action = this._customerStrategyActionCreator.executePaymentMethodCheckout(options);\n\n return this._dispatch(action, { queueId: 'customerStrategy' });\n }\n\n /**\n * Loads a list of shipping options available for checkout.\n *\n * Available shipping options can only be determined once a customer\n * provides their shipping address. If the method is executed successfully,\n * `CheckoutStoreSelector#getShippingOptions` can be called to retrieve the\n * list of shipping options.\n *\n * ```js\n * const state = await service.loadShippingOptions();\n *\n * console.log(state.data.getShippingOptions());\n * ```\n *\n * @param options - Options for loading the available shipping options.\n * @returns A promise that resolves to the current state.\n */\n loadShippingOptions(options?: RequestOptions): Promise {\n const action = this._consignmentActionCreator.loadShippingOptions(options);\n\n return this._dispatch(action);\n }\n\n /**\n * Initializes the shipping step of a checkout process.\n *\n * Some payment methods, such as Amazon Pay, can provide shipping\n * information to be used for checkout. In order to support them, this\n * method must be called.\n *\n * ```js\n * await service.initializeShipping({\n * methodId: 'amazonpay',\n * amazonpay: {\n * editAddressButtonId: 'changeAddressButton',\n * },\n * });\n * ```\n *\n * @param options - Options for initializing the shipping step of checkout.\n * @returns A promise that resolves to the current state.\n */\n initializeShipping(options?: ShippingInitializeOptions): Promise {\n const action = this._shippingStrategyActionCreator.initialize(options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * De-initializes the shipping step of a checkout process.\n *\n * It should be called once you no longer need to collect shipping details.\n * It can perform any necessary clean-up behind the scene, i.e.: remove DOM\n * nodes or event handlers that are attached as a result of shipping\n * initialization.\n *\n * ```js\n * await service.deinitializeShipping({\n * methodId: 'amazonpay',\n * });\n * ```\n *\n * @param options - Options for deinitializing the shipping step of checkout.\n * @returns A promise that resolves to the current state.\n */\n deinitializeShipping(options?: ShippingRequestOptions): Promise {\n const action = this._shippingStrategyActionCreator.deinitialize(options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Selects a shipping option for the current address.\n *\n * If a shipping option has an additional cost, the quote for the current\n * order will be adjusted once the option is selected.\n *\n * ```js\n * const state = await service.selectShippingOption('address-id', 'shipping-option-id');\n *\n * console.log(state.data.getSelectedShippingOption());\n * ```\n *\n * @param shippingOptionId - The identifier of the shipping option to\n * select.\n * @param options - Options for selecting the shipping option.\n * @returns A promise that resolves to the current state.\n */\n selectShippingOption(\n shippingOptionId: string,\n options?: ShippingRequestOptions,\n ): Promise {\n const action = this._shippingStrategyActionCreator.selectOption(shippingOptionId, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Updates the shipping address for the current checkout.\n *\n * When a customer updates their shipping address for an order, they will\n * see an updated list of shipping options and the cost for each option,\n * unless no options are available. If the update is successful, you can\n * call `CheckoutStoreSelector#getShippingAddress` to retrieve the address.\n *\n * If the shipping address changes and the selected shipping option becomes\n * unavailable for the updated address, the shipping option will be\n * deselected.\n *\n * You can submit an address that is partially complete. The address does\n * not get validated until you submit the order.\n *\n * ```js\n * const state = await service.updateShippingAddress(address);\n *\n * console.log(state.data.getShippingAddress());\n * ```\n *\n * @param address - The address to be used for shipping.\n * @param options - Options for updating the shipping address.\n * @returns A promise that resolves to the current state.\n */\n updateShippingAddress(\n address: Partial,\n options?: ShippingRequestOptions,\n ): Promise {\n const action = this._shippingStrategyActionCreator.updateAddress(address, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Creates consignments given a list.\n *\n * Note: this is used when items need to be shipped to multiple addresses,\n * for single shipping address, use `CheckoutService#updateShippingAddress`.\n *\n * When consignments are created, an updated list of shipping options will\n * become available for each consignment, unless no options are available.\n * If the update is successful, you can call\n * `CheckoutStoreSelector#getConsignments` to retrieve the updated list of\n * consignments.'\n *\n * Beware that if a consignment includes all line items from another\n * consignment, that consignment will be deleted as a valid consignment must\n * include at least one valid line item.\n *\n * You can submit an address that is partially complete. The address does\n * not get validated until you submit the order.\n *\n * ```js\n * const state = await service.createConsignments(consignments);\n *\n * console.log(state.data.getConsignments());\n * ```\n *\n * @param consignments - The list of consignments to be created.\n * @param options - Options for updating the shipping address.\n * @returns A promise that resolves to the current state.\n */\n createConsignments(\n consignments: ConsignmentsRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._consignmentActionCreator.createConsignments(consignments, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Deletes a consignment\n *\n * ```js\n * const state = await service.deleteConsignment('55c96cda6f04c');\n *\n * console.log(state.data.getConsignments());\n * ```\n *\n * @param consignmentId - The ID of the consignment to be deleted\n * @param options - Options for the consignment delete request\n * @returns A promise that resolves to the current state.\n */\n deleteConsignment(consignmentId: string, options?: RequestOptions): Promise {\n const action = this._consignmentActionCreator.deleteConsignment(consignmentId, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Updates a specific consignment.\n *\n * Note: this is used when items need to be shipped to multiple addresses,\n * for single shipping address, use `CheckoutService#selectShippingOption`.\n *\n * When a shipping address for a consignment is updated, an updated list of\n * shipping options will become available for the consignment, unless no\n * options are available. If the update is successful, you can call\n * `CheckoutStoreSelector#getConsignments` to retrieve updated list of\n * consignments.\n *\n * Beware that if the updated consignment includes all line items from another\n * consignment, that consignment will be deleted as a valid consignment must\n * include at least one valid line item.\n *\n * If the shipping address changes and the selected shipping option becomes\n * unavailable for the updated address, the shipping option will be\n * deselected.\n *\n * You can submit an address that is partially complete. The address does\n * not get validated until you submit the order.\n *\n * ```js\n * const state = await service.updateConsignment(consignment);\n *\n * console.log(state.data.getConsignments());\n * ```\n *\n * @param consignment - The consignment data that will be used.\n * @param options - Options for updating the shipping address.\n * @returns A promise that resolves to the current state.\n */\n updateConsignment(\n consignment: ConsignmentUpdateRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._consignmentActionCreator.updateConsignment(consignment, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Convenience method that assigns items to be shipped to a specific address.\n *\n * Note: this method finds an existing consignment that matches the provided address\n * and assigns the provided items. If no consignment matches the address, a new one\n * will be created.\n *\n * @param consignment - The consignment data that will be used.\n * @param options - Options for the request\n * @returns A promise that resolves to the current state.\n */\n assignItemsToAddress(\n consignment: ConsignmentAssignmentRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._consignmentActionCreator.assignItemsByAddress(consignment, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Convenience method that unassigns items from a specific shipping address.\n *\n * Note: this method finds an existing consignment that matches the provided address\n * and unassigns the specified items. If the consignment ends up with no line items\n * after the unassignment, it will be deleted.\n *\n * @param consignment - The consignment data that will be used.\n * @param options - Options for the request\n * @returns A promise that resolves to the current state.\n */\n unassignItemsToAddress(\n consignment: ConsignmentAssignmentRequestBody,\n options?: RequestOptions,\n ): Promise {\n const action = this._consignmentActionCreator.unassignItemsByAddress(consignment, options);\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Selects a shipping option for a given consignment.\n *\n * Note: this is used when items need to be shipped to multiple addresses,\n * for single shipping address, use `CheckoutService#updateShippingAddress`.\n *\n * If a shipping option has an additional cost, the quote for the current\n * order will be adjusted once the option is selected.\n *\n * ```js\n * const state = await service.selectConsignmentShippingOption(consignmentId, optionId);\n *\n * console.log(state.data.getConsignments());\n * ```\n *\n * @param consignmentId - The identified of the consignment to be updated.\n * @param shippingOptionId - The identifier of the shipping option to\n * select.\n * @param options - Options for selecting the shipping option.\n * @returns A promise that resolves to the current state.\n */\n selectConsignmentShippingOption(\n consignmentId: string,\n shippingOptionId: string,\n options?: ShippingRequestOptions,\n ): Promise {\n const action = this._consignmentActionCreator.updateShippingOption(\n {\n id: consignmentId,\n shippingOptionId,\n },\n options,\n );\n\n return this._dispatch(action, { queueId: 'shippingStrategy' });\n }\n\n /**\n * Updates the billing address for the current checkout.\n *\n * A customer must provide their billing address before they can proceed to\n * pay for their order.\n *\n * You can submit an address that is partially complete. The address does\n * not get validated until you submit the order.\n *\n * ```js\n * const state = await service.updateBillingAddress(address);\n *\n * console.log(state.data.getBillingAddress());\n * ```\n *\n * @param address - The address to be used for billing.\n * @param options - Options for updating the billing address.\n * @returns A promise that resolves to the current state.\n */\n updateBillingAddress(\n address: Partial,\n options: RequestOptions = {},\n ): Promise {\n const action = this._billingAddressActionCreator.updateAddress(address, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Applies or removes customer's store credit code to the current checkout.\n *\n * Once the store credit gets applied, the outstanding balance will be adjusted accordingly.\n *\n * ```js\n * const state = await service.applyStoreCredit(true);\n *\n * console.log(state.data.getCheckout().outstandingBalance);\n * ```\n *\n * @param options - Options for applying store credit.\n * @returns A promise that resolves to the current state.\n */\n applyStoreCredit(\n useStoreCredit: boolean,\n options?: RequestOptions,\n ): Promise {\n const action = this._storeCreditActionCreator.applyStoreCredit(useStoreCredit, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Applies a coupon code to the current checkout.\n *\n * Once the coupon code gets applied, the quote for the current checkout will\n * be adjusted accordingly. The same coupon code cannot be applied more than\n * once.\n *\n * ```js\n * await service.applyCoupon('COUPON');\n * ```\n *\n * @param code - The coupon code to apply to the current checkout.\n * @param options - Options for applying the coupon code.\n * @returns A promise that resolves to the current state.\n */\n applyCoupon(code: string, options?: RequestOptions): Promise {\n const action = this._couponActionCreator.applyCoupon(code, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Removes a coupon code from the current checkout.\n *\n * Once the coupon code gets removed, the quote for the current checkout will\n * be adjusted accordingly.\n *\n * ```js\n * await service.removeCoupon('COUPON');\n * ```\n *\n * @param code - The coupon code to remove from the current checkout.\n * @param options - Options for removing the coupon code.\n * @returns A promise that resolves to the current state.\n */\n removeCoupon(code: string, options?: RequestOptions): Promise {\n const action = this._couponActionCreator.removeCoupon(code, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Applies a gift certificate to the current checkout.\n *\n * Once the gift certificate gets applied, the quote for the current\n * checkout will be adjusted accordingly.\n *\n * ```js\n * await service.applyGiftCertificate('GIFT_CERTIFICATE');\n * ```\n *\n * @param code - The gift certificate to apply to the current checkout.\n * @param options - Options for applying the gift certificate.\n * @returns A promise that resolves to the current state.\n */\n applyGiftCertificate(code: string, options?: RequestOptions): Promise {\n const action = this._giftCertificateActionCreator.applyGiftCertificate(code, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Removes a gift certificate from an order.\n *\n * Once the gift certificate gets removed, the quote for the current\n * checkout will be adjusted accordingly.\n *\n * ```js\n * await service.removeGiftCertificate('GIFT_CERTIFICATE');\n * ```\n *\n * @param code - The gift certificate to remove from the current checkout.\n * @param options - Options for removing the gift certificate.\n * @returns A promise that resolves to the current state.\n */\n removeGiftCertificate(code: string, options?: RequestOptions): Promise {\n const action = this._giftCertificateActionCreator.removeGiftCertificate(code, options);\n\n return this._dispatch(action);\n }\n\n /**\n * Loads a list of payment instruments associated with a customer.\n *\n * Once the method has been called successfully, you can retrieve the list\n * of payment instruments by calling `CheckoutStoreSelector#getInstruments`.\n * If the customer does not have any payment instruments on record, i.e.:\n * credit card, you will get an empty list instead.\n *\n * ```js\n * const state = service.loadInstruments();\n *\n * console.log(state.data.getInstruments());\n * ```\n *\n * @returns A promise that resolves to the current state.\n */\n loadInstruments(): Promise {\n const action = this._instrumentActionCreator.loadInstruments();\n\n return this._dispatch(action);\n }\n\n /**\n * Deletes a payment instrument by an id.\n *\n * Once an instrument gets removed, it can no longer be retrieved using\n * `CheckoutStoreSelector#getInstruments`.\n *\n * ```js\n * const state = service.deleteInstrument('123');\n *\n * console.log(state.data.getInstruments());\n * ```\n *\n * @param instrumentId - The identifier of the payment instrument to delete.\n * @returns A promise that resolves to the current state.\n */\n deleteInstrument(instrumentId: string): Promise {\n const action = this._instrumentActionCreator.deleteInstrument(instrumentId);\n\n return this._dispatch(action).then(() => this.loadInstruments());\n }\n\n /**\n * Clear errors that have been collected from previous calls.\n *\n * ```js\n * const state = await service.clearError(error);\n *\n * console.log(state.errors.getError());\n * ```\n *\n * @param error - Specific error object to clear\n * @returns A promise that resolves to the current state.\n */\n clearError(error: Error): Promise {\n const action = this._errorActionCreator.clearError(error);\n\n return this._dispatch(action);\n }\n\n /**\n * Initializes the spam protection for order creation.\n *\n * Note: Use `CheckoutService#executeSpamCheck` instead.\n * You do not need to call this method before calling\n * `CheckoutService#executeSpamCheck`.\n *\n * With spam protection enabled, the customer has to be verified as\n * a human. The order creation will fail if spam protection\n * is enabled but verification fails.\n *\n * ```js\n * await service.initializeSpamProtection();\n * ```\n *\n * @param options - Options for initializing spam protection.\n * @returns A promise that resolves to the current state.\n * @deprecated - Use CheckoutService#executeSpamCheck instead.\n */\n initializeSpamProtection(options: SpamProtectionOptions): Promise {\n const action = this._spamProtectionActionCreator.initialize(options);\n\n return this._dispatch(action, { queueId: 'spamProtection' });\n }\n\n /**\n * Verifies whether the current checkout is created by a human.\n *\n * Note: this method will do the initialization, therefore you do not\n * need to call `CheckoutService#initializeSpamProtection`\n * before calling this method.\n *\n * With spam protection enabled, the customer has to be verified as\n * a human. The order creation will fail if spam protection\n * is enabled but verification fails. You should call this method before\n * `submitOrder` method is called (i.e.: when the shopper\n * first gets to the payment step).\n *\n * **Note**: You need to enable Google ReCAPTCHA bot protection in your Checkout Settings.\n *\n * ```js\n * await service.executeSpamCheck();\n * ```\n *\n * @returns A promise that resolves to the current state.\n */\n executeSpamCheck(): Promise {\n const action = this._spamProtectionActionCreator.verifyCheckoutSpamProtection();\n\n return this._dispatch(action, { queueId: 'spamProtection' });\n }\n\n /**\n * Loads a list of extensions available for checkout.\n *\n * ```js\n * const state = await service.loadExtensions();\n *\n * console.log(state.data.getExtensions());\n * ```\n *\n * @alpha\n * @param options - Options for loading the extensions that are\n * available to the current customer.\n * @returns A promise that resolves to the current state.\n */\n loadExtensions(options?: RequestOptions): Promise {\n const action = this._extensionActionCreator.loadExtensions(options);\n\n return this._dispatch(action, { queueId: 'extensions' });\n }\n\n /**\n * Renders an extension for a checkout extension region.\n * Currently, only one extension is allowed per region.\n *\n * @alpha\n * @param container The ID of a container which the extension should be inserted.\n * @param region The name of an area where the extension should be presented.\n * @returns A promise that resolves to the current state.\n */\n renderExtension(container: string, region: ExtensionRegion): Promise {\n const action = this._extensionActionCreator.renderExtension(container, region);\n\n return this._dispatch(action, { queueId: 'extensions' });\n }\n\n /**\n * Dispatches an action through the data store and returns the current state\n * once the action is dispatched.\n *\n * @param action - The action to dispatch.\n * @returns A promise that resolves to the current state.\n */\n private _dispatch(\n action: Action | Observable | ThunkAction,\n options?: { queueId?: string },\n ): Promise {\n return this._store\n .dispatch(action, options)\n .then(() => this.getState())\n .catch((error) => {\n throw this._errorTransformer.transform(error);\n });\n }\n}\n","import { ErrorMessageTransformer } from '../common/error';\nimport {\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../common/error/errors';\nimport { getEnvironment } from '../common/utility';\n\nexport type CheckoutServiceErrorType = MissingDataError | NotInitializedError;\nexport type CheckoutServiceErrorTransformer = ErrorMessageTransformer<\n CheckoutServiceErrorType | Error\n>;\n\nexport default function createCheckoutServiceErrorTransformer(\n isDevelopment: boolean = getEnvironment() === 'development',\n): CheckoutServiceErrorTransformer {\n return new ErrorMessageTransformer((error) => {\n if (!isDevelopment || !isCheckoutServiceError(error)) {\n return error.message;\n }\n\n switch (error.subtype || error.type) {\n case MissingDataErrorType.MissingConsignments:\n return `\n ${error.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 `;\n\n case MissingDataErrorType.MissingCart:\n case MissingDataErrorType.MissingCheckout:\n return `\n ${error.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 `;\n\n case MissingDataErrorType.MissingCheckoutConfig:\n return `\n ${error.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 `;\n\n case MissingDataErrorType.MissingOrder:\n return `\n ${error.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 `;\n\n case MissingDataErrorType.MissingOrderId:\n return `\n ${error.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 `;\n\n case MissingDataErrorType.MissingPaymentMethod:\n return `\n ${error.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 `;\n\n case NotInitializedErrorType.CustomerNotInitialized:\n 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 `;\n\n case NotInitializedErrorType.PaymentNotInitialized:\n return `\n ${error.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 `;\n\n case NotInitializedErrorType.ShippingNotInitialized:\n return `\n ${error.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 `;\n\n default:\n return error.message;\n }\n });\n}\n\nfunction isCheckoutServiceError(error: any): error is CheckoutServiceErrorType {\n return !!(error.subtype || error.type);\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { omit, values } from 'lodash';\n\nimport { Address } from '../address';\nimport { BillingAddress } from '../billing';\nimport { Cart } from '../cart';\nimport { createSelector } from '../common/selector';\nimport { cloneResult as clone } from '../common/utility';\nimport { FlashMessage, FlashMessageType, StoreConfig, UserExperienceSettings } from '../config';\nimport { Coupon, GiftCertificate } from '../coupon';\nimport { Customer } from '../customer';\nimport { Extension } from '../extension';\nimport { FormField } from '../form';\nimport { Country } from '../geography';\nimport { Order } from '../order';\nimport { PaymentMethod } from '../payment';\nimport { CardInstrument, PaymentInstrument } from '../payment/instrument';\nimport { Consignment, PickupOptionResult, SearchArea, ShippingOption } from '../shipping';\nimport { SignInEmail } from '../signin-email';\n\nimport Checkout from './checkout';\nimport InternalCheckoutSelectors from './internal-checkout-selectors';\n\nexport type Instrument = CardInstrument;\n\n/**\n * Responsible for getting the state of the current checkout.\n *\n * This object has a set of methods that allow you to get a specific piece of\n * checkout information, such as shipping and billing details.\n */\nexport default interface CheckoutStoreSelector {\n /**\n * Gets the current checkout.\n *\n * @returns The current checkout if it is loaded, otherwise undefined.\n */\n getCheckout(): Checkout | undefined;\n\n /**\n * Gets the current order.\n *\n * @returns The current order if it is loaded, otherwise undefined.\n */\n getOrder(): Order | undefined;\n\n /**\n * Gets the checkout configuration of a store.\n *\n * @returns The configuration object if it is loaded, otherwise undefined.\n */\n getConfig(): StoreConfig | undefined;\n\n /**\n * Gets the sign-in email.\n *\n * @returns The sign-in email object if sent, otherwise undefined\n */\n getSignInEmail(): SignInEmail | undefined;\n\n /**\n * Gets the shipping address of the current checkout.\n *\n * If the address is partially complete, it may not have shipping options\n * associated with it.\n *\n * @returns The shipping address object if it is loaded, otherwise\n * undefined.\n */\n getShippingAddress(): Address | undefined;\n\n /**\n * Gets a list of shipping options available for the shipping address.\n *\n * If there is no shipping address assigned to the current checkout, the\n * list of shipping options will be empty.\n *\n * @returns The list of shipping options if any, otherwise undefined.\n */\n getShippingOptions(): ShippingOption[] | undefined;\n\n /**\n * Gets a list of consignments.\n *\n * If there are no consignments created for to the current checkout, the\n * list will be empty.\n *\n * @returns The list of consignments if any, otherwise undefined.\n */\n getConsignments(): Consignment[] | undefined;\n\n /**\n * Gets the selected shipping option for the current checkout.\n *\n * @returns The shipping option object if there is a selected option,\n * otherwise undefined.\n */\n getSelectedShippingOption(): ShippingOption | undefined;\n\n /**\n * Gets a list of countries available for shipping.\n *\n * @returns The list of countries if it is loaded, otherwise undefined.\n */\n getShippingCountries(): Country[] | undefined;\n\n /**\n * Gets the billing address of an order.\n *\n * @returns The billing address object if it is loaded, otherwise undefined.\n */\n getBillingAddress(): BillingAddress | undefined;\n\n /**\n * Gets a list of countries available for billing.\n *\n * @returns The list of countries if it is loaded, otherwise undefined.\n */\n getBillingCountries(): Country[] | undefined;\n\n /**\n * Gets a list of payment methods available for checkout.\n *\n * @returns The list of payment methods if it is loaded, otherwise undefined.\n */\n getPaymentMethods(): PaymentMethod[] | undefined;\n\n /**\n * Gets a payment method by an id.\n *\n * The method returns undefined if unable to find a payment method with the\n * specified id, either because it is not available for the customer, or it\n * is not loaded.\n *\n * @param methodId - The identifier of the payment method.\n * @param gatewayId - The identifier of a payment provider providing the\n * payment method.\n * @returns The payment method object if loaded and available, otherwise,\n * undefined.\n */\n getPaymentMethod(methodId: string, gatewayId?: string): PaymentMethod | undefined;\n\n /**\n * Gets the payment method that is selected for checkout.\n *\n * @returns The payment method object if there is a selected method;\n * undefined if otherwise.\n */\n getSelectedPaymentMethod(): PaymentMethod | undefined;\n\n /**\n * Gets the available flash messages.\n *\n * Flash messages contain messages set by the server,\n * e.g: when trying to sign in using an invalid email link.\n *\n * @param type - The type of flash messages to be returned. Optional\n * @returns The flash messages if available, otherwise undefined.\n */\n getFlashMessages(type?: FlashMessageType): FlashMessage[] | undefined;\n\n /**\n * Gets the current cart.\n *\n * @returns The current cart object if it is loaded, otherwise undefined.\n */\n getCart(): Cart | undefined;\n\n /**\n * Gets a list of coupons that are applied to the current checkout.\n *\n * @returns The list of applied coupons if there is any, otherwise undefined.\n */\n getCoupons(): Coupon[] | undefined;\n\n /**\n * Gets a list of gift certificates that are applied to the current checkout.\n *\n * @returns The list of applied gift certificates if there is any, otherwise undefined.\n */\n getGiftCertificates(): GiftCertificate[] | undefined;\n\n /**\n * Gets the current customer.\n *\n * @returns The current customer object if it is loaded, otherwise\n * undefined.\n */\n getCustomer(): Customer | undefined;\n\n /**\n * Checks if payment data is required or not.\n *\n * If payment data is required, customers should be prompted to enter their\n * payment details.\n *\n * ```js\n * if (state.checkout.isPaymentDataRequired()) {\n * // Render payment form\n * } else {\n * // Render \"Payment is not required for this order\" message\n * }\n * ```\n *\n * @param useStoreCredit - If true, check whether payment data is required\n * with store credit applied; otherwise, check without store credit.\n * @returns True if payment data is required, otherwise false.\n */\n isPaymentDataRequired(useStoreCredit?: boolean): boolean;\n\n /**\n * Checks if payment data is submitted or not.\n *\n * If payment data is already submitted using a payment method, customers\n * should not be prompted to enter their payment details again.\n *\n * @param methodId - The identifier of the payment method.\n * @param gatewayId - The identifier of a payment provider providing the\n * payment method.\n * @returns True if payment data is submitted, otherwise false.\n */\n isPaymentDataSubmitted(methodId: string, gatewayId?: string): boolean;\n\n /**\n * Gets a list of payment instruments associated with the current customer.\n *\n * @returns The list of payment instruments if it is loaded, otherwise undefined.\n */\n getInstruments(): Instrument[] | undefined;\n getInstruments(paymentMethod: PaymentMethod): PaymentInstrument[] | undefined;\n\n /**\n * Gets a set of form fields that should be presented in order to create a customer.\n *\n * @returns The set of customer account form fields if it is loaded,\n * otherwise undefined.\n */\n getCustomerAccountFields(): FormField[];\n\n /**\n * Gets a set of form fields that should be presented to customers in order\n * to capture their billing address for a specific country.\n *\n * @param countryCode - A 2-letter country code (ISO 3166-1 alpha-2).\n * @returns The set of billing address form fields if it is loaded,\n * otherwise undefined.\n */\n getBillingAddressFields(countryCode: string): FormField[];\n\n /**\n * Gets a set of form fields that should be presented to customers in order\n * to capture their shipping address for a specific country.\n *\n * @param countryCode - A 2-letter country code (ISO 3166-1 alpha-2).\n * @returns The set of shipping address form fields if it is loaded,\n * otherwise undefined.\n */\n getShippingAddressFields(countryCode: string): FormField[];\n\n /**\n * Gets a list of pickup options for specified parameters.\n *\n * @param consignmentId - Id of consignment.\n * @param searchArea - An object containing of radius and co-ordinates.\n * @returns The set of shipping address form fields if it is loaded,\n * otherwise undefined.\n */\n getPickupOptions(\n consignmentId: string,\n searchArea: SearchArea,\n ): PickupOptionResult[] | undefined;\n\n /**\n * Gets user experience settings.\n *\n * @returns The object of user experience settings if it is loaded, otherwise undefined.\n */\n getUserExperienceSettings(): UserExperienceSettings | undefined;\n\n /**\n * Gets a list of extensions available for checkout.\n *\n * @alpha\n * @returns The list of extensions if it is loaded, otherwise undefined.\n */\n getExtensions(): Extension[] | undefined;\n}\n\nexport type CheckoutStoreSelectorFactory = (\n state: InternalCheckoutSelectors,\n) => CheckoutStoreSelector;\n\nexport function createCheckoutStoreSelectorFactory(): CheckoutStoreSelectorFactory {\n const getCheckout = createSelector(\n ({ checkout }: InternalCheckoutSelectors) => checkout.getCheckout,\n (getCheckout) => clone(getCheckout),\n );\n\n const getOrder = createSelector(\n ({ order }: InternalCheckoutSelectors) => order.getOrder,\n (getOrder) => clone(getOrder),\n );\n\n const getConfig = createSelector(\n ({ config }: InternalCheckoutSelectors) => config.getStoreConfig,\n (getStoreConfig) => clone(getStoreConfig),\n );\n\n const getShippingAddress = createSelector(\n ({ shippingAddress }: InternalCheckoutSelectors) => shippingAddress.getShippingAddress,\n ({ config }: InternalCheckoutSelectors) => config.getContextConfig,\n (getShippingAddress, getContextConfig) =>\n clone(() => {\n const shippingAddress = getShippingAddress();\n const context = getContextConfig();\n\n if (!shippingAddress) {\n if (!context || !context.geoCountryCode) {\n return;\n }\n\n return {\n firstName: '',\n lastName: '',\n company: '',\n address1: '',\n address2: '',\n city: '',\n stateOrProvince: '',\n stateOrProvinceCode: '',\n postalCode: '',\n country: '',\n phone: '',\n customFields: [],\n countryCode: context.geoCountryCode,\n };\n }\n\n return shippingAddress;\n }),\n );\n\n const getShippingOptions = createSelector(\n ({ consignments }: InternalCheckoutSelectors) => consignments.getConsignments,\n (getConsignments) =>\n clone(() => {\n const consignments = getConsignments();\n\n const shippingConsignment = consignments?.find(\n (consignment) => !consignment.selectedPickupOption,\n );\n\n return shippingConsignment?.availableShippingOptions;\n }),\n );\n\n const getConsignments = createSelector(\n ({ consignments }: InternalCheckoutSelectors) => consignments.getConsignments,\n (getConsignments) => clone(getConsignments),\n );\n\n const getSelectedShippingOption = createSelector(\n ({ consignments }: InternalCheckoutSelectors) => consignments.getConsignments,\n (getConsignments) =>\n clone(() => {\n const consignments = getConsignments();\n const shippingConsignment = consignments?.find(\n (consignment) => !consignment.selectedPickupOption,\n );\n\n return shippingConsignment?.selectedShippingOption;\n }),\n );\n\n const getShippingCountries = createSelector(\n ({ shippingCountries }: InternalCheckoutSelectors) =>\n shippingCountries.getShippingCountries,\n (getShippingCountries) => clone(getShippingCountries),\n );\n\n const getBillingAddress = createSelector(\n ({ billingAddress }: InternalCheckoutSelectors) => billingAddress.getBillingAddress,\n ({ config }: InternalCheckoutSelectors) => config.getContextConfig,\n (getBillingAddress, getContextConfig) =>\n clone(() => {\n const billingAddress = getBillingAddress();\n const context = getContextConfig();\n const isEmptyBillingAddress =\n !billingAddress ||\n values(omit(billingAddress, 'shouldSaveAddress', 'email', 'id')).every(\n (val) => !val || !val.length,\n );\n\n if (isEmptyBillingAddress) {\n if (!context || !context.geoCountryCode) {\n return billingAddress;\n }\n\n return {\n id: billingAddress ? billingAddress.id : '',\n firstName: '',\n lastName: '',\n company: '',\n address1: '',\n address2: '',\n city: '',\n email: billingAddress ? billingAddress.email : '',\n stateOrProvince: '',\n stateOrProvinceCode: '',\n postalCode: '',\n country: '',\n phone: '',\n customFields: [],\n countryCode: context.geoCountryCode,\n };\n }\n\n return billingAddress;\n }),\n );\n\n const getBillingCountries = createSelector(\n ({ countries }: InternalCheckoutSelectors) => countries.getCountries,\n (getCountries) => clone(getCountries),\n );\n\n const getPaymentMethods = createSelector(\n ({ paymentMethods }: InternalCheckoutSelectors) => paymentMethods.getPaymentMethods,\n (getPaymentMethods) => clone(getPaymentMethods),\n );\n\n const getPaymentMethod = createSelector(\n ({ paymentMethods }: InternalCheckoutSelectors) => paymentMethods.getPaymentMethod,\n (getPaymentMethod) => clone(getPaymentMethod),\n );\n\n const getSelectedPaymentMethod = createSelector(\n ({ payment }: InternalCheckoutSelectors) => payment.getPaymentId,\n ({ paymentMethods }: InternalCheckoutSelectors) => paymentMethods.getPaymentMethod,\n (getPaymentId, getPaymentMethod) =>\n clone(() => {\n const payment = getPaymentId();\n\n return payment && getPaymentMethod(payment.providerId, payment.gatewayId);\n }),\n );\n\n const getCart = createSelector(\n ({ cart }: InternalCheckoutSelectors) => cart.getCart,\n (getCart) => clone(getCart),\n );\n\n const getCoupons = createSelector(\n ({ coupons }: InternalCheckoutSelectors) => coupons.getCoupons,\n (getCoupons) => clone(getCoupons),\n );\n\n const getGiftCertificates = createSelector(\n ({ giftCertificates }: InternalCheckoutSelectors) => giftCertificates.getGiftCertificates,\n (getGiftCertificates) => clone(getGiftCertificates),\n );\n\n const getCustomer = createSelector(\n ({ customer }: InternalCheckoutSelectors) => customer.getCustomer,\n (getCustomer) => clone(getCustomer),\n );\n\n const getSignInEmail = createSelector(\n ({ signInEmail }: InternalCheckoutSelectors) => signInEmail.getEmail,\n (getEmail) => clone(getEmail),\n );\n\n const isPaymentDataRequired = createSelector(\n ({ payment }: InternalCheckoutSelectors) => payment.isPaymentDataRequired,\n (isPaymentDataRequired) => clone(isPaymentDataRequired),\n );\n\n const isPaymentDataSubmitted = createSelector(\n ({ payment }: InternalCheckoutSelectors) => payment.isPaymentDataSubmitted,\n ({ paymentMethods }: InternalCheckoutSelectors) => paymentMethods.getPaymentMethod,\n (isPaymentDataSubmitted, getPaymentMethod) =>\n clone((methodId: string, gatewayId?: string) => {\n return isPaymentDataSubmitted(getPaymentMethod(methodId, gatewayId));\n }),\n );\n\n const getInstruments = createSelector(\n ({ instruments }: InternalCheckoutSelectors) => instruments.getInstruments,\n ({ instruments }: InternalCheckoutSelectors) => instruments.getInstrumentsByPaymentMethod,\n (getInstruments, getInstrumentsByPaymentMethod) => {\n function getInstrumentsSelector(): Instrument[] | undefined;\n function getInstrumentsSelector(\n paymentMethod: PaymentMethod,\n ): PaymentInstrument[] | undefined;\n\n function getInstrumentsSelector(\n paymentMethod?: PaymentMethod,\n ): PaymentInstrument[] | undefined {\n return paymentMethod\n ? getInstrumentsByPaymentMethod(paymentMethod)\n : getInstruments();\n }\n\n return clone(getInstrumentsSelector);\n },\n );\n\n const getCustomerAccountFields = createSelector(\n ({ form }: InternalCheckoutSelectors) => form.getCustomerAccountFields,\n (getCustomerAccountFields) => clone(getCustomerAccountFields),\n );\n\n const getBillingAddressFields = createSelector(\n ({ form }: InternalCheckoutSelectors) => form.getBillingAddressFields,\n ({ countries }: InternalCheckoutSelectors) => countries.getCountries,\n (getBillingAddressFields, getCountries) =>\n clone((countryCode: string) => {\n return getBillingAddressFields(getCountries(), countryCode);\n }),\n );\n\n const getShippingAddressFields = createSelector(\n ({ form }: InternalCheckoutSelectors) => form.getShippingAddressFields,\n ({ shippingCountries }: InternalCheckoutSelectors) =>\n shippingCountries.getShippingCountries,\n (getShippingAddressFields, getShippingCountries) =>\n clone((countryCode: string) => {\n return getShippingAddressFields(getShippingCountries(), countryCode);\n }),\n );\n\n const getFlashMessages = createSelector(\n ({ config }: InternalCheckoutSelectors) => config.getFlashMessages,\n (getFlashMessages) => clone(getFlashMessages),\n );\n\n const getPickupOptions = createSelector(\n ({ pickupOptions }: InternalCheckoutSelectors) => pickupOptions.getPickupOptions,\n (getPickupOptions) => clone(getPickupOptions),\n );\n\n const getUserExperienceSettings = createSelector(\n ({ config }: InternalCheckoutSelectors) => config.getStoreConfig,\n (getStoreConfig) =>\n clone(() => {\n const config = getStoreConfig();\n\n if (!config) {\n return;\n }\n\n return config.checkoutSettings.checkoutUserExperienceSettings;\n }),\n );\n\n const getExtensions = createSelector(\n ({ extensions }: InternalCheckoutSelectors) => extensions.getExtensions,\n (getExtensions) => clone(getExtensions),\n );\n\n return memoizeOne((state: InternalCheckoutSelectors): CheckoutStoreSelector => {\n return {\n getCheckout: getCheckout(state),\n getOrder: getOrder(state),\n getConfig: getConfig(state),\n getExtensions: getExtensions(state),\n getFlashMessages: getFlashMessages(state),\n getShippingAddress: getShippingAddress(state),\n getShippingOptions: getShippingOptions(state),\n getConsignments: getConsignments(state),\n getSelectedShippingOption: getSelectedShippingOption(state),\n getShippingCountries: getShippingCountries(state),\n getBillingAddress: getBillingAddress(state),\n getBillingCountries: getBillingCountries(state),\n getPaymentMethods: getPaymentMethods(state),\n getPaymentMethod: getPaymentMethod(state),\n getSelectedPaymentMethod: getSelectedPaymentMethod(state),\n getCart: getCart(state),\n getCoupons: getCoupons(state),\n getGiftCertificates: getGiftCertificates(state),\n getCustomer: getCustomer(state),\n isPaymentDataRequired: isPaymentDataRequired(state),\n isPaymentDataSubmitted: isPaymentDataSubmitted(state),\n getSignInEmail: getSignInEmail(state),\n getInstruments: getInstruments(state),\n getCustomerAccountFields: getCustomerAccountFields(state),\n getBillingAddressFields: getBillingAddressFields(state),\n getShippingAddressFields: getShippingAddressFields(state),\n getPickupOptions: getPickupOptions(state),\n getUserExperienceSettings: getUserExperienceSettings(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { CartChangedError, CartConsistencyError } from '../cart/errors';\nimport { RequestError } from '../common/error/errors';\nimport { createSelector, createShallowEqualSelector } from '../common/selector';\nimport { Omit } from '../common/types';\n\nimport InternalCheckoutSelectors from './internal-checkout-selectors';\n\n/**\n * Responsible for getting the error of any asynchronous checkout action, if\n * there is any.\n *\n * This object has a set of getters that would return an error if an action is\n * not executed successfully. For example, if you are unable to submit an order,\n * you can use this object to retrieve the reason for the failure.\n */\nexport default interface CheckoutStoreErrorSelector {\n getError(): Error | undefined;\n\n /**\n * Returns an error if unable to load the current checkout.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadCheckoutError(): Error | undefined;\n\n /**\n * Returns an error if unable to update the current checkout.\n *\n * @returns The error object if unable to update, otherwise undefined.\n */\n getUpdateCheckoutError(): Error | undefined;\n\n /**\n * Returns an error if unable to submit the current order.\n *\n * @returns The error object if unable to submit, otherwise undefined.\n */\n getSubmitOrderError(): Error | CartChangedError | CartConsistencyError | undefined;\n\n /**\n * Returns an error if unable to finalize the current order.\n *\n * @returns The error object if unable to finalize, otherwise undefined.\n */\n getFinalizeOrderError(): Error | undefined;\n\n /**\n * Returns an error if unable to load the current order.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadOrderError(): Error | undefined;\n\n /**\n * Returns an error if unable to load the current cart.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadCartError(): Error | undefined;\n\n /**\n * Returns an error if unable to load billing countries.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadBillingCountriesError(): Error | undefined;\n\n /**\n * Returns an error if unable to load shipping countries.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadShippingCountriesError(): Error | undefined;\n\n /**\n * Returns an error if unable to load payment methods.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadPaymentMethodsError(): Error | undefined;\n\n /**\n * Returns an error if unable to load a specific payment method.\n *\n * @param methodId - The identifier of the payment method to load.\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadPaymentMethodError(methodId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to initialize a specific payment method.\n *\n * @param methodId - The identifier of the payment method to initialize.\n * @returns The error object if unable to initialize, otherwise undefined.\n */\n getInitializePaymentError(methodId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to sign in.\n *\n * @returns The error object if unable to sign in, otherwise undefined.\n */\n getSignInError(): Error | undefined;\n\n /**\n * Returns an error if unable to sign out.\n *\n * @returns The error object if unable to sign out, otherwise undefined.\n */\n getSignOutError(): Error | undefined;\n\n /**\n * Returns an error if unable to initialize the customer step of a checkout\n * process.\n *\n * @param methodId - The identifer of the initialization method to execute.\n * @returns The error object if unable to initialize, otherwise undefined.\n */\n getInitializeCustomerError(methodId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to load shipping options.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadShippingOptionsError(): Error | undefined;\n\n /**\n * Returns an error if unable to select a shipping option.\n *\n * A consignment ID should be provided when checking for an error for a\n * specific consignment, otherwise it will check for all available consignments.\n *\n * @param consignmentId - The identifier of the consignment to be checked.\n * @returns The error object if unable to select, otherwise undefined.\n */\n getSelectShippingOptionError(consignmentId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to continue as guest.\n *\n * The call could fail in scenarios where guest checkout is not allowed, for example, when existing accounts are required to sign-in.\n *\n * In the background, this call tries to set the billing address email using the Storefront API. You could access the Storefront API response status code using `getContinueAsGuestError` error selector.\n *\n * ```js\n * console.log(state.errors.getContinueAsGuestError());\n * console.log(state.errors.getContinueAsGuestError().status);\n * ```\n *\n * For more information about status codes, check [Checkout Storefront API - Add Checkout Billing Address](https://developer.bigcommerce.com/api-reference/cart-checkout/storefront-checkout-api/checkout-billing-address/checkoutsbillingaddressbycheckoutidpost).\n *\n * @returns The error object if unable to continue, otherwise undefined.\n */\n getContinueAsGuestError(): Error | undefined;\n\n /**\n * Returns an error if unable to update billing address.\n *\n * @returns The error object if unable to update, otherwise undefined.\n */\n getUpdateBillingAddressError(): Error | undefined;\n\n /**\n * Returns an error if unable to update subscriptions.\n *\n * @returns The error object if unable to update, otherwise undefined.\n */\n getUpdateSubscriptionsError(): Error | undefined;\n\n /**\n * Returns an error if unable to update shipping address.\n *\n * @returns The error object if unable to update, otherwise undefined.\n */\n getUpdateShippingAddressError(): Error | undefined;\n\n /**\n * Returns an error if unable to delete a consignment.\n *\n * A consignment ID should be provided when checking for an error for a\n * specific consignment, otherwise it will check for all available consignments.\n *\n * @param consignmentId - The identifier of the consignment to be checked.\n * @returns The error object if unable to delete, otherwise undefined.\n */\n getDeleteConsignmentError(consignmentId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to update a consignment.\n *\n * A consignment ID should be provided when checking for an error for a\n * specific consignment, otherwise it will check for all available consignments.\n *\n * @param consignmentId - The identifier of the consignment to be checked.\n * @returns The error object if unable to update, otherwise undefined.\n */\n getUpdateConsignmentError(consignmentId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to create consignments.\n *\n * @returns The error object if unable to create, otherwise undefined.\n */\n getCreateConsignmentsError(): Error | undefined;\n\n /**\n * Returns an error if unable to initialize the shipping step of a checkout\n * process.\n *\n * @param methodId - The identifer of the initialization method to execute.\n * @returns The error object if unable to initialize, otherwise undefined.\n */\n getInitializeShippingError(methodId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to apply store credit.\n *\n * @returns The error object if unable to apply, otherwise undefined.\n */\n getApplyStoreCreditError(): RequestError | undefined;\n\n /**\n * Returns an error if unable to apply a coupon code.\n *\n * @returns The error object if unable to apply, otherwise undefined.\n */\n getApplyCouponError(): RequestError | undefined;\n\n /**\n * Returns an error if unable to remove a coupon code.\n *\n * @returns The error object if unable to remove, otherwise undefined.\n */\n getRemoveCouponError(): RequestError | undefined;\n\n /**\n * Returns an error if unable to apply a gift certificate.\n *\n * @returns The error object if unable to apply, otherwise undefined.\n */\n getApplyGiftCertificateError(): RequestError | undefined;\n\n /**\n * Returns an error if unable to remove a gift certificate.\n *\n * @returns The error object if unable to remove, otherwise undefined.\n */\n getRemoveGiftCertificateError(): RequestError | undefined;\n\n /**\n * Returns an error if unable to load payment instruments.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadInstrumentsError(): Error | undefined;\n\n /**\n * Returns an error if unable to delete a payment instrument.\n *\n * @param instrumentId - The identifier of the payment instrument to delete.\n * @returns The error object if unable to delete, otherwise undefined.\n */\n getDeleteInstrumentError(instrumentId?: string): Error | undefined;\n\n /**\n * Returns an error if unable to load the checkout configuration of a store.\n *\n * @returns The error object if unable to load, otherwise undefined.\n */\n getLoadConfigError(): Error | undefined;\n\n /**\n * Returns an error if unable to send sign-in email.\n *\n * @returns The error object if unable to send email, otherwise undefined.\n */\n getSignInEmailError(): Error | undefined;\n\n /**\n * Returns an error if unable to create customer account.\n *\n * @returns The error object if unable to create account, otherwise undefined.\n */\n getCreateCustomerAccountError(): Error | undefined;\n\n /**\n * Returns an error if unable to create customer address.\n *\n * @returns The error object if unable to create address, otherwise undefined.\n */\n getCreateCustomerAddressError(): Error | undefined;\n\n /**\n * Returns an error if unable to fetch pickup options.\n *\n * @returns The error object if unable to fetch pickup options, otherwise undefined.\n */\n getPickupOptionsError(): Error | undefined;\n\n /**\n * Returns an error if unable to fetch extensions.\n *\n * @alpha\n * @returns The error object if unable to fetch extensions, otherwise undefined.\n */\n getLoadExtensionsError(): Error | undefined;\n}\n\nexport type CheckoutStoreErrorSelectorFactory = (\n state: InternalCheckoutSelectors,\n) => CheckoutStoreErrorSelector;\n\nexport function createCheckoutStoreErrorSelectorFactory(): CheckoutStoreErrorSelectorFactory {\n const getError = createShallowEqualSelector(\n (selector: Omit) => selector,\n (selector) => () => {\n for (const key of Object.keys(selector) as Array<\n keyof Omit\n >) {\n const error = selector[key]();\n\n if (error) {\n return error;\n }\n }\n },\n );\n\n const getSelectShippingOptionError = createSelector(\n ({ shippingStrategies }: InternalCheckoutSelectors) =>\n shippingStrategies.getSelectOptionError,\n ({ consignments }: InternalCheckoutSelectors) => consignments.getUpdateShippingOptionError,\n (getSelectOptionError, getUpdateShippingOptionError) => (consignmentId?: string) => {\n return getSelectOptionError() || getUpdateShippingOptionError(consignmentId);\n },\n );\n\n return memoizeOne((state: InternalCheckoutSelectors): CheckoutStoreErrorSelector => {\n const selector = {\n getLoadCheckoutError: state.checkout.getLoadError,\n getUpdateCheckoutError: state.checkout.getUpdateError,\n getSubmitOrderError: state.paymentStrategies.getExecuteError,\n getFinalizeOrderError: state.paymentStrategies.getFinalizeError,\n getLoadOrderError: state.order.getLoadError,\n getLoadCartError: state.cart.getLoadError,\n getLoadBillingCountriesError: state.countries.getLoadError,\n getLoadShippingCountriesError: state.shippingCountries.getLoadError,\n getLoadPaymentMethodsError: state.paymentMethods.getLoadError,\n getLoadPaymentMethodError: state.paymentMethods.getLoadMethodError,\n getInitializePaymentError: state.paymentStrategies.getInitializeError,\n getSignInError: state.customerStrategies.getSignInError,\n getSignOutError: state.customerStrategies.getSignOutError,\n getInitializeCustomerError: state.customerStrategies.getInitializeError,\n getLoadShippingOptionsError: state.consignments.getLoadShippingOptionsError,\n getSelectShippingOptionError: getSelectShippingOptionError(state),\n getContinueAsGuestError: state.billingAddress.getContinueAsGuestError,\n getUpdateBillingAddressError: state.billingAddress.getUpdateError,\n getUpdateSubscriptionsError: state.subscriptions.getUpdateError,\n getUpdateShippingAddressError: state.shippingStrategies.getUpdateAddressError,\n getDeleteConsignmentError: state.consignments.getDeleteError,\n getUpdateConsignmentError: state.consignments.getUpdateError,\n getCreateConsignmentsError: state.consignments.getCreateError,\n getInitializeShippingError: state.shippingStrategies.getInitializeError,\n getApplyStoreCreditError: state.storeCredit.getApplyError,\n getApplyCouponError: state.coupons.getApplyError,\n getRemoveCouponError: state.coupons.getRemoveError,\n getApplyGiftCertificateError: state.giftCertificates.getApplyError,\n getRemoveGiftCertificateError: state.giftCertificates.getRemoveError,\n getLoadInstrumentsError: state.instruments.getLoadError,\n getDeleteInstrumentError: state.instruments.getDeleteError,\n getLoadConfigError: state.config.getLoadError,\n getSignInEmailError: state.signInEmail.getSendError,\n getCreateCustomerAccountError: state.customer.getCreateAccountError,\n getCreateCustomerAddressError: state.customer.getCreateAddressError,\n getPickupOptionsError: state.pickupOptions.getLoadError,\n getLoadExtensionsError: state.extensions.getLoadError,\n };\n\n return {\n getError: getError(selector),\n ...selector,\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector, createShallowEqualSelector } from '../common/selector';\nimport { Omit } from '../common/types';\n\nimport InternalCheckoutSelectors from './internal-checkout-selectors';\n\n/**\n * Responsible for checking the statuses of various asynchronous actions related\n * to checkout.\n *\n * This object has a set of getters that return true if an action is in\n * progress. For example, you can check whether a customer is submitting an\n * order and waiting for the request to complete.\n */\nexport default interface CheckoutStoreStatusSelector {\n /**\n * Checks whether any checkout action is pending.\n *\n * @returns True if there is a pending action, otherwise false.\n */\n isPending(): boolean;\n\n /**\n * Checks whether the current checkout is loading.\n *\n * @returns True if the current checkout is loading, otherwise false.\n */\n isLoadingCheckout(): boolean;\n\n /**\n * Checks whether the current checkout is being updated.\n *\n * @returns True if the current checkout is being updated, otherwise false.\n */\n isUpdatingCheckout(): boolean;\n\n /**\n * Checks whether spam check is executing.\n *\n * @returns True if the current checkout is being updated, otherwise false.\n */\n isExecutingSpamCheck(): boolean;\n\n /**\n * Checks whether the current order is submitting.\n *\n * @returns True if the current order is submitting, otherwise false.\n */\n isSubmittingOrder(): boolean;\n\n /**\n * Checks whether the current order is finalizing.\n *\n * @returns True if the current order is finalizing, otherwise false.\n */\n isFinalizingOrder(): boolean;\n\n /**\n * Checks whether the current order is loading.\n *\n * @returns True if the current order is loading, otherwise false.\n */\n isLoadingOrder(): boolean;\n\n /**\n * Checks whether the current cart is loading.\n *\n * @returns True if the current cart is loading, otherwise false.\n */\n isLoadingCart(): boolean;\n\n /**\n * Checks whether billing countries are loading.\n *\n * @returns True if billing countries are loading, otherwise false.\n */\n isLoadingBillingCountries(): boolean;\n\n /**\n * Checks whether shipping countries are loading.\n *\n * @returns True if shipping countries are loading, otherwise false.\n */\n isLoadingShippingCountries(): boolean;\n\n /**\n * Checks whether payment methods are loading.\n *\n * @returns True if payment methods are loading, otherwise false.\n */\n isLoadingPaymentMethods(): boolean;\n\n /**\n * Checks whether a specific or any payment method is loading.\n *\n * The method returns true if no ID is provided and at least one payment\n * method is loading.\n *\n * @param methodId - The identifier of the payment method to check.\n * @returns True if the payment method is loading, otherwise false.\n */\n isLoadingPaymentMethod(methodId?: string): boolean;\n\n /**\n * Checks whether a specific or any payment method is initializing.\n *\n * The method returns true if no ID is provided and at least one payment\n * method is initializing.\n *\n * @param methodId - The identifier of the payment method to check.\n * @returns True if the payment method is initializing, otherwise false.\n */\n isInitializingPayment(methodId?: string): boolean;\n\n /**\n * Checks whether the current customer is signing in.\n *\n * If an ID is provided, the method also checks whether the customer is\n * signing in using a specific customer method with the same ID.\n *\n * @param methodId - The identifier of the method used for signing in the\n * current customer.\n * @returns True if the customer is signing in, otherwise false.\n */\n isSigningIn(methodId?: string): boolean;\n\n /**\n * Checks whether the current customer is signing out.\n *\n * If an ID is provided, the method also checks whether the customer is\n * signing out using a specific customer method with the same ID.\n *\n * @param methodId - The identifier of the method used for signing out the\n * current customer.\n * @returns True if the customer is signing out, otherwise false.\n */\n isSigningOut(methodId?: string): boolean;\n\n /**\n * Checks whether the customer step is initializing.\n *\n * If an ID is provided, the method also checks whether the customer step is\n * initializing using a specific customer method with the same ID.\n *\n * @param methodId - The identifier of the method used for initializing the\n * customer step of checkout.\n * @returns True if the customer step is initializing, otherwise false.\n */\n isInitializingCustomer(methodId?: string): boolean;\n\n /**\n * Checks whether a wallet button is initialized.\n *\n * @param methodId - The identifier of the payment method to check.\n * @returns True if the wallet button method is initialized, otherwise false.\n */\n isInitializedCustomer(methodId?: string): boolean;\n\n /**\n * Checks whether the current customer is executing payment method checkout.\n *\n * If an ID is provided, the method also checks whether the customer is\n * executing payment method checkout using a specific customer method with the same ID.\n *\n * @param methodId - The identifier of the method used for continuing the\n * current customer.\n * @returns True if the customer is executing payment method checkout, otherwise false.\n */\n isExecutingPaymentMethodCheckout(methodId?: string): boolean;\n\n /**\n * Checks whether shipping options are loading.\n *\n * @returns True if shipping options are loading, otherwise false.\n */\n isLoadingShippingOptions(): boolean;\n\n /**\n * Checks whether a shipping option is being selected.\n *\n * A consignment ID should be provided when checking if a shipping option\n * is being selected for a specific consignment, otherwise it will check\n * for all consignments.\n *\n * @param consignmentId - The identifier of the consignment to be checked.\n * @returns True if selecting a shipping option, otherwise false.\n */\n isSelectingShippingOption(consignmentId?: string): boolean;\n\n /**\n * Checks whether the billing address is being updated.\n *\n * @returns True if updating their billing address, otherwise false.\n */\n isUpdatingBillingAddress(): boolean;\n\n /**\n * Checks whether the shopper is continuing out as a guest.\n *\n * @returns True if continuing as guest, otherwise false.\n */\n isContinuingAsGuest(): boolean;\n\n /**\n * Checks the shipping address is being updated.\n *\n * @returns True if updating their shipping address, otherwise false.\n */\n isUpdatingShippingAddress(): boolean;\n\n /**\n * Checks whether a given/any consignment is being updated.\n *\n * A consignment ID should be provided when checking for a specific consignment,\n * otherwise it will check for any consignment.\n *\n * @param consignmentId - The identifier of the consignment to be checked.\n * @returns True if updating consignment(s), otherwise false.\n */\n isUpdatingConsignment(consignmentId?: string): boolean;\n\n /**\n * Checks whether a given/any consignment is being deleted.\n *\n * A consignment ID should be provided when checking for a specific consignment,\n * otherwise it will check for any consignment.\n *\n * @param consignmentId - The identifier of the consignment to be checked.\n * @returns True if deleting consignment(s), otherwise false.\n */\n isDeletingConsignment(consignmentId?: string): boolean;\n\n /**\n * Checks whether a given/any consignment is being updated.\n *\n * A consignment ID should be provided when checking for a specific consignment,\n * otherwise it will check for any consignment.\n *\n * @returns True if creating consignments, otherwise false.\n */\n isCreatingConsignments(): boolean;\n\n /**\n * Checks whether the shipping step of a checkout process is initializing.\n *\n * If an identifier is provided, the method also checks whether the shipping\n * step is initializing using a specific shipping method with the same\n * identifier.\n *\n * @param methodId - The identifer of the initialization method to check.\n * @returns True if the shipping step is initializing, otherwise false.\n */\n isInitializingShipping(methodId?: string): boolean;\n\n /**\n * Checks whether the current customer is applying a coupon code.\n *\n * @returns True if applying a coupon code, otherwise false.\n */\n isApplyingCoupon(): boolean;\n\n /**\n * Checks whether the current customer is applying store credit.\n *\n * @returns True if applying store credit, otherwise false.\n */\n isApplyingStoreCredit(): boolean;\n\n /**\n * Checks whether the current customer is removing a coupon code.\n *\n * @returns True if removing a coupon code, otherwise false.\n */\n isRemovingCoupon(): boolean;\n\n /**\n * Checks whether a sign-in email is being sent.\n *\n * @returns True if sending a sign-in email, otherwise false\n */\n isSendingSignInEmail(): boolean;\n\n /**\n * Checks whether the current customer is applying a gift certificate.\n *\n * @returns True if applying a gift certificate, otherwise false.\n */\n isApplyingGiftCertificate(): boolean;\n\n /**\n * Checks whether the current customer is removing a gift certificate.\n *\n * @returns True if removing a gift certificate, otherwise false.\n */\n isRemovingGiftCertificate(): boolean;\n\n /**\n * Checks whether the current customer's payment instruments are loading.\n *\n * @returns True if payment instruments are loading, otherwise false.\n */\n isLoadingInstruments(): boolean;\n\n /**\n * Checks whether the current customer is deleting a payment instrument.\n *\n * @returns True if deleting a payment instrument, otherwise false.\n */\n isDeletingInstrument(instrumentId?: string): boolean;\n\n /**\n * Checks whether the checkout configuration of a store is loading.\n *\n * @returns True if the configuration is loading, otherwise false.\n */\n isLoadingConfig(): boolean;\n\n /**\n * Checks whether the customer step of a checkout is in a pending state.\n *\n * The customer step is considered to be pending if it is in the process of\n * initializing, signing in, signing out, and/or interacting with a customer\n * widget.\n *\n * @returns True if the customer step is pending, otherwise false.\n */\n isCustomerStepPending(): boolean;\n\n /**\n * Checks whether the shipping step of a checkout is in a pending state.\n *\n * The shipping step is considered to be pending if it is in the process of\n * initializing, updating address, selecting a shipping option, and/or\n * interacting with a shipping widget.\n *\n * @returns True if the shipping step is pending, otherwise false.\n */\n isShippingStepPending(): boolean;\n\n /**\n * Checks whether the payment step of a checkout is in a pending state.\n *\n * The payment step is considered to be pending if it is in the process of\n * initializing, submitting an order, finalizing an order, and/or\n * interacting with a payment widget.\n *\n * @returns True if the payment step is pending, otherwise false.\n */\n isPaymentStepPending(): boolean;\n\n /**\n * Checks whether the subscriptions are being updated.\n *\n * @returns True if updating subscriptions, otherwise false.\n */\n isUpdatingSubscriptions(): boolean;\n\n /**\n * Checks whether a customer account is being created\n *\n * @returns True if creating, otherwise false.\n */\n isCreatingCustomerAccount(): boolean;\n\n /**\n * Checks whether a customer address is being created\n *\n * @returns True if creating, otherwise false.\n */\n isCreatingCustomerAddress(): boolean;\n\n /**\n * Checks whether pickup options are loading.\n *\n * @returns True if pickup options are loading, otherwise false.\n */\n isLoadingPickupOptions(): boolean;\n}\n\nexport type CheckoutStoreStatusSelectorFactory = (\n state: InternalCheckoutSelectors,\n) => CheckoutStoreStatusSelector;\n\nexport function createCheckoutStoreStatusSelectorFactory(): CheckoutStoreStatusSelectorFactory {\n const isPending = createShallowEqualSelector(\n (selector: Omit) => selector,\n (selector) => () => {\n return (\n Object.keys(selector) as Array>\n ).some((key) => selector[key]());\n },\n );\n\n const isSelectingShippingOption = createSelector(\n ({ shippingStrategies }: InternalCheckoutSelectors) => shippingStrategies.isSelectingOption,\n ({ consignments }: InternalCheckoutSelectors) => consignments.isUpdatingShippingOption,\n (isSelectingOption, isUpdatingShippingOption) => (consignmentId?: string) => {\n return isSelectingOption() || isUpdatingShippingOption(consignmentId);\n },\n );\n\n const isCustomerStepPending = createSelector(\n ({ customerStrategies }: InternalCheckoutSelectors) => customerStrategies.isInitializing,\n ({ customerStrategies }: InternalCheckoutSelectors) => customerStrategies.isSigningIn,\n ({ customerStrategies }: InternalCheckoutSelectors) => customerStrategies.isSigningOut,\n ({ customerStrategies }: InternalCheckoutSelectors) =>\n customerStrategies.isExecutingPaymentMethodCheckout,\n ({ customerStrategies }: InternalCheckoutSelectors) =>\n customerStrategies.isWidgetInteracting,\n (\n isInitializing,\n isSigningIn,\n isSigningOut,\n isExecutingPaymentMethodCheckout,\n isWidgetInteracting,\n ) =>\n (methodId?: string) => {\n return (\n isInitializing(methodId) ||\n isSigningIn(methodId) ||\n isSigningOut(methodId) ||\n isExecutingPaymentMethodCheckout(methodId) ||\n isWidgetInteracting(methodId)\n );\n },\n );\n\n const isShippingStepPending = createSelector(\n ({ shippingStrategies }: InternalCheckoutSelectors) => shippingStrategies.isInitializing,\n ({ shippingStrategies }: InternalCheckoutSelectors) => shippingStrategies.isUpdatingAddress,\n ({ shippingStrategies }: InternalCheckoutSelectors) => shippingStrategies.isSelectingOption,\n ({ shippingStrategies }: InternalCheckoutSelectors) =>\n shippingStrategies.isWidgetInteracting,\n (isInitializing, isUpdatingAddress, isSelectingOption, isWidgetInteracting) =>\n (methodId?: string) => {\n return (\n isInitializing(methodId) ||\n isUpdatingAddress(methodId) ||\n isSelectingOption(methodId) ||\n isWidgetInteracting(methodId)\n );\n },\n );\n\n const isPaymentStepPending = createSelector(\n ({ paymentStrategies }: InternalCheckoutSelectors) => paymentStrategies.isInitializing,\n ({ paymentStrategies }: InternalCheckoutSelectors) => paymentStrategies.isExecuting,\n ({ paymentStrategies }: InternalCheckoutSelectors) => paymentStrategies.isFinalizing,\n ({ paymentStrategies }: InternalCheckoutSelectors) => paymentStrategies.isWidgetInteracting,\n (isInitializing, isExecuting, isFinalizing, isWidgetInteracting) => (methodId?: string) => {\n return (\n isInitializing(methodId) ||\n isExecuting(methodId) ||\n isFinalizing(methodId) ||\n isWidgetInteracting(methodId)\n );\n },\n );\n\n const isSubmittingOrder = createSelector(\n ({ paymentStrategies }: InternalCheckoutSelectors) => paymentStrategies.isExecuting,\n ({ checkout }: InternalCheckoutSelectors) => checkout.isExecutingSpamCheck, // Remove this when CheckoutService#initializeSpamProtection is deprecated\n (isExecuting, isExecutingSpamCheck) => (methodId?: string) => {\n return isExecuting(methodId) || isExecutingSpamCheck();\n },\n );\n\n return memoizeOne((state: InternalCheckoutSelectors): CheckoutStoreStatusSelector => {\n const selector = {\n isLoadingCheckout: state.checkout.isLoading,\n isUpdatingCheckout: state.checkout.isUpdating,\n isExecutingSpamCheck: state.checkout.isExecutingSpamCheck,\n isSubmittingOrder: isSubmittingOrder(state),\n isFinalizingOrder: state.paymentStrategies.isFinalizing,\n isLoadingOrder: state.order.isLoading,\n isLoadingCart: state.cart.isLoading,\n isLoadingBillingCountries: state.countries.isLoading,\n isLoadingShippingCountries: state.shippingCountries.isLoading,\n isLoadingPaymentMethods: state.paymentMethods.isLoading,\n isLoadingPaymentMethod: state.paymentMethods.isLoadingMethod,\n isInitializingPayment: state.paymentStrategies.isInitializing,\n isSigningIn: state.customerStrategies.isSigningIn,\n isSigningOut: state.customerStrategies.isSigningOut,\n isExecutingPaymentMethodCheckout:\n state.customerStrategies.isExecutingPaymentMethodCheckout,\n isInitializingCustomer: state.customerStrategies.isInitializing,\n isInitializedCustomer: state.customerStrategies.isInitialized,\n isLoadingShippingOptions: state.consignments.isLoadingShippingOptions,\n isSelectingShippingOption: isSelectingShippingOption(state),\n isUpdatingBillingAddress: state.billingAddress.isUpdating,\n isUpdatingSubscriptions: state.subscriptions.isUpdating,\n isCreatingCustomerAccount: state.customer.isCreatingCustomerAccount,\n isCreatingCustomerAddress: state.customer.isCreatingCustomerAddress,\n isContinuingAsGuest: state.billingAddress.isContinuingAsGuest,\n isUpdatingShippingAddress: state.shippingStrategies.isUpdatingAddress,\n isUpdatingConsignment: state.consignments.isUpdating,\n isDeletingConsignment: state.consignments.isDeleting,\n isCreatingConsignments: state.consignments.isCreating,\n isInitializingShipping: state.shippingStrategies.isInitializing,\n isApplyingStoreCredit: state.storeCredit.isApplying,\n isApplyingCoupon: state.coupons.isApplying,\n isRemovingCoupon: state.coupons.isRemoving,\n isApplyingGiftCertificate: state.giftCertificates.isApplying,\n isRemovingGiftCertificate: state.giftCertificates.isRemoving,\n isLoadingInstruments: state.instruments.isLoading,\n isDeletingInstrument: state.instruments.isDeleting,\n isLoadingConfig: state.config.isLoading,\n isSendingSignInEmail: state.signInEmail.isSending,\n isCustomerStepPending: isCustomerStepPending(state),\n isShippingStepPending: isShippingStepPending(state),\n isPaymentStepPending: isPaymentStepPending(state),\n isLoadingPickupOptions: state.pickupOptions.isLoading,\n };\n\n return {\n isPending: isPending(selector),\n ...selector,\n };\n });\n}\n","import {\n CheckoutSelectors,\n createCheckoutStoreErrorSelectorFactory,\n createCheckoutStoreSelectorFactory,\n createCheckoutStoreStatusSelectorFactory,\n InternalCheckoutSelectors,\n} from '../checkout';\n\nexport type CheckoutSelectorsFactory = (selectors: InternalCheckoutSelectors) => CheckoutSelectors;\n\nexport function createCheckoutSelectorsFactory(): CheckoutSelectorsFactory {\n const createCheckoutStoreSelector = createCheckoutStoreSelectorFactory();\n const createCheckoutStoreErrorSelector = createCheckoutStoreErrorSelectorFactory();\n const createCheckoutStoreStatusSelector = createCheckoutStoreStatusSelectorFactory();\n\n return (selectors: InternalCheckoutSelectors) => {\n const data = createCheckoutStoreSelector(selectors);\n const errors = createCheckoutStoreErrorSelector(selectors);\n const statuses = createCheckoutStoreStatusSelector(selectors);\n\n return {\n data,\n errors,\n statuses,\n };\n };\n}\n\nexport default function createCheckoutSelectors(\n selectors: InternalCheckoutSelectors,\n): CheckoutSelectors {\n return createCheckoutSelectorsFactory()(selectors);\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport RequestError from './request-error';\n\n/**\n * Throw this error if there is an unexpected error and it is not possible to\n * recover from unless the shopper creates a new checkout session.\n */\nexport default class UnrecoverableError extends RequestError {\n constructor(response: Response, message?: string) {\n super(response, {\n message:\n message ||\n 'An unexpected error has occurred. The checkout process cannot continue as a result.',\n });\n\n this.name = 'UnrecoverableError';\n this.type = 'unrecoverable';\n }\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { InternalErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport RequestError from './request-error';\n\nexport default function mapFromInternalErrorResponse(\n response: Response,\n message?: string,\n): RequestError {\n const { body } = response;\n const { errors = [] } = body;\n\n return new RequestError(response, {\n message: joinErrors(errors) || body.detail || body.title || message,\n errors: errors.length\n ? errors.map((message) => ({ code: body.type, message }))\n : [{ code: body.type, message: body.detail || body.title }],\n });\n}\n\nfunction joinErrors(errors: string[]): string | undefined {\n return errors\n .reduce((result: string[], error) => {\n if (error) {\n return [...result, error];\n }\n\n return result;\n }, [])\n .join(' ');\n}\n","import { Response } from '@bigcommerce/request-sender';\nimport { last } from 'lodash';\n\nimport {\n ErrorResponseBody,\n InternalErrorResponseBody,\n StorefrontErrorResponseBody,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n mapFromInternalErrorResponse,\n mapFromPaymentErrorResponse,\n mapFromStorefrontErrorResponse,\n RequestError,\n TimeoutError,\n} from './errors';\n\nexport default class RequestErrorFactory {\n private _factoryMethods: { [key: string]: ErrorFactoryMethod } = {};\n\n constructor() {\n this.register('default', (response, message) => new RequestError(response, { message }));\n this.register('internal', (response, message) =>\n mapFromInternalErrorResponse(response, message),\n );\n this.register('storefront', (response, message) =>\n mapFromStorefrontErrorResponse(response, message),\n );\n this.register('payment', (response, message) =>\n mapFromPaymentErrorResponse(response, message),\n );\n this.register('timeout', (response) => new TimeoutError(response));\n }\n\n register(type: string, factoryMethod: ErrorFactoryMethod): void {\n this._factoryMethods[type] = factoryMethod;\n }\n\n createError(response: Response, message?: string): RequestError {\n const factoryMethod =\n this._factoryMethods[this._getType(response)] || this._factoryMethods.default;\n\n return factoryMethod(response, message);\n }\n\n private _getType(response: Response): string {\n if (response.status === 0) {\n return 'timeout';\n }\n\n if (this._isStorefrontErrorResponseBody(response.body)) {\n return 'storefront';\n }\n\n if (this._isInternalErrorResponseBody(response.body)) {\n const internalType = last(response.body.type.split('/'));\n\n return internalType && this._factoryMethods[internalType] ? internalType : 'internal';\n }\n\n const error = last(response.body && response.body.errors);\n\n if (error && error.code && this._factoryMethods[error.code]) {\n return error.code;\n }\n\n return 'payment';\n }\n\n private _isStorefrontErrorResponseBody(\n errorResponse: ErrorResponseBody,\n ): errorResponse is StorefrontErrorResponseBody {\n const storefrontErrorResponse = errorResponse as StorefrontErrorResponseBody;\n\n return (\n !this._isInternalErrorResponseBody(errorResponse) &&\n typeof storefrontErrorResponse.title === 'string' &&\n typeof storefrontErrorResponse.type === 'string' &&\n typeof storefrontErrorResponse.status === 'number' &&\n typeof storefrontErrorResponse.detail === 'string'\n );\n }\n\n private _isInternalErrorResponseBody(\n errorResponse: ErrorResponseBody,\n ): errorResponse is InternalErrorResponseBody {\n const internalErrorResponse = errorResponse as InternalErrorResponseBody;\n\n return (\n typeof internalErrorResponse.errors === 'object' &&\n typeof internalErrorResponse.title === 'string' &&\n typeof internalErrorResponse.type === 'string' &&\n typeof internalErrorResponse.status === 'number'\n );\n }\n}\n\nexport type ErrorFactoryMethod = (response: Response, message?: string) => RequestError;\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport RequestError from './request-error';\n\nexport default function mapFromStorefrontErrorResponse(\n response: Response,\n message?: string,\n): RequestError {\n const { body } = response;\n\n return new RequestError(response, {\n message: message || body.detail || body.title,\n errors: [\n {\n code: body.code || body.type,\n message: body.detail || body.title,\n },\n ],\n });\n}\n","import { isPlainObject, omitBy, transform } from 'lodash';\n\nexport default function omitDeep(\n object: any,\n predicate: (value: any, key: string) => boolean,\n): any {\n if (Array.isArray(object)) {\n return object.map((value) => omitDeep(value, predicate));\n }\n\n if (isPlainObject(object)) {\n return transform(\n omitBy(object, predicate),\n (result, value, key) => {\n result[key] = omitDeep(value, predicate);\n },\n {} as { [key: string]: any },\n );\n }\n\n return object;\n}\n","import { Action } from '@bigcommerce/data-store';\n\nimport { omitDeep } from '../utility';\n\nimport { ClearErrorAction, ErrorActionType } from './error-actions';\n\nexport default function clearErrorReducer<\n TState extends { [key: string]: any },\n TAction extends Action,\n>(state: TState, action: TAction): TState | undefined {\n if (isClearErrorAction(action)) {\n return omitDeep(state, (value) => value === action.payload);\n }\n\n return state;\n}\n\nfunction isClearErrorAction(action: Action): action is ClearErrorAction {\n return action.type === ErrorActionType.ClearError;\n}\n","export interface CompareOptions {\n keyFilter?(key: string): boolean;\n}\n\nexport default function isEqual(objectA: any, objectB: any, options?: CompareOptions): boolean {\n if (objectA === objectB) {\n return true;\n }\n\n if (objectA && objectB && typeof objectA === 'object' && typeof objectB === 'object') {\n if (Array.isArray(objectA) && Array.isArray(objectB)) {\n return isArrayEqual(objectA, objectB, options);\n }\n\n if (Array.isArray(objectA) || Array.isArray(objectB)) {\n return false;\n }\n\n if (objectA instanceof Date && objectB instanceof Date) {\n return isDateEqual(objectA, objectB);\n }\n\n if (objectA instanceof Date || objectB instanceof Date) {\n return false;\n }\n\n if (objectA instanceof RegExp && objectB instanceof RegExp) {\n return isRegExpEqual(objectA, objectB);\n }\n\n if (objectA instanceof RegExp || objectB instanceof RegExp) {\n return false;\n }\n\n return isObjectEqual(objectA, objectB, options);\n }\n\n return objectA === objectB;\n}\n\nfunction isRegExpEqual(objectA: RegExp, objectB: RegExp): boolean {\n return objectA.toString() === objectB.toString();\n}\n\nfunction isDateEqual(objectA: Date, objectB: Date): boolean {\n return objectA.getTime() === objectB.getTime();\n}\n\nfunction isArrayEqual(objectA: any[], objectB: any[], options?: CompareOptions): boolean {\n if (objectA.length !== objectB.length) {\n return false;\n }\n\n for (let index = 0, length = objectA.length; index < length; index++) {\n if (!isEqual(objectA[index], objectB[index], options)) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction isObjectEqual(\n objectA: { [key: string]: any },\n objectB: { [key: string]: any },\n options?: CompareOptions,\n): boolean {\n const filter = options && options.keyFilter;\n const keysA = filter ? Object.keys(objectA).filter(filter) : Object.keys(objectA);\n const keysB = filter ? Object.keys(objectB).filter(filter) : Object.keys(objectB);\n\n if (keysA.length !== keysB.length) {\n return false;\n }\n\n for (let index = 0, length = keysA.length; index < length; index++) {\n const key = keysA[index];\n\n if (!Object.prototype.hasOwnProperty.call(objectB, key)) {\n return false;\n }\n\n if (!isEqual(objectA[key], objectB[key], options)) {\n return false;\n }\n }\n\n return true;\n}\n","import isEqual from './is-equal';\n\n/**\n * Replace the current value with a new value if the former is different to the\n * latter.\n */\nexport default function replace(currentValue: T, newValue?: T): T {\n if (newValue === undefined || isEqual(currentValue, newValue)) {\n return currentValue;\n }\n\n return newValue;\n}\n","import isEqual from './is-equal';\n\n/**\n * Set a new value to an object under a key if the new value is different to the\n * current value of the key.\n */\nexport default function objectSet(\n object: T | undefined,\n key: K,\n value: T[K],\n): T {\n if (\n object &&\n Object.prototype.hasOwnProperty.call(object, key) &&\n isEqual(object[key], value)\n ) {\n return object;\n }\n\n return {\n ...(object as any),\n [key]: value,\n };\n}\n","import BillingAddress from './billing-address';\n\nexport default interface BillingAddressState {\n data?: BillingAddress;\n errors: BillingAddressErrorsState;\n statuses: BillingAddressStatusesState;\n}\n\nexport interface BillingAddressErrorsState {\n loadError?: Error;\n updateError?: Error;\n continueAsGuestError?: Error;\n}\n\nexport interface BillingAddressStatusesState {\n isLoading?: boolean;\n isUpdating?: boolean;\n isContinuingAsGuest?: boolean;\n}\n\nexport const DEFAULT_STATE: BillingAddressState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { objectSet, replace } from '../common/utility';\nimport { OrderAction } from '../order';\nimport { SubscriptionsActionType, UpdateSubscriptionsAction } from '../subscription';\n\nimport BillingAddress from './billing-address';\nimport { BillingAddressAction, BillingAddressActionType } from './billing-address-actions';\nimport BillingAddressState, {\n BillingAddressErrorsState,\n BillingAddressStatusesState,\n DEFAULT_STATE,\n} from './billing-address-state';\n\nexport default function billingAddressReducer(\n state: BillingAddressState = DEFAULT_STATE,\n action: Action,\n): BillingAddressState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: BillingAddress | undefined,\n action: CheckoutAction | BillingAddressAction | OrderAction,\n): BillingAddress | undefined {\n switch (action.type) {\n case BillingAddressActionType.UpdateBillingAddressSucceeded:\n case BillingAddressActionType.ContinueAsGuestSucceeded:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return replace(data, action.payload && action.payload.billingAddress);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: BillingAddressErrorsState = DEFAULT_STATE.errors,\n action: CheckoutAction | BillingAddressAction | OrderAction | UpdateSubscriptionsAction,\n): BillingAddressErrorsState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case CheckoutActionType.LoadCheckoutFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n case BillingAddressActionType.UpdateBillingAddressRequested:\n case BillingAddressActionType.UpdateBillingAddressSucceeded:\n return objectSet(errors, 'updateError', undefined);\n\n case BillingAddressActionType.UpdateBillingAddressFailed:\n return objectSet(errors, 'updateError', action.payload);\n\n case SubscriptionsActionType.UpdateSubscriptionsRequested:\n case SubscriptionsActionType.UpdateSubscriptionsSucceeded:\n case BillingAddressActionType.ContinueAsGuestRequested:\n case BillingAddressActionType.ContinueAsGuestSucceeded:\n return objectSet(errors, 'continueAsGuestError', undefined);\n\n case SubscriptionsActionType.UpdateSubscriptionsFailed:\n case BillingAddressActionType.ContinueAsGuestFailed:\n return objectSet(errors, 'continueAsGuestError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: BillingAddressStatusesState = DEFAULT_STATE.statuses,\n action: CheckoutAction | BillingAddressAction | OrderAction | UpdateSubscriptionsAction,\n): BillingAddressStatusesState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case CheckoutActionType.LoadCheckoutSucceeded:\n case CheckoutActionType.LoadCheckoutFailed:\n return objectSet(statuses, 'isLoading', false);\n\n case BillingAddressActionType.UpdateBillingAddressRequested:\n return objectSet(statuses, 'isUpdating', true);\n\n case BillingAddressActionType.UpdateBillingAddressFailed:\n case BillingAddressActionType.UpdateBillingAddressSucceeded:\n return objectSet(statuses, 'isUpdating', false);\n\n case BillingAddressActionType.ContinueAsGuestRequested:\n case SubscriptionsActionType.UpdateSubscriptionsRequested:\n return objectSet(statuses, 'isContinuingAsGuest', true);\n\n case SubscriptionsActionType.UpdateSubscriptionsSucceeded:\n case SubscriptionsActionType.UpdateSubscriptionsFailed:\n case BillingAddressActionType.ContinueAsGuestFailed:\n case BillingAddressActionType.ContinueAsGuestSucceeded:\n return objectSet(statuses, 'isContinuingAsGuest', false);\n\n default:\n return statuses;\n }\n}\n","import { isArray } from 'lodash';\n\nimport isPlainObject from './is-plain-object';\nimport objectMerge from './object-merge';\nimport replace from './replace';\n\nexport interface ArrayReplaceOptions {\n matchObject(objectA: any, objectB: any): boolean;\n}\n\nfunction arrayReplace(\n currentArray: T[] | undefined,\n newArray: T[],\n options?: ArrayReplaceOptions,\n): T[];\nfunction arrayReplace(\n currentArray: T[],\n newArray?: T[],\n options?: ArrayReplaceOptions,\n): undefined;\nfunction arrayReplace(\n currentArray?: T[],\n newArray?: T[],\n options?: ArrayReplaceOptions,\n): T[] | undefined;\n\nfunction arrayReplace(\n currentArray?: T[],\n newArray?: T[],\n options?: ArrayReplaceOptions,\n): T[] | undefined {\n const { matchObject = (a: any, b: any) => a.id !== undefined && a.id === b.id } = options || {};\n\n // Return the new array if the current array does not exist\n if (!currentArray) {\n return newArray;\n }\n\n // If the new array does not exist, or the current array is strictly equal\n // to the new array, exit early and return the current array so that the\n // object reference doesn't change\n if (!newArray || currentArray === newArray) {\n return currentArray;\n }\n\n // Otherwise, try to replace the items of the current array with the new\n // array. If the item from the two arrays are the same, keep the current\n // one. Do it recursively until all arrays are replaced.\n let sameAsCurrentCount = 0;\n let sameAsNewCount = 0;\n\n const countSameAsReplaced = (replacedValue: T, currentValue: T, newValue: T): T => {\n sameAsCurrentCount += replacedValue === currentValue ? 1 : 0;\n sameAsNewCount += replacedValue === newValue ? 1 : 0;\n\n return replacedValue;\n };\n\n const result = newArray.map((newItem, index) => {\n const currentItem = currentArray && currentArray[index];\n\n if (isPlainObject(currentItem) && isPlainObject(newItem)) {\n if (matchObject(currentItem, newItem)) {\n return countSameAsReplaced(objectMerge(currentItem, newItem), currentItem, newItem);\n }\n\n return countSameAsReplaced(replace(currentItem, newItem), currentItem, newItem);\n }\n\n if (isArray(currentItem) && isArray(newItem)) {\n return countSameAsReplaced(arrayReplace(currentItem, newItem), currentItem, newItem);\n }\n\n return countSameAsReplaced(replace(currentItem, newItem), currentItem, newItem);\n }) as T[];\n\n // If all items in the result are identical to the current array, and the\n // current array and the new array have the same size, simply return the\n // current array instead of the result.\n if (\n sameAsCurrentCount === newArray.length &&\n currentArray &&\n currentArray.length === newArray.length\n ) {\n return currentArray;\n }\n\n // If all items in the result are identical to the new array, simply return\n // the new array.\n if (sameAsNewCount === newArray.length) {\n return newArray;\n }\n\n return result;\n}\n\nexport default arrayReplace;\n","import { isArray } from 'lodash';\n\nimport arrayReplace from './array-replace';\nimport isPlainObject from './is-plain-object';\nimport objectSet from './object-set';\n\nfunction objectMerge(currentObject: T, newObject?: Partial): T;\nfunction objectMerge(\n currentObject: T | undefined,\n newObject: Partial,\n): Partial;\nfunction objectMerge(currentObject?: T, newObject?: Partial): T | undefined;\n\nfunction objectMerge(\n currentObject?: T,\n newObject?: Partial,\n): T | Partial | undefined {\n if (!currentObject) {\n return newObject;\n }\n\n // If the new object does not exist but the current object does, or the new\n // object is strictly equal to the current object, return the current object\n if (!newObject || currentObject === newObject) {\n return currentObject;\n }\n\n // If both objects exist, but some values might be different, perform a merge.\n // Retain values that are equal and only replace them with the new values if\n // they are different.\n return (Object.keys(newObject) as Array).reduce((result, key) => {\n const currentValue = result[key];\n const newValue = newObject[key];\n\n if (isPlainObject(currentValue) && isPlainObject(newValue)) {\n return objectSet(result, key, objectMerge(currentValue, newValue));\n }\n\n if (isArray(currentValue) && isArray(newValue)) {\n return objectSet(result, key, arrayReplace(currentValue, newValue) as any);\n }\n\n return objectSet(result, key, newValue as any);\n }, currentObject);\n}\n\nexport default objectMerge;\n","import Cart from './cart';\n\nexport default interface CartState {\n data?: Cart;\n errors: CartErrorsState;\n statuses: CartStatusesState;\n}\n\nexport interface CartErrorsState {\n loadError?: Error;\n}\n\nexport interface CartStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: CartState = {\n errors: {},\n statuses: {},\n};\n","import { Action } from '@bigcommerce/data-store';\n\nimport { LoadPaymentMethodAction } from '../payment';\n\nimport { CheckoutButtonMethodType } from './strategies';\n\nexport enum CheckoutButtonActionType {\n InitializeButtonFailed = 'INITIALIZE_BUTTON_FAILED',\n InitializeButtonRequested = 'INITIALIZE_BUTTON_REQUESTED',\n InitializeButtonSucceeded = 'INITIALIZE_BUTTON_SUCCEEDED',\n\n DeinitializeButtonFailed = 'DEINITIALIZE_BUTTON_FAILED',\n DeinitializeButtonRequested = 'DEINITIALIZE_BUTTON_REQUESTED',\n DeinitializeButtonSucceeded = 'DEINITIALIZE_BUTTON_SUCCEEDED',\n}\n\nexport type CheckoutButtonAction = InitializeButtonAction | DeinitializeButtonAction;\n\nexport type InitializeButtonAction =\n | InitializeButtonRequestedAction\n | InitializeButtonSucceededAction\n | InitializeButtonFailedAction\n | LoadPaymentMethodAction;\n\nexport type DeinitializeButtonAction =\n | DeinitializeButtonRequestedAction\n | DeinitializeButtonSucceededAction\n | DeinitializeButtonFailedAction;\n\nexport interface CheckoutButtonActionMeta {\n methodId: CheckoutButtonMethodType;\n}\n\nexport interface InitializeButtonActionMeta extends CheckoutButtonActionMeta {\n containerId: string;\n}\n\nexport interface InitializeButtonRequestedAction\n extends Action {\n type: CheckoutButtonActionType.InitializeButtonRequested;\n}\n\nexport interface InitializeButtonSucceededAction\n extends Action {\n type: CheckoutButtonActionType.InitializeButtonSucceeded;\n}\n\nexport interface InitializeButtonFailedAction extends Action {\n type: CheckoutButtonActionType.InitializeButtonFailed;\n}\n\nexport interface DeinitializeButtonRequestedAction\n extends Action {\n type: CheckoutButtonActionType.DeinitializeButtonRequested;\n}\n\nexport interface DeinitializeButtonSucceededAction\n extends Action {\n type: CheckoutButtonActionType.DeinitializeButtonSucceeded;\n}\n\nexport interface DeinitializeButtonFailedAction extends Action {\n type: CheckoutButtonActionType.DeinitializeButtonFailed;\n}\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { BillingAddressAction, BillingAddressActionType } from '../billing';\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\nimport {\n CouponAction,\n CouponActionType,\n GiftCertificateAction,\n GiftCertificateActionType,\n} from '../coupon';\nimport { ConsignmentAction, ConsignmentActionType } from '../shipping';\n\nimport Cart from './cart';\nimport CartState, { CartErrorsState, CartStatusesState, DEFAULT_STATE } from './cart-state';\n\nexport default function cartReducer(state: CartState = DEFAULT_STATE, action: Action): CartState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: Cart | undefined,\n action:\n | BillingAddressAction\n | CheckoutAction\n | ConsignmentAction\n | CouponAction\n | GiftCertificateAction,\n): Cart | undefined {\n switch (action.type) {\n case BillingAddressActionType.UpdateBillingAddressSucceeded:\n case CheckoutActionType.LoadCheckoutSucceeded:\n case ConsignmentActionType.CreateConsignmentsSucceeded:\n case ConsignmentActionType.DeleteConsignmentSucceeded:\n case ConsignmentActionType.UpdateConsignmentSucceeded:\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n case ConsignmentActionType.LoadShippingOptionsSucceeded:\n case CouponActionType.ApplyCouponSucceeded:\n case CouponActionType.RemoveCouponSucceeded:\n case GiftCertificateActionType.ApplyGiftCertificateSucceeded:\n case GiftCertificateActionType.RemoveGiftCertificateSucceeded:\n return objectMerge(data, action.payload && action.payload.cart);\n\n default:\n return data;\n }\n}\n\nfunction statusesReducer(\n statuses: CartStatusesState = DEFAULT_STATE.statuses,\n action: CheckoutAction,\n): CartStatusesState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case CheckoutActionType.LoadCheckoutFailed:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n\nfunction errorsReducer(\n errors: CartErrorsState = DEFAULT_STATE.errors,\n action: CheckoutAction,\n): CartErrorsState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case CheckoutActionType.LoadCheckoutFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n","import { CheckoutButtonMethodType } from './strategies';\n\nexport default interface CheckoutButtonState {\n data: {\n [key in CheckoutButtonMethodType]?: CheckoutButtonDataState | undefined;\n };\n errors: {\n [key in CheckoutButtonMethodType]?: CheckoutButtonErrorsState | undefined;\n };\n statuses: {\n [key in CheckoutButtonMethodType]?: CheckoutButtonStatusesState | undefined;\n };\n}\n\nexport interface CheckoutButtonDataState {\n initializedContainers: {\n [key: string]: boolean;\n };\n}\n\nexport interface CheckoutButtonErrorsState {\n initializeError?: Error;\n deinitializeError?: Error;\n}\n\nexport interface CheckoutButtonStatusesState {\n isInitializing?: boolean;\n isDeinitializing?: boolean;\n}\n\nexport const DEFAULT_STATE: CheckoutButtonState = {\n data: {},\n errors: {},\n statuses: {},\n};\n","import { combineReducers } from '@bigcommerce/data-store';\n\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport { CheckoutButtonAction, CheckoutButtonActionType } from './checkout-button-actions';\nimport CheckoutButtonState, {\n CheckoutButtonDataState,\n CheckoutButtonErrorsState,\n CheckoutButtonStatusesState,\n DEFAULT_STATE,\n} from './checkout-button-state';\n\nconst DEFAULT_DATA_STATE: CheckoutButtonDataState = { initializedContainers: {} };\nconst DEFAULT_ERROR_STATE: CheckoutButtonErrorsState = {};\nconst DEFAULT_STATUS_STATE: CheckoutButtonStatusesState = {};\n\nexport default function checkoutButtonReducer(\n state: CheckoutButtonState = DEFAULT_STATE,\n action: CheckoutButtonAction,\n): CheckoutButtonState {\n if (!action.meta || !action.meta.methodId) {\n return state;\n }\n\n const reducer = combineReducers({\n data: combineReducers({\n [action.meta.methodId]: dataReducer,\n }),\n errors: combineReducers({\n [action.meta.methodId]: errorsReducer,\n }),\n statuses: combineReducers({\n [action.meta.methodId]: statusesReducer,\n }),\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: CheckoutButtonDataState = DEFAULT_DATA_STATE,\n action: CheckoutButtonAction,\n): CheckoutButtonDataState {\n switch (action.type) {\n case CheckoutButtonActionType.InitializeButtonSucceeded:\n if (!action.meta || !action.meta.containerId) {\n return data;\n }\n\n return objectMerge(data, {\n initializedContainers: {\n [action.meta.containerId]: true,\n },\n });\n\n case CheckoutButtonActionType.DeinitializeButtonSucceeded:\n return objectSet(data, 'initializedContainers', {});\n }\n\n return data;\n}\n\nfunction errorsReducer(\n errors: CheckoutButtonErrorsState = DEFAULT_ERROR_STATE,\n action: CheckoutButtonAction,\n): CheckoutButtonErrorsState {\n switch (action.type) {\n case CheckoutButtonActionType.InitializeButtonRequested:\n case CheckoutButtonActionType.InitializeButtonSucceeded:\n return objectSet(errors, 'initializeError', undefined);\n\n case CheckoutButtonActionType.InitializeButtonFailed:\n return objectSet(errors, 'initializeError', action.payload);\n\n case CheckoutButtonActionType.DeinitializeButtonRequested:\n case CheckoutButtonActionType.DeinitializeButtonSucceeded:\n return objectSet(errors, 'deinitializeError', undefined);\n\n case CheckoutButtonActionType.DeinitializeButtonFailed:\n return objectSet(errors, 'deinitializeError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: CheckoutButtonStatusesState = DEFAULT_STATUS_STATE,\n action: CheckoutButtonAction,\n): CheckoutButtonStatusesState {\n switch (action.type) {\n case CheckoutButtonActionType.InitializeButtonRequested:\n return objectSet(statuses, 'isInitializing', true);\n\n case CheckoutButtonActionType.InitializeButtonFailed:\n case CheckoutButtonActionType.InitializeButtonSucceeded:\n return objectSet(statuses, 'isInitializing', false);\n\n case CheckoutButtonActionType.DeinitializeButtonRequested:\n return objectSet(statuses, 'isDeinitializing', true);\n\n case CheckoutButtonActionType.DeinitializeButtonFailed:\n case CheckoutButtonActionType.DeinitializeButtonSucceeded:\n return objectSet(statuses, 'isDeinitializing', false);\n\n default:\n return statuses;\n }\n}\n","import Config from './config';\n\nexport default interface ConfigState {\n data?: Config;\n meta?: ConfigMetaState;\n errors: ConfigErrorsState;\n statuses: ConfigStatusesState;\n}\n\nexport interface ConfigMetaState {\n externalSource?: string;\n variantIdentificationToken?: string;\n host?: string;\n locale?: string;\n}\n\nexport interface ConfigErrorsState {\n loadError?: Error;\n}\n\nexport interface ConfigStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: ConfigState = {\n meta: {},\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport Config from './config';\nimport { ConfigActionType, LoadConfigAction } from './config-actions';\nimport ConfigState, { ConfigErrorsState, ConfigStatusesState, DEFAULT_STATE } from './config-state';\n\nexport default function configReducer(\n state: ConfigState = DEFAULT_STATE,\n action: Action,\n): ConfigState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(data: Config | undefined, action: LoadConfigAction): Config | undefined {\n switch (action.type) {\n case ConfigActionType.LoadConfigSucceeded:\n return objectMerge(data, action.payload);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: ConfigErrorsState = DEFAULT_STATE.errors,\n action: LoadConfigAction,\n): ConfigErrorsState {\n switch (action.type) {\n case ConfigActionType.LoadConfigSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case ConfigActionType.LoadConfigFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: ConfigStatusesState = DEFAULT_STATE.statuses,\n action: LoadConfigAction,\n): ConfigStatusesState {\n switch (action.type) {\n case ConfigActionType.LoadConfigRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case ConfigActionType.LoadConfigSucceeded:\n case ConfigActionType.LoadConfigFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","import { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RequestError } from '../common/error/errors';\n\nimport Coupon from './coupon';\n\nexport default interface CouponState {\n data?: Coupon[];\n errors: CouponErrorsState;\n statuses: CouponStatusesState;\n}\n\nexport interface CouponErrorsState {\n applyCouponError?: RequestError;\n removeCouponError?: RequestError;\n}\n\nexport interface CouponStatusesState {\n isApplyingCoupon?: boolean;\n isRemovingCoupon?: boolean;\n}\n\nexport const DEFAULT_STATE: CouponState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectSet } from '../common/utility';\nimport { OrderAction, OrderActionType } from '../order';\nimport { ConsignmentAction, ConsignmentActionType } from '../shipping';\n\nimport Coupon from './coupon';\nimport { CouponAction, CouponActionType } from './coupon-actions';\nimport CouponState, { CouponErrorsState, CouponStatusesState, DEFAULT_STATE } from './coupon-state';\n\nexport default function couponReducer(\n state: CouponState = DEFAULT_STATE,\n action: Action,\n): CouponState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: Coupon[] | undefined,\n action: CouponAction | CheckoutAction | OrderAction | ConsignmentAction,\n): Coupon[] | undefined {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutSucceeded:\n case CouponActionType.ApplyCouponSucceeded:\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n case CouponActionType.RemoveCouponSucceeded:\n case OrderActionType.LoadOrderSucceeded:\n return arrayReplace(data, action.payload && action.payload.coupons);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(errors: CouponErrorsState = {}, action: CouponAction): CouponErrorsState {\n switch (action.type) {\n case CouponActionType.ApplyCouponRequested:\n case CouponActionType.ApplyCouponSucceeded:\n return objectSet(errors, 'applyCouponError', undefined);\n\n case CouponActionType.ApplyCouponFailed:\n return objectSet(errors, 'applyCouponError', action.payload);\n\n case CouponActionType.RemoveCouponRequested:\n case CouponActionType.RemoveCouponSucceeded:\n return objectSet(errors, 'removeCouponError', undefined);\n\n case CouponActionType.RemoveCouponFailed:\n return objectSet(errors, 'removeCouponError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: CouponStatusesState = {},\n action: CouponAction,\n): CouponStatusesState {\n switch (action.type) {\n case CouponActionType.ApplyCouponRequested:\n return objectSet(statuses, 'isApplyingCoupon', true);\n\n case CouponActionType.ApplyCouponSucceeded:\n case CouponActionType.ApplyCouponFailed:\n return objectSet(statuses, 'isApplyingCoupon', false);\n\n case CouponActionType.RemoveCouponRequested:\n return objectSet(statuses, 'isRemovingCoupon', true);\n\n case CouponActionType.RemoveCouponSucceeded:\n case CouponActionType.RemoveCouponFailed:\n return objectSet(statuses, 'isRemovingCoupon', false);\n\n default:\n return statuses;\n }\n}\n","import { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RequestError } from '../common/error/errors';\n\nimport GiftCertificate from './gift-certificate';\n\nexport default interface GiftCertificateState {\n data?: GiftCertificate[];\n errors: GiftCertificateErrorsState;\n statuses: GiftCertificateStatusesState;\n}\n\nexport interface GiftCertificateErrorsState {\n applyGiftCertificateError?: RequestError;\n removeGiftCertificateError?: RequestError;\n}\n\nexport interface GiftCertificateStatusesState {\n isApplyingGiftCertificate?: boolean;\n isRemovingGiftCertificate?: boolean;\n}\n\nexport const DEFAULT_STATE: GiftCertificateState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectSet } from '../common/utility';\nimport { ConsignmentAction, ConsignmentActionType } from '../shipping';\n\nimport { CouponAction, CouponActionType } from './coupon-actions';\nimport GiftCertificate from './gift-certificate';\nimport { GiftCertificateAction, GiftCertificateActionType } from './gift-certificate-actions';\nimport GiftCertificateState, {\n DEFAULT_STATE,\n GiftCertificateErrorsState,\n GiftCertificateStatusesState,\n} from './gift-certificate-state';\n\nexport default function giftCertificateReducer(\n state: GiftCertificateState = DEFAULT_STATE,\n action: Action,\n): GiftCertificateState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: GiftCertificate[] | undefined,\n action: CheckoutAction | GiftCertificateAction | ConsignmentAction | CouponAction,\n): GiftCertificate[] | undefined {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutSucceeded:\n case ConsignmentActionType.CreateConsignmentsSucceeded:\n case ConsignmentActionType.UpdateConsignmentSucceeded:\n case ConsignmentActionType.DeleteConsignmentSucceeded:\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n case CouponActionType.ApplyCouponSucceeded:\n case CouponActionType.RemoveCouponSucceeded:\n case GiftCertificateActionType.ApplyGiftCertificateSucceeded:\n case GiftCertificateActionType.RemoveGiftCertificateSucceeded:\n return arrayReplace(data, action.payload && action.payload.giftCertificates);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: GiftCertificateErrorsState = DEFAULT_STATE.errors,\n action: GiftCertificateAction,\n): GiftCertificateErrorsState {\n switch (action.type) {\n case GiftCertificateActionType.ApplyGiftCertificateRequested:\n case GiftCertificateActionType.ApplyGiftCertificateSucceeded:\n return objectSet(errors, 'applyGiftCertificateError', undefined);\n\n case GiftCertificateActionType.ApplyGiftCertificateFailed:\n return objectSet(errors, 'applyGiftCertificateError', action.payload);\n\n case GiftCertificateActionType.RemoveGiftCertificateRequested:\n case GiftCertificateActionType.RemoveGiftCertificateSucceeded:\n return objectSet(errors, 'removeGiftCertificateError', undefined);\n\n case GiftCertificateActionType.RemoveGiftCertificateFailed:\n return objectSet(errors, 'removeGiftCertificateError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: GiftCertificateStatusesState = DEFAULT_STATE.statuses,\n action: GiftCertificateAction,\n): GiftCertificateStatusesState {\n switch (action.type) {\n case GiftCertificateActionType.ApplyGiftCertificateRequested:\n return objectSet(statuses, 'isApplyingGiftCertificate', true);\n\n case GiftCertificateActionType.ApplyGiftCertificateSucceeded:\n case GiftCertificateActionType.ApplyGiftCertificateFailed:\n return objectSet(statuses, 'isApplyingGiftCertificate', false);\n\n case GiftCertificateActionType.RemoveGiftCertificateRequested:\n return objectSet(statuses, 'isRemovingGiftCertificate', true);\n\n case GiftCertificateActionType.RemoveGiftCertificateSucceeded:\n case GiftCertificateActionType.RemoveGiftCertificateFailed:\n return objectSet(statuses, 'isRemovingGiftCertificate', false);\n\n default:\n return statuses;\n }\n}\n","import Customer from './customer';\n\nexport default interface CustomerState {\n data?: Customer;\n statuses: CustomerStatusesState;\n errors: CustomerErrorsState;\n}\n\nexport interface CustomerErrorsState {\n createError?: Error;\n createAddressError?: Error;\n}\n\nexport interface CustomerStatusesState {\n isCreating?: boolean;\n isCreatingAddress?: boolean;\n}\n\nexport const DEFAULT_STATE: CustomerState = {\n errors: {},\n statuses: {},\n};\n","import { combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { BillingAddressActionType, ContinueAsGuestAction } from '../billing';\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport Customer from './customer';\nimport {\n CustomerAction,\n CustomerActionType,\n StripeLinkAuthenticatedAction,\n} from './customer-actions';\nimport CustomerState, {\n CustomerErrorsState,\n CustomerStatusesState,\n DEFAULT_STATE,\n} from './customer-state';\n\ntype ReducerActionType =\n | CheckoutAction\n | ContinueAsGuestAction\n | CustomerAction\n | StripeLinkAuthenticatedAction;\n\nexport default function customerReducer(\n state: CustomerState = DEFAULT_STATE,\n action: ReducerActionType,\n): CustomerState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(data: Customer | undefined, action: ReducerActionType): Customer | undefined {\n switch (action.type) {\n case BillingAddressActionType.ContinueAsGuestSucceeded:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return objectMerge(data, action.payload && action.payload.customer);\n\n case CustomerActionType.CreateCustomerAddressSucceeded:\n return objectMerge(data, action.payload);\n\n case CustomerActionType.StripeLinkAuthenticated:\n return objectSet(data, 'isStripeLinkAuthenticated', action.payload);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: CustomerErrorsState = DEFAULT_STATE.errors,\n action: ReducerActionType,\n): CustomerErrorsState {\n switch (action.type) {\n case CustomerActionType.CreateCustomerRequested:\n case CustomerActionType.CreateCustomerSucceeded:\n return objectSet(errors, 'createError', undefined);\n\n case CustomerActionType.CreateCustomerFailed:\n return objectSet(errors, 'createError', action.payload);\n\n case CustomerActionType.CreateCustomerAddressRequested:\n case CustomerActionType.CreateCustomerAddressSucceeded:\n return objectSet(errors, 'createAddressError', undefined);\n\n case CustomerActionType.CreateCustomerAddressFailed:\n return objectSet(errors, 'createAddressError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: CustomerStatusesState = DEFAULT_STATE.statuses,\n action: ReducerActionType,\n): CustomerStatusesState {\n switch (action.type) {\n case CustomerActionType.CreateCustomerRequested:\n return objectSet(statuses, 'isCreating', true);\n\n case CustomerActionType.CreateCustomerFailed:\n case CustomerActionType.CreateCustomerSucceeded:\n return objectSet(statuses, 'isCreating', false);\n\n case CustomerActionType.CreateCustomerAddressRequested:\n return objectSet(statuses, 'isCreatingAddress', true);\n\n case CustomerActionType.CreateCustomerAddressFailed:\n case CustomerActionType.CreateCustomerAddressSucceeded:\n return objectSet(statuses, 'isCreatingAddress', false);\n\n default:\n return statuses;\n }\n}\n","export default interface CustomerStrategyState {\n data: CustomerStrategyDataState;\n errors: CustomerStrategyErrorsState;\n statuses: CustomerStrategyStatusesState;\n}\n\nexport interface CustomerStrategyDataState {\n [key: string]: {\n isInitialized: boolean;\n };\n}\n\nexport interface CustomerStrategyErrorsState {\n deinitializeError?: Error;\n deinitializeMethodId?: string;\n initializeErrors?: { [key: string]: Error };\n initializeMethodId?: string;\n signInError?: Error;\n signInMethodId?: string;\n signOutError?: Error;\n signOutMethodId?: string;\n executePaymentMethodCheckoutError?: Error;\n executePaymentMethodCheckoutMethodId?: string;\n widgetInteractionError?: Error;\n widgetInteractionMethodId?: string;\n}\n\nexport interface CustomerStrategyStatusesState {\n deinitializeMethodId?: string;\n initializeMethodId?: string;\n isDeinitializing?: boolean;\n isInitializing?: boolean;\n isSigningIn?: boolean;\n isSigningOut?: boolean;\n signInMethodId?: string;\n signOutMethodId?: string;\n isExecutingPaymentMethodCheckout?: boolean;\n executePaymentMethodCheckoutMethodId?: string;\n isWidgetInteracting?: boolean;\n widgetInteractionMethodId?: string;\n}\n\nexport const DEFAULT_STATE: CustomerStrategyState = {\n data: {},\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge } from '../common/utility';\n\nimport { CustomerStrategyAction, CustomerStrategyActionType } from './customer-strategy-actions';\nimport CustomerStrategyState, {\n CustomerStrategyDataState,\n CustomerStrategyErrorsState,\n CustomerStrategyStatusesState,\n DEFAULT_STATE,\n} from './customer-strategy-state';\n\nexport default function customerStrategyReducer(\n state: CustomerStrategyState = DEFAULT_STATE,\n action: Action,\n): CustomerStrategyState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: CustomerStrategyDataState = DEFAULT_STATE.data,\n action: CustomerStrategyAction,\n): CustomerStrategyDataState {\n switch (action.type) {\n case CustomerStrategyActionType.InitializeSucceeded:\n return objectMerge(data, {\n [action.meta && action.meta.methodId]: {\n isInitialized: true,\n },\n });\n\n case CustomerStrategyActionType.DeinitializeSucceeded:\n return objectMerge(data, {\n [action.meta && action.meta.methodId]: {\n isInitialized: false,\n },\n });\n }\n\n return data;\n}\n\nfunction errorsReducer(\n errors: CustomerStrategyErrorsState = DEFAULT_STATE.errors,\n action: CustomerStrategyAction,\n): CustomerStrategyErrorsState {\n switch (action.type) {\n case CustomerStrategyActionType.InitializeRequested:\n case CustomerStrategyActionType.InitializeSucceeded:\n return objectMerge(errors, {\n initializeErrors: { ...errors.initializeErrors },\n initializeMethodId: errors.initializeMethodId\n ? errors.initializeMethodId\n : undefined,\n });\n\n case CustomerStrategyActionType.InitializeFailed:\n return objectMerge(errors, {\n initializeErrors: {\n ...errors.initializeErrors,\n [action.meta && action.meta.methodId]: action.payload,\n },\n initializeMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.DeinitializeRequested:\n case CustomerStrategyActionType.DeinitializeSucceeded:\n return objectMerge(errors, {\n deinitializeError: undefined,\n deinitializeMethodId: undefined,\n });\n\n case CustomerStrategyActionType.DeinitializeFailed:\n return objectMerge(errors, {\n deinitializeError: action.payload,\n deinitializeMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.SignInRequested:\n case CustomerStrategyActionType.SignInSucceeded:\n return objectMerge(errors, {\n signInError: undefined,\n signInMethodId: undefined,\n });\n\n case CustomerStrategyActionType.SignInFailed:\n return objectMerge(errors, {\n signInError: action.payload,\n signInMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.SignOutRequested:\n case CustomerStrategyActionType.SignOutSucceeded:\n return objectMerge(errors, {\n signOutError: undefined,\n signOutMethodId: undefined,\n });\n\n case CustomerStrategyActionType.SignOutFailed:\n return objectMerge(errors, {\n signOutError: action.payload,\n signOutMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.ExecutePaymentMethodCheckoutRequested:\n case CustomerStrategyActionType.ExecutePaymentMethodCheckoutSucceeded:\n return objectMerge(errors, {\n executePaymentMethodCheckoutError: undefined,\n executePaymentMethodCheckoutMethodId: undefined,\n });\n\n case CustomerStrategyActionType.ExecutePaymentMethodCheckoutFailed:\n return objectMerge(errors, {\n executePaymentMethodCheckoutError: action.payload,\n executePaymentMethodCheckoutMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.WidgetInteractionStarted:\n case CustomerStrategyActionType.WidgetInteractionFinished:\n return objectMerge(errors, {\n widgetInteractionError: undefined,\n widgetInteractionMethodId: undefined,\n });\n\n case CustomerStrategyActionType.WidgetInteractionFailed:\n return objectMerge(errors, {\n widgetInteractionError: action.payload,\n widgetInteractionMethodId: action.meta.methodId,\n });\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: CustomerStrategyStatusesState = DEFAULT_STATE.statuses,\n action: CustomerStrategyAction,\n): CustomerStrategyStatusesState {\n switch (action.type) {\n case CustomerStrategyActionType.InitializeRequested:\n return objectMerge(statuses, {\n isInitializing: true,\n initializeMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.InitializeFailed:\n case CustomerStrategyActionType.InitializeSucceeded:\n return objectMerge(statuses, {\n isInitializing: false,\n initializeMethodId: undefined,\n });\n\n case CustomerStrategyActionType.DeinitializeRequested:\n return objectMerge(statuses, {\n isDeinitializing: true,\n deinitializeMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.DeinitializeFailed:\n case CustomerStrategyActionType.DeinitializeSucceeded:\n return objectMerge(statuses, {\n isDeinitializing: false,\n deinitializeMethodId: undefined,\n });\n\n case CustomerStrategyActionType.SignInRequested:\n return objectMerge(statuses, {\n isSigningIn: true,\n signInMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.SignInFailed:\n case CustomerStrategyActionType.SignInSucceeded:\n return objectMerge(statuses, {\n isSigningIn: false,\n signInMethodId: undefined,\n });\n\n case CustomerStrategyActionType.SignOutRequested:\n return objectMerge(statuses, {\n isSigningOut: true,\n signOutMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.SignOutFailed:\n case CustomerStrategyActionType.SignOutSucceeded:\n return objectMerge(statuses, {\n isSigningOut: false,\n signOutMethodId: undefined,\n });\n\n case CustomerStrategyActionType.ExecutePaymentMethodCheckoutRequested:\n return objectMerge(statuses, {\n isExecutingPaymentMethodCheckout: true,\n executePaymentMethodCheckoutMethodId: action.meta && action.meta.methodId,\n });\n\n case CustomerStrategyActionType.ExecutePaymentMethodCheckoutFailed:\n case CustomerStrategyActionType.ExecutePaymentMethodCheckoutSucceeded:\n return objectMerge(statuses, {\n isExecutingPaymentMethodCheckout: false,\n executePaymentMethodCheckoutMethodId: undefined,\n });\n\n case CustomerStrategyActionType.WidgetInteractionStarted:\n return objectMerge(statuses, {\n isWidgetInteracting: true,\n widgetInteractionMethodId: action.meta.methodId,\n });\n\n case CustomerStrategyActionType.WidgetInteractionFinished:\n case CustomerStrategyActionType.WidgetInteractionFailed:\n return objectMerge(statuses, {\n isWidgetInteracting: false,\n widgetInteractionMethodId: undefined,\n });\n\n default:\n return statuses;\n }\n}\n","import { Extension } from './extension';\n\nexport interface ExtensionState {\n data?: Extension[];\n errors: ExtensionErrorsState;\n statuses: ExtensionStatusesState;\n}\n\nexport interface ExtensionErrorsState {\n loadError?: Error;\n}\n\nexport interface ExtensionStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: ExtensionState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectSet } from '../common/utility';\n\nimport { Extension } from './extension';\nimport { ExtensionAction, ExtensionActionType } from './extension-actions';\nimport {\n DEFAULT_STATE,\n ExtensionErrorsState,\n ExtensionState,\n ExtensionStatusesState,\n} from './extension-state';\n\nexport function extensionReducer(\n state: ExtensionState = DEFAULT_STATE,\n action: Action,\n): ExtensionState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: Extension[] | undefined,\n action: ExtensionAction,\n): Extension[] | undefined {\n if (action.type === ExtensionActionType.LoadExtensionsSucceeded) {\n return arrayReplace(data, action.payload);\n }\n\n return data;\n}\n\nfunction errorsReducer(\n errors: ExtensionErrorsState = DEFAULT_STATE.errors,\n action: ExtensionAction,\n): ExtensionErrorsState {\n switch (action.type) {\n case ExtensionActionType.LoadExtensionsRequested:\n case ExtensionActionType.LoadExtensionsSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case ExtensionActionType.LoadExtensionsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: ExtensionStatusesState = DEFAULT_STATE.statuses,\n action: ExtensionAction,\n): ExtensionStatusesState {\n switch (action.type) {\n case ExtensionActionType.LoadExtensionsRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case ExtensionActionType.LoadExtensionsSucceeded:\n case ExtensionActionType.LoadExtensionsFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","import { FormFields } from './form-field';\n\nexport default interface FormFieldsState {\n data?: FormFields;\n errors: FormFieldsErrorState;\n statuses: FormFieldsStatusesState;\n}\n\nexport interface FormFieldsErrorState {\n loadError?: Error;\n}\n\nexport interface FormFieldsStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: FormFieldsState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport { FormFields } from './form-field';\nimport { FormFieldsActionType, LoadFormFieldsAction } from './form-fields-actions';\nimport FormFieldsState, {\n DEFAULT_STATE,\n FormFieldsErrorState,\n FormFieldsStatusesState,\n} from './form-fields-state';\n\nexport default function formFieldsReducer(\n state: FormFieldsState = DEFAULT_STATE,\n action: Action,\n): FormFieldsState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: FormFields | undefined,\n action: LoadFormFieldsAction,\n): FormFields | undefined {\n switch (action.type) {\n case FormFieldsActionType.LoadFormFieldsSucceeded:\n return objectMerge(data, action.payload);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: FormFieldsErrorState = DEFAULT_STATE.errors,\n action: LoadFormFieldsAction,\n): FormFieldsErrorState {\n switch (action.type) {\n case FormFieldsActionType.LoadFormFieldsSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case FormFieldsActionType.LoadFormFieldsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: FormFieldsStatusesState = DEFAULT_STATE.statuses,\n action: LoadFormFieldsAction,\n): FormFieldsStatusesState {\n switch (action.type) {\n case FormFieldsActionType.LoadFormFieldsRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case FormFieldsActionType.LoadFormFieldsSucceeded:\n case FormFieldsActionType.LoadFormFieldsFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","import Country from './country';\n\nexport default interface CountryState {\n data?: Country[];\n errors: CountryErrorsState;\n statuses: CountryStatusesState;\n}\n\nexport interface CountryErrorsState {\n loadError?: Error;\n}\n\nexport interface CountryStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: CountryState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectSet } from '../common/utility';\n\nimport Country from './country';\nimport { CountryActionType, LoadCountriesAction } from './country-actions';\nimport CountryState, {\n CountryErrorsState,\n CountryStatusesState,\n DEFAULT_STATE,\n} from './country-state';\n\nexport default function countryReducer(\n state: CountryState = DEFAULT_STATE,\n action: Action,\n): CountryState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: Country[] | undefined,\n action: LoadCountriesAction,\n): Country[] | undefined {\n switch (action.type) {\n case CountryActionType.LoadCountriesSucceeded:\n return arrayReplace(data, action.payload);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: CountryErrorsState = DEFAULT_STATE.errors,\n action: LoadCountriesAction,\n): CountryErrorsState {\n switch (action.type) {\n case CountryActionType.LoadCountriesRequested:\n case CountryActionType.LoadCountriesSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case CountryActionType.LoadCountriesFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: CountryStatusesState = DEFAULT_STATE.statuses,\n action: LoadCountriesAction,\n): CountryStatusesState {\n switch (action.type) {\n case CountryActionType.LoadCountriesRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case CountryActionType.LoadCountriesSucceeded:\n case CountryActionType.LoadCountriesFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","import { Omit } from '../common/types';\n\nimport { InternalOrderMeta, InternalOrderPayment } from './internal-order';\nimport Order from './order';\n\nexport default interface OrderState {\n data?: OrderDataState;\n meta?: OrderMetaState;\n errors: OrderErrorsState;\n statuses: OrderStatusesState;\n}\n\nexport type OrderDataState = Omit;\n\nexport interface OrderMetaState extends InternalOrderMeta {\n token?: string;\n orderToken?: string;\n callbackUrl?: string;\n payment?: InternalOrderPayment;\n}\n\nexport interface OrderErrorsState {\n loadError?: Error;\n submitError?: Error;\n finalizeError?: Error;\n}\n\nexport interface OrderStatusesState {\n isLoading?: boolean;\n isSubmitting?: boolean;\n isFinalizing?: boolean;\n}\n\nexport const DEFAULT_STATE: OrderState = {\n errors: {},\n meta: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\nimport { omit } from 'lodash';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport { OrderAction, OrderActionType } from './order-actions';\nimport OrderState, {\n DEFAULT_STATE,\n OrderDataState,\n OrderErrorsState,\n OrderMetaState,\n OrderStatusesState,\n} from './order-state';\n\nexport default function orderReducer(\n state: OrderState = DEFAULT_STATE,\n action: Action,\n): OrderState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n meta: metaReducer,\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: OrderDataState | undefined,\n action: OrderAction,\n): OrderDataState | undefined {\n switch (action.type) {\n case OrderActionType.LoadOrderSucceeded:\n case OrderActionType.LoadOrderPaymentsSucceeded:\n return objectMerge(\n data,\n omit(action.payload, ['billingAddress', 'coupons']),\n ) as OrderDataState;\n\n default:\n return data;\n }\n}\n\nfunction metaReducer(\n meta: OrderMetaState | undefined,\n action: OrderAction,\n): OrderMetaState | undefined {\n switch (action.type) {\n case OrderActionType.FinalizeOrderSucceeded:\n case OrderActionType.SubmitOrderSucceeded:\n return objectMerge(meta, {\n ...action.meta,\n callbackUrl: action.payload && action.payload.order.callbackUrl,\n orderToken: action.payload && action.payload.order.token,\n payment: action.payload && action.payload.order && action.payload.order.payment,\n });\n\n default:\n return meta;\n }\n}\n\nfunction errorsReducer(\n errors: OrderErrorsState = DEFAULT_STATE.errors,\n action: OrderAction,\n): OrderErrorsState {\n switch (action.type) {\n case OrderActionType.LoadOrderRequested:\n case OrderActionType.LoadOrderSucceeded:\n case OrderActionType.LoadOrderPaymentsSucceeded:\n case OrderActionType.LoadOrderPaymentsRequested:\n return objectSet(errors, 'loadError', undefined);\n\n case OrderActionType.LoadOrderFailed:\n case OrderActionType.LoadOrderPaymentsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: OrderStatusesState = DEFAULT_STATE.statuses,\n action: OrderAction,\n): OrderStatusesState {\n switch (action.type) {\n case OrderActionType.LoadOrderRequested:\n case OrderActionType.LoadOrderPaymentsRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case OrderActionType.LoadOrderSucceeded:\n case OrderActionType.LoadOrderFailed:\n case OrderActionType.LoadOrderPaymentsSucceeded:\n case OrderActionType.LoadOrderPaymentsFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","import { Address } from '../address';\n\nexport interface OrderBillingAddress extends Address {\n email?: string;\n}\n\nexport default interface OrderBillingAddressState {\n data?: OrderBillingAddress;\n}\n\nexport const DEFAULT_STATE: OrderBillingAddressState = {};\n","import { Action, combineReducers } from '@bigcommerce/data-store';\n\nimport { replace } from '../common/utility';\nimport { OrderAction, OrderActionType } from '../order';\n\nimport OrderBillingAddressState, {\n DEFAULT_STATE,\n OrderBillingAddress,\n} from './order-billing-address-state';\n\nexport default function orderBillingAddressReducer(\n state: OrderBillingAddressState = DEFAULT_STATE,\n action: Action,\n): OrderBillingAddressState {\n const reducer = combineReducers({\n data: dataReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: OrderBillingAddress | undefined,\n action: OrderAction,\n): OrderBillingAddress | undefined {\n switch (action.type) {\n case OrderActionType.LoadOrderPaymentsSucceeded:\n case OrderActionType.LoadOrderSucceeded:\n return replace(data, action.payload && action.payload.billingAddress);\n\n default:\n return data;\n }\n}\n","import { combineReducers } from '@bigcommerce/data-store';\n\nimport { PaymentAction, PaymentActionType } from './payment-actions';\nimport PaymentResponseBody from './payment-response-body';\nimport PaymentState from './payment-state';\n\nexport default function paymentReducer(\n state: PaymentState = {},\n action: PaymentAction,\n): PaymentState {\n const reducer = combineReducers({\n data: dataReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: PaymentResponseBody | undefined,\n action: PaymentAction,\n): PaymentResponseBody | undefined {\n switch (action.type) {\n case PaymentActionType.SubmitPaymentSucceeded:\n return action.payload;\n\n default:\n return data;\n }\n}\n","import PaymentMethod from './payment-method';\nimport PaymentMethodMeta from './payment-method-meta';\n\nexport default interface PaymentMethodState {\n data?: PaymentMethod[];\n meta?: PaymentMethodMeta;\n errors: PaymentMethodErrorsState;\n statuses: PaymentMethodStatusesState;\n}\n\nexport interface PaymentMethodErrorsState {\n loadMethodId?: string;\n loadError?: Error;\n loadMethodError?: Error;\n}\n\nexport interface PaymentMethodStatusesState {\n loadMethodId?: string;\n isLoading?: boolean;\n isLoadingMethod?: boolean;\n}\n\nexport const DEFAULT_STATE: PaymentMethodState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, mergeOrPush, objectMerge, objectSet } from '../common/utility';\n\nimport PaymentMethod from './payment-method';\nimport { PaymentMethodAction, PaymentMethodActionType } from './payment-method-actions';\nimport PaymentMethodMeta from './payment-method-meta';\nimport PaymentMethodState, {\n DEFAULT_STATE,\n PaymentMethodErrorsState,\n PaymentMethodStatusesState,\n} from './payment-method-state';\n\nexport default function paymentMethodReducer(\n state: PaymentMethodState = DEFAULT_STATE,\n action: Action,\n): PaymentMethodState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n meta: metaReducer,\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: PaymentMethod[] | undefined,\n action: PaymentMethodAction,\n): PaymentMethod[] | undefined {\n switch (action.type) {\n case PaymentMethodActionType.LoadPaymentMethodSucceeded:\n return mergeOrPush(\n data || [],\n action.payload,\n action.payload && {\n id: action.payload.id,\n gateway: action.payload.gateway,\n },\n );\n\n case PaymentMethodActionType.LoadPaymentMethodsSucceeded:\n return arrayReplace(data, action.payload, {\n matchObject: (methodA, methodB) =>\n methodA.id === methodB.id && methodA.gateway === methodB.gateway,\n });\n\n default:\n return data;\n }\n}\n\nfunction metaReducer(\n meta: PaymentMethodMeta | undefined,\n action: PaymentMethodAction,\n): PaymentMethodMeta | undefined {\n switch (action.type) {\n case PaymentMethodActionType.LoadPaymentMethodsSucceeded:\n return objectMerge(meta, action.meta);\n\n default:\n return meta;\n }\n}\n\nfunction errorsReducer(\n errors: PaymentMethodErrorsState = DEFAULT_STATE.errors,\n action: PaymentMethodAction,\n): PaymentMethodErrorsState {\n switch (action.type) {\n case PaymentMethodActionType.LoadPaymentMethodsRequested:\n case PaymentMethodActionType.LoadPaymentMethodsSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case PaymentMethodActionType.LoadPaymentMethodsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n case PaymentMethodActionType.LoadPaymentMethodRequested:\n case PaymentMethodActionType.LoadPaymentMethodSucceeded:\n return objectMerge(errors, {\n loadMethodId: undefined,\n loadMethodError: undefined,\n });\n\n case PaymentMethodActionType.LoadPaymentMethodFailed:\n return objectMerge(errors, {\n loadMethodId: action.meta.methodId,\n loadMethodError: action.payload,\n });\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: PaymentMethodStatusesState = DEFAULT_STATE.statuses,\n action: PaymentMethodAction,\n): PaymentMethodStatusesState {\n switch (action.type) {\n case PaymentMethodActionType.LoadPaymentMethodsRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case PaymentMethodActionType.LoadPaymentMethodsSucceeded:\n case PaymentMethodActionType.LoadPaymentMethodsFailed:\n return objectSet(statuses, 'isLoading', false);\n\n case PaymentMethodActionType.LoadPaymentMethodRequested:\n return objectMerge(statuses, {\n isLoadingMethod: true,\n loadMethodId: action.meta.methodId,\n });\n\n case PaymentMethodActionType.LoadPaymentMethodSucceeded:\n case PaymentMethodActionType.LoadPaymentMethodFailed:\n return objectMerge(statuses, {\n isLoadingMethod: false,\n loadMethodId: undefined,\n });\n\n default:\n return statuses;\n }\n}\n","import { findIndex, pick, pickBy, ValueKeyIteratee } from 'lodash';\n\nimport isPlainObject from './is-plain-object';\nimport objectMerge from './object-merge';\n\n/**\n * Push an item to an array if it doesn't exist in the array. Otherwise, merge\n * with the existing item in the array. This function always returns a new array.\n */\nexport default function mergeOrPush(array: T[], item?: T, predicate?: ValueKeyIteratee): T[] {\n if (!item) {\n return array;\n }\n\n const defaultPredicate = pick(item, 'id');\n const index = findIndex(\n array,\n typeof predicate === 'object' ? pickBy(predicate) : predicate || defaultPredicate,\n );\n const newArray = [...array];\n\n if (index === -1) {\n newArray.push(item);\n } else {\n const existingItem = array[index];\n\n newArray[index] =\n isPlainObject(existingItem) && isPlainObject(item)\n ? objectMerge(existingItem, item)\n : item;\n }\n\n return newArray;\n}\n","export default interface PaymentStrategyState {\n data: PaymentStrategyDataState;\n errors: PaymentStrategyErrorsState;\n statuses: PaymentStrategyStatusesState;\n}\n\nexport interface PaymentStrategyDataState {\n [key: string]: {\n isInitialized: boolean;\n };\n}\n\nexport interface PaymentStrategyErrorsState {\n deinitializeError?: Error;\n deinitializeMethodId?: string;\n executeError?: Error;\n executeMethodId?: string;\n finalizeError?: Error;\n finalizeMethodId?: string;\n initializeError?: Error;\n initializeMethodId?: string;\n widgetInteractionError?: Error;\n widgetInteractionMethodId?: string;\n}\n\nexport interface PaymentStrategyStatusesState {\n deinitializeMethodId?: string;\n executeMethodId?: string;\n finalizeMethodId?: string;\n initializeMethodId?: string;\n isDeinitializing?: boolean;\n isExecuting?: boolean;\n isFinalizing?: boolean;\n isInitializing?: boolean;\n isWidgetInteracting?: boolean;\n widgetInteractionMethodId?: string;\n}\n\nexport const DEFAULT_STATE: PaymentStrategyState = {\n data: {},\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge } from '../common/utility';\n\nimport { PaymentStrategyAction, PaymentStrategyActionType } from './payment-strategy-actions';\nimport PaymentStrategyState, {\n DEFAULT_STATE,\n PaymentStrategyDataState,\n PaymentStrategyErrorsState,\n PaymentStrategyStatusesState,\n} from './payment-strategy-state';\n\nexport default function paymentStrategyReducer(\n state: PaymentStrategyState = DEFAULT_STATE,\n action: Action,\n): PaymentStrategyState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: PaymentStrategyDataState = DEFAULT_STATE.data,\n action: PaymentStrategyAction,\n): PaymentStrategyDataState {\n switch (action.type) {\n case PaymentStrategyActionType.InitializeSucceeded: {\n if (action.meta) {\n const { methodId, gatewayId } = action.meta;\n const initializeMethodId = gatewayId ? `${methodId}.${gatewayId}` : methodId;\n\n return objectMerge(data, {\n [initializeMethodId]: {\n isInitialized: true,\n },\n });\n }\n\n break;\n }\n\n case PaymentStrategyActionType.DeinitializeSucceeded: {\n if (action.meta) {\n const { methodId, gatewayId } = action.meta;\n const initializeMethodId = gatewayId ? `${methodId}.${gatewayId}` : methodId;\n\n return objectMerge(data, {\n [initializeMethodId]: {\n isInitialized: false,\n },\n });\n }\n }\n }\n\n return data;\n}\n\nfunction errorsReducer(\n errors: PaymentStrategyErrorsState = DEFAULT_STATE.errors,\n action: PaymentStrategyAction,\n): PaymentStrategyErrorsState {\n switch (action.type) {\n case PaymentStrategyActionType.InitializeRequested:\n case PaymentStrategyActionType.InitializeSucceeded:\n return objectMerge(errors, {\n initializeError: undefined,\n initializeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.InitializeFailed: {\n let initializeMethodId = action.meta && action.meta.methodId;\n\n if (action.meta) {\n const { methodId, gatewayId } = action.meta;\n\n initializeMethodId = gatewayId ? `${methodId}.${gatewayId}` : methodId;\n }\n\n return objectMerge(errors, {\n initializeError: action.payload,\n initializeMethodId,\n });\n }\n\n case PaymentStrategyActionType.DeinitializeRequested:\n case PaymentStrategyActionType.DeinitializeSucceeded:\n return objectMerge(errors, {\n deinitializeError: undefined,\n deinitializeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.DeinitializeFailed: {\n let deinitializeMethodId = action.meta && action.meta.methodId;\n\n if (action.meta) {\n const { methodId, gatewayId } = action.meta;\n\n deinitializeMethodId = gatewayId ? `${methodId}.${gatewayId}` : methodId;\n }\n\n return objectMerge(errors, {\n deinitializeError: action.payload,\n deinitializeMethodId,\n });\n }\n\n case PaymentStrategyActionType.ExecuteRequested:\n case PaymentStrategyActionType.ExecuteSucceeded:\n return objectMerge(errors, {\n executeError: undefined,\n executeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.ExecuteFailed:\n return objectMerge(errors, {\n executeError: action.payload,\n executeMethodId: action.meta && action.meta.methodId,\n });\n\n case PaymentStrategyActionType.FinalizeRequested:\n case PaymentStrategyActionType.FinalizeSucceeded:\n return objectMerge(errors, {\n finalizeError: undefined,\n finalizeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.FinalizeFailed:\n return objectMerge(errors, {\n finalizeError: action.payload,\n finalizeMethodId: action.meta && action.meta.methodId,\n });\n\n case PaymentStrategyActionType.WidgetInteractionStarted:\n case PaymentStrategyActionType.WidgetInteractionFinished:\n return objectMerge(errors, {\n widgetInteractionError: undefined,\n widgetInteractionMethodId: undefined,\n });\n\n case PaymentStrategyActionType.WidgetInteractionFailed:\n return objectMerge(errors, {\n widgetInteractionError: action.payload,\n widgetInteractionMethodId: action.meta.methodId,\n });\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: PaymentStrategyStatusesState = DEFAULT_STATE.statuses,\n action: PaymentStrategyAction,\n): PaymentStrategyStatusesState {\n switch (action.type) {\n case PaymentStrategyActionType.InitializeRequested: {\n let initializeMethodId = action.meta && action.meta.methodId;\n\n if (action.meta) {\n const { methodId, gatewayId } = action.meta;\n\n initializeMethodId = gatewayId ? `${methodId}.${gatewayId}` : methodId;\n }\n\n return objectMerge(statuses, {\n isInitializing: true,\n initializeMethodId,\n });\n }\n\n case PaymentStrategyActionType.InitializeFailed:\n case PaymentStrategyActionType.InitializeSucceeded:\n return objectMerge(statuses, {\n isInitializing: false,\n initializeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.DeinitializeRequested: {\n let deinitializeMethodId = action.meta && action.meta.methodId;\n\n if (action.meta) {\n const { methodId, gatewayId } = action.meta;\n\n deinitializeMethodId = gatewayId ? `${methodId}.${gatewayId}` : methodId;\n }\n\n return objectMerge(statuses, {\n isDeinitializing: true,\n deinitializeMethodId,\n });\n }\n\n case PaymentStrategyActionType.DeinitializeFailed:\n case PaymentStrategyActionType.DeinitializeSucceeded:\n return objectMerge(statuses, {\n isDeinitializing: false,\n deinitializeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.ExecuteRequested:\n return objectMerge(statuses, {\n isExecuting: true,\n executeMethodId: action.meta && action.meta.methodId,\n });\n\n case PaymentStrategyActionType.ExecuteFailed:\n case PaymentStrategyActionType.ExecuteSucceeded:\n return objectMerge(statuses, {\n isExecuting: false,\n executeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.FinalizeRequested:\n return objectMerge(statuses, {\n isFinalizing: true,\n finalizeMethodId: action.meta && action.meta.methodId,\n });\n\n case PaymentStrategyActionType.FinalizeFailed:\n case PaymentStrategyActionType.FinalizeSucceeded:\n return objectMerge(statuses, {\n isFinalizing: false,\n finalizeMethodId: undefined,\n });\n\n case PaymentStrategyActionType.WidgetInteractionStarted:\n return objectMerge(statuses, {\n isWidgetInteracting: true,\n widgetInteractionMethodId: action.meta.methodId,\n });\n\n case PaymentStrategyActionType.WidgetInteractionFinished:\n case PaymentStrategyActionType.WidgetInteractionFailed:\n return objectMerge(statuses, {\n isWidgetInteracting: false,\n widgetInteractionMethodId: undefined,\n });\n\n default:\n return statuses;\n }\n}\n","import PaymentInstrument, { VaultAccessToken } from './instrument';\n\nexport default interface InstrumentState {\n data?: PaymentInstrument[];\n meta?: InstrumentMeta;\n errors: InstrumentErrorState;\n statuses: InstrumentStatusState;\n}\n\nexport interface InstrumentErrorState {\n deleteError?: Error;\n failedInstrument?: string;\n loadError?: Error;\n vaultError?: Error;\n}\n\nexport interface InstrumentStatusState {\n isDeleting?: boolean;\n isLoading?: boolean;\n isVaulting?: boolean;\n deletingInstrument?: string;\n}\n\nexport type InstrumentMeta = VaultAccessToken;\n\nexport const DEFAULT_STATE = {\n data: [],\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../../common/error';\nimport { arrayReplace, objectMerge, objectSet } from '../../common/utility';\n\nimport PaymentInstrument from './instrument';\nimport { InstrumentAction, InstrumentActionType } from './instrument-actions';\nimport InstrumentState, {\n DEFAULT_STATE,\n InstrumentErrorState,\n InstrumentMeta,\n InstrumentStatusState,\n} from './instrument-state';\n\nexport default function instrumentReducer(\n state: InstrumentState = DEFAULT_STATE,\n action: Action,\n): InstrumentState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n meta: metaReducer,\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: PaymentInstrument[] = DEFAULT_STATE.data,\n action: InstrumentAction,\n): PaymentInstrument[] {\n switch (action.type) {\n case InstrumentActionType.LoadInstrumentsSucceeded:\n return arrayReplace(data, (action.payload && action.payload.vaultedInstruments) || []);\n\n default:\n return data;\n }\n}\n\nfunction metaReducer(\n meta: InstrumentMeta | undefined,\n action: InstrumentAction,\n): InstrumentMeta | undefined {\n switch (action.type) {\n case InstrumentActionType.LoadInstrumentsSucceeded:\n case InstrumentActionType.DeleteInstrumentSucceeded:\n return objectMerge(meta, action.meta);\n\n default:\n return meta;\n }\n}\n\nfunction errorsReducer(\n errors: InstrumentErrorState = DEFAULT_STATE.errors,\n action: InstrumentAction,\n): InstrumentErrorState {\n switch (action.type) {\n case InstrumentActionType.LoadInstrumentsRequested:\n case InstrumentActionType.LoadInstrumentsSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case InstrumentActionType.DeleteInstrumentRequested:\n case InstrumentActionType.DeleteInstrumentSucceeded:\n return objectMerge(errors, {\n deleteError: undefined,\n failedInstrument: undefined,\n });\n\n case InstrumentActionType.LoadInstrumentsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n case InstrumentActionType.DeleteInstrumentFailed:\n return objectMerge(errors, {\n deleteError: action.payload,\n failedInstrument: action.meta.instrumentId,\n });\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: InstrumentStatusState = DEFAULT_STATE.statuses,\n action: InstrumentAction,\n): InstrumentStatusState {\n switch (action.type) {\n case InstrumentActionType.LoadInstrumentsRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case InstrumentActionType.DeleteInstrumentRequested:\n return objectMerge(statuses, {\n isDeleting: true,\n deletingInstrument: action.meta.instrumentId,\n });\n\n case InstrumentActionType.LoadInstrumentsSucceeded:\n case InstrumentActionType.LoadInstrumentsFailed:\n return objectSet(statuses, 'isLoading', false);\n\n case InstrumentActionType.DeleteInstrumentSucceeded:\n case InstrumentActionType.DeleteInstrumentFailed:\n return objectMerge(statuses, {\n isDeleting: false,\n deletingInstrument: undefined,\n });\n\n default:\n return statuses;\n }\n}\n","import { AmazonPayRemoteCheckout } from './methods';\n\nexport default interface RemoteCheckoutState {\n data: RemoteCheckoutStateData;\n}\n\nexport interface RemoteCheckoutStateData {\n amazon?: AmazonPayRemoteCheckout;\n}\n\nexport const DEFAULT_STATE: RemoteCheckoutState = {\n data: {},\n};\n","import { combineReducers } from '@bigcommerce/data-store';\n\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport RemoteCheckout from './remote-checkout';\nimport { RemoteCheckoutAction, RemoteCheckoutActionType } from './remote-checkout-actions';\nimport RemoteCheckoutState, {\n DEFAULT_STATE,\n RemoteCheckoutStateData,\n} from './remote-checkout-state';\n\nexport default function remoteCheckoutReducer(\n state: RemoteCheckoutState = DEFAULT_STATE,\n action: RemoteCheckoutAction,\n): RemoteCheckoutState {\n if (!action.meta || !action.meta.methodId) {\n return state;\n }\n\n const reducer = combineReducers({\n data: combineReducers({\n [action.meta.methodId]: dataReducer,\n }),\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(data: RemoteCheckout, action: RemoteCheckoutAction): RemoteCheckout {\n switch (action.type) {\n case RemoteCheckoutActionType.InitializeRemoteBillingSucceeded:\n return objectSet(data, 'billing' as any, action.payload && action.payload.billing);\n\n case RemoteCheckoutActionType.InitializeRemoteShippingSucceeded:\n return objectSet(data, 'shipping' as any, action.payload && action.payload.shipping);\n\n case RemoteCheckoutActionType.LoadRemoteSettingsSucceeded:\n return objectSet(data, 'settings', action.payload);\n\n case RemoteCheckoutActionType.UpdateRemoteCheckout:\n return objectMerge(data, action.payload);\n\n default:\n return data;\n }\n}\n","import Consignment from './consignment';\n\nexport default interface ConsignmentState {\n data?: Consignment[];\n errors: ConsignmentErrorsState;\n statuses: ConsignmentStatusesState;\n}\n\nexport interface ConsignmentErrorsState {\n loadError?: Error;\n loadShippingOptionsError?: Error;\n createError?: Error;\n updateError: { [key: string]: Error | undefined };\n deleteError: { [key: string]: Error | undefined };\n updateShippingOptionError: { [key: string]: Error | undefined };\n}\n\nexport interface ConsignmentStatusesState {\n isLoading?: boolean;\n isLoadingShippingOptions?: boolean;\n isCreating?: boolean;\n isUpdating: { [key: string]: boolean };\n isDeleting: { [key: string]: boolean };\n isUpdatingShippingOption: { [key: string]: boolean };\n}\n\nexport const DEFAULT_STATE: ConsignmentState = {\n errors: {\n updateShippingOptionError: {},\n updateError: {},\n deleteError: {},\n },\n statuses: {\n isUpdating: {},\n isUpdatingShippingOption: {},\n isDeleting: {},\n },\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { CheckoutAction, CheckoutActionType } from '../checkout';\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectMerge, objectSet } from '../common/utility';\nimport { CouponAction, CouponActionType } from '../coupon';\nimport { CustomerAction, CustomerActionType } from '../customer';\n\nimport Consignment from './consignment';\nimport { ConsignmentAction, ConsignmentActionType } from './consignment-actions';\nimport ConsignmentState, {\n ConsignmentErrorsState,\n ConsignmentStatusesState,\n DEFAULT_STATE,\n} from './consignment-state';\n\nexport default function consignmentReducer(\n state: ConsignmentState = DEFAULT_STATE,\n action: Action,\n): ConsignmentState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: Consignment[] | undefined,\n action: ConsignmentAction | CheckoutAction | CouponAction | CustomerAction,\n): Consignment[] | undefined {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutSucceeded:\n case ConsignmentActionType.LoadShippingOptionsSucceeded:\n case ConsignmentActionType.CreateConsignmentsSucceeded:\n case ConsignmentActionType.UpdateConsignmentSucceeded:\n case ConsignmentActionType.DeleteConsignmentSucceeded:\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n case CouponActionType.ApplyCouponSucceeded:\n case CouponActionType.RemoveCouponSucceeded:\n return arrayReplace(data, action.payload && action.payload.consignments);\n\n case CustomerActionType.SignOutCustomerSucceeded:\n return arrayReplace(data, []);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: ConsignmentErrorsState = DEFAULT_STATE.errors,\n action: ConsignmentAction | CheckoutAction,\n): ConsignmentErrorsState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n case CheckoutActionType.LoadCheckoutSucceeded:\n case ConsignmentActionType.LoadShippingOptionsSucceeded:\n case ConsignmentActionType.LoadShippingOptionsRequested:\n return objectSet(errors, 'loadError', undefined);\n\n case CheckoutActionType.LoadCheckoutFailed:\n case ConsignmentActionType.LoadShippingOptionsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n case ConsignmentActionType.CreateConsignmentsRequested:\n case ConsignmentActionType.CreateConsignmentsSucceeded:\n return objectSet(errors, 'createError', undefined);\n\n case ConsignmentActionType.CreateConsignmentsFailed:\n return objectSet(errors, 'createError', action.payload);\n\n case ConsignmentActionType.UpdateConsignmentSucceeded:\n case ConsignmentActionType.UpdateConsignmentRequested:\n if (action.meta) {\n return objectMerge(errors, {\n updateError: {\n [action.meta.id]: undefined,\n },\n });\n }\n\n return errors;\n\n case ConsignmentActionType.UpdateConsignmentFailed:\n if (action.meta) {\n return objectMerge(errors, {\n updateError: {\n [action.meta.id]: action.payload,\n },\n });\n }\n\n return errors;\n\n case ConsignmentActionType.DeleteConsignmentSucceeded:\n case ConsignmentActionType.DeleteConsignmentRequested:\n if (action.meta) {\n return objectMerge(errors, {\n deleteError: {\n [action.meta.id]: undefined,\n },\n });\n }\n\n return errors;\n\n case ConsignmentActionType.DeleteConsignmentFailed:\n if (action.meta) {\n return objectMerge(errors, {\n deleteError: {\n [action.meta.id]: action.payload,\n },\n });\n }\n\n return errors;\n\n case ConsignmentActionType.UpdateShippingOptionRequested:\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n if (action.meta) {\n return objectMerge(errors, {\n updateShippingOptionError: {\n [action.meta.id]: undefined,\n },\n });\n }\n\n return errors;\n\n case ConsignmentActionType.UpdateShippingOptionFailed:\n if (action.meta) {\n return objectMerge(errors, {\n updateShippingOptionError: {\n [action.meta.id]: action.payload,\n },\n });\n }\n\n return errors;\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: ConsignmentStatusesState = DEFAULT_STATE.statuses,\n action: ConsignmentAction | CheckoutAction,\n): ConsignmentStatusesState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case ConsignmentActionType.LoadShippingOptionsRequested:\n return objectSet(statuses, 'isLoadingShippingOptions', true);\n\n case CheckoutActionType.LoadCheckoutSucceeded:\n case CheckoutActionType.LoadCheckoutFailed:\n return objectSet(statuses, 'isLoading', false);\n\n case ConsignmentActionType.LoadShippingOptionsSucceeded:\n case ConsignmentActionType.LoadShippingOptionsFailed:\n return objectSet(statuses, 'isLoadingShippingOptions', false);\n\n case ConsignmentActionType.CreateConsignmentsRequested:\n return objectSet(statuses, 'isCreating', true);\n\n case ConsignmentActionType.CreateConsignmentsSucceeded:\n case ConsignmentActionType.CreateConsignmentsFailed:\n return objectSet(statuses, 'isCreating', false);\n\n case ConsignmentActionType.UpdateConsignmentRequested:\n if (action.meta) {\n return objectMerge(statuses, {\n isUpdating: {\n [action.meta.id]: true,\n },\n });\n }\n\n return statuses;\n\n case ConsignmentActionType.UpdateConsignmentSucceeded:\n case ConsignmentActionType.UpdateConsignmentFailed:\n if (action.meta) {\n return objectMerge(statuses, {\n isUpdating: {\n [action.meta.id]: false,\n },\n });\n }\n\n return statuses;\n\n case ConsignmentActionType.DeleteConsignmentRequested:\n if (action.meta) {\n return objectMerge(statuses, {\n isDeleting: {\n [action.meta.id]: true,\n },\n });\n }\n\n return statuses;\n\n case ConsignmentActionType.DeleteConsignmentSucceeded:\n case ConsignmentActionType.DeleteConsignmentFailed:\n if (action.meta) {\n return objectMerge(statuses, {\n isDeleting: {\n [action.meta.id]: false,\n },\n });\n }\n\n return statuses;\n\n case ConsignmentActionType.UpdateShippingOptionRequested:\n if (action.meta) {\n return objectMerge(statuses, {\n isUpdatingShippingOption: {\n [action.meta.id]: true,\n },\n });\n }\n\n return statuses;\n\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n case ConsignmentActionType.UpdateShippingOptionFailed:\n if (action.meta) {\n return objectMerge(statuses, {\n isUpdatingShippingOption: {\n [action.meta.id]: false,\n },\n });\n }\n\n return statuses;\n\n default:\n return statuses;\n }\n}\n","/**\n * Takes a nested object and flattens it.\n */\nexport default function objectFlatten(\n object: { [key: string]: any },\n parent?: string,\n): { [key: string]: any } {\n const flattened: { [key: string]: any } = {};\n\n Object.keys(object).forEach((key: string) => {\n const value = object[key];\n const keyString = parent ? `${parent}.${key}` : key;\n\n if (typeof value === 'object') {\n Object.assign(flattened, objectFlatten(value, keyString));\n } else {\n flattened[keyString] = value;\n }\n });\n\n return flattened;\n}\n","export default function objectWithSortedKeys(object: { [key: string]: any }) {\n const keys = Object.keys(object);\n const sortedKeys = keys.sort();\n\n const sortedArray = sortedKeys.reduce(\n (previous, current) => ({\n ...previous,\n [current]: object[current],\n }),\n {},\n );\n\n return sortedArray;\n}\n","import { PickupOptionQueryMap } from './pickup-option';\n\nexport default interface PickupOptionState {\n data?: PickupOptionQueryMap;\n errors: PickupOptionErrorsState;\n statuses: PickupOptionStatusesState;\n}\n\nexport interface PickupOptionErrorsState {\n loadError?: Error;\n}\n\nexport interface PickupOptionStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: PickupOptionState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectFlatten, objectSet, objectWithSortedKeys } from '../common/utility';\n\nimport { PickupOptionQueryMap } from './pickup-option';\nimport { LoadPickupOptionsAction, PickupOptionActionType } from './pickup-option-actions';\nimport PickupOptionState, {\n DEFAULT_STATE,\n PickupOptionErrorsState,\n PickupOptionStatusesState,\n} from './pickup-option-state';\n\nexport default function pickupOptionReducer(\n state: PickupOptionState = DEFAULT_STATE,\n action: Action,\n): PickupOptionState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: PickupOptionQueryMap | undefined,\n action: LoadPickupOptionsAction,\n): PickupOptionQueryMap | undefined {\n switch (action.type) {\n case PickupOptionActionType.LoadPickupOptionsSucceeded:\n if (action.meta) {\n const optionQuery = {\n consignmentId: action.meta.consignmentId,\n searchArea: action.meta.searchArea,\n };\n const flattenedMeta = objectFlatten(optionQuery);\n const sortedflattenedMeta = objectWithSortedKeys(flattenedMeta);\n const keyString = btoa(`${JSON.stringify(sortedflattenedMeta)}`);\n\n return objectSet(data, keyString, action.payload);\n }\n\n break;\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(errors: PickupOptionErrorsState = DEFAULT_STATE.errors, action: Action) {\n switch (action.type) {\n case PickupOptionActionType.LoadPickupOptionsRequested:\n case PickupOptionActionType.LoadPickupOptionsSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case PickupOptionActionType.LoadPickupOptionsFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: PickupOptionStatusesState = DEFAULT_STATE.statuses,\n action: Action,\n) {\n switch (action.type) {\n case PickupOptionActionType.LoadPickupOptionsRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case PickupOptionActionType.LoadPickupOptionsSucceeded:\n case PickupOptionActionType.LoadPickupOptionsFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","import { Country } from '../geography';\n\nexport default interface ShippingCountryState {\n data?: Country[];\n errors: ShippingCountryErrorsState;\n statuses: ShippingCountryStatusesState;\n}\n\nexport interface ShippingCountryErrorsState {\n loadError?: Error;\n}\n\nexport interface ShippingCountryStatusesState {\n isLoading?: boolean;\n}\n\nexport const DEFAULT_STATE: ShippingCountryState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { arrayReplace, objectSet } from '../common/utility';\nimport { Country } from '../geography';\n\nimport { LoadShippingCountriesAction, ShippingCountryActionType } from './shipping-country-actions';\nimport ShippingCountryState, {\n DEFAULT_STATE,\n ShippingCountryErrorsState,\n ShippingCountryStatusesState,\n} from './shipping-country-state';\n\nexport default function shippingCountryReducer(\n state: ShippingCountryState = DEFAULT_STATE,\n action: Action,\n): ShippingCountryState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: Country[] | undefined,\n action: LoadShippingCountriesAction,\n): Country[] | undefined {\n switch (action.type) {\n case ShippingCountryActionType.LoadShippingCountriesSucceeded:\n return arrayReplace(data, action.payload);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: ShippingCountryErrorsState = DEFAULT_STATE.errors,\n action: LoadShippingCountriesAction,\n): ShippingCountryErrorsState {\n switch (action.type) {\n case ShippingCountryActionType.LoadShippingCountriesRequested:\n case ShippingCountryActionType.LoadShippingCountriesSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case ShippingCountryActionType.LoadShippingCountriesFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: ShippingCountryStatusesState = DEFAULT_STATE.statuses,\n action: LoadShippingCountriesAction,\n): ShippingCountryStatusesState {\n switch (action.type) {\n case ShippingCountryActionType.LoadShippingCountriesRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case ShippingCountryActionType.LoadShippingCountriesSucceeded:\n case ShippingCountryActionType.LoadShippingCountriesFailed:\n return objectSet(statuses, 'isLoading', false);\n\n default:\n return statuses;\n }\n}\n","export default interface ShippingStrategyState {\n data: ShippingStrategyDataState;\n errors: ShippingStrategyErrorsState;\n statuses: ShippingStrategyStatusesState;\n}\n\nexport interface ShippingStrategyDataState {\n [key: string]: {\n isInitialized: boolean;\n };\n}\n\nexport interface ShippingStrategyErrorsState {\n deinitializeError?: Error;\n deinitializeMethodId?: string;\n initializeError?: Error;\n initializeMethodId?: string;\n updateAddressError?: Error;\n updateAddressMethodId?: string;\n selectOptionError?: Error;\n selectOptionMethodId?: string;\n widgetInteractionError?: Error;\n widgetInteractionMethodId?: string;\n}\n\nexport interface ShippingStrategyStatusesState {\n deinitializeMethodId?: string;\n initializeMethodId?: string;\n isDeinitializing?: boolean;\n isInitializing?: boolean;\n isUpdatingAddress?: boolean;\n isSelectingOption?: boolean;\n updateAddressMethodId?: string;\n selectOptionMethodId?: string;\n isWidgetInteracting?: boolean;\n widgetInteractionMethodId?: string;\n}\n\nexport const DEFAULT_STATE: ShippingStrategyState = {\n data: {},\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge } from '../common/utility';\n\nimport { ShippingStrategyAction, ShippingStrategyActionType } from './shipping-strategy-actions';\nimport ShippingStrategyState, {\n DEFAULT_STATE,\n ShippingStrategyDataState,\n ShippingStrategyErrorsState,\n ShippingStrategyStatusesState,\n} from './shipping-strategy-state';\n\nexport default function shippingStrategyReducer(\n state: ShippingStrategyState = DEFAULT_STATE,\n action: Action,\n): ShippingStrategyState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: ShippingStrategyDataState = DEFAULT_STATE.data,\n action: ShippingStrategyAction,\n): ShippingStrategyDataState {\n switch (action.type) {\n case ShippingStrategyActionType.InitializeSucceeded:\n return objectMerge(data, {\n [action.meta && action.meta.methodId]: {\n isInitialized: true,\n },\n });\n\n case ShippingStrategyActionType.DeinitializeSucceeded:\n return objectMerge(data, {\n [action.meta && action.meta.methodId]: {\n isInitialized: false,\n },\n });\n }\n\n return data;\n}\n\nfunction errorsReducer(\n errors: ShippingStrategyErrorsState = DEFAULT_STATE.errors,\n action: ShippingStrategyAction,\n): ShippingStrategyErrorsState {\n switch (action.type) {\n case ShippingStrategyActionType.InitializeRequested:\n case ShippingStrategyActionType.InitializeSucceeded:\n return objectMerge(errors, {\n initializeError: undefined,\n initializeMethodId: undefined,\n });\n\n case ShippingStrategyActionType.InitializeFailed:\n return objectMerge(errors, {\n initializeError: action.payload,\n initializeMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.DeinitializeRequested:\n case ShippingStrategyActionType.DeinitializeSucceeded:\n return objectMerge(errors, {\n deinitializeError: undefined,\n deinitializeMethodId: undefined,\n });\n\n case ShippingStrategyActionType.DeinitializeFailed:\n return objectMerge(errors, {\n deinitializeError: action.payload,\n deinitializeMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.UpdateAddressRequested:\n case ShippingStrategyActionType.UpdateAddressSucceeded:\n return objectMerge(errors, {\n updateAddressError: undefined,\n updateAddressMethodId: undefined,\n });\n\n case ShippingStrategyActionType.UpdateAddressFailed:\n return objectMerge(errors, {\n updateAddressError: action.payload,\n updateAddressMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.SelectOptionRequested:\n case ShippingStrategyActionType.SelectOptionSucceeded:\n return objectMerge(errors, {\n selectOptionError: undefined,\n selectOptionMethodId: undefined,\n });\n\n case ShippingStrategyActionType.SelectOptionFailed:\n return objectMerge(errors, {\n selectOptionError: action.payload,\n selectOptionMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.WidgetInteractionStarted:\n case ShippingStrategyActionType.WidgetInteractionFinished:\n return objectMerge(errors, {\n widgetInteractionError: undefined,\n widgetInteractionMethodId: undefined,\n });\n\n case ShippingStrategyActionType.WidgetInteractionFailed:\n return objectMerge(errors, {\n widgetInteractionError: action.payload,\n widgetInteractionMethodId: action.meta && action.meta.methodId,\n });\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: ShippingStrategyStatusesState = DEFAULT_STATE.statuses,\n action: ShippingStrategyAction,\n): ShippingStrategyStatusesState {\n switch (action.type) {\n case ShippingStrategyActionType.InitializeRequested:\n return objectMerge(statuses, {\n isInitializing: true,\n initializeMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.InitializeFailed:\n case ShippingStrategyActionType.InitializeSucceeded:\n return objectMerge(statuses, {\n isInitializing: false,\n initializeMethodId: undefined,\n });\n\n case ShippingStrategyActionType.DeinitializeRequested:\n return objectMerge(statuses, {\n isDeinitializing: true,\n deinitializeMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.DeinitializeFailed:\n case ShippingStrategyActionType.DeinitializeSucceeded:\n return objectMerge(statuses, {\n isDeinitializing: false,\n deinitializeMethodId: undefined,\n });\n\n case ShippingStrategyActionType.UpdateAddressRequested:\n return objectMerge(statuses, {\n isUpdatingAddress: true,\n updateAddressMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.UpdateAddressFailed:\n case ShippingStrategyActionType.UpdateAddressSucceeded:\n return objectMerge(statuses, {\n isUpdatingAddress: false,\n updateAddressMethodId: undefined,\n });\n\n case ShippingStrategyActionType.SelectOptionRequested:\n return objectMerge(statuses, {\n isSelectingOption: true,\n selectOptionMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.SelectOptionFailed:\n case ShippingStrategyActionType.SelectOptionSucceeded:\n return objectMerge(statuses, {\n isSelectingOption: false,\n selectOptionMethodId: undefined,\n });\n\n case ShippingStrategyActionType.WidgetInteractionStarted:\n return objectMerge(statuses, {\n isWidgetInteracting: true,\n widgetInteractionMethodId: action.meta && action.meta.methodId,\n });\n\n case ShippingStrategyActionType.WidgetInteractionFinished:\n case ShippingStrategyActionType.WidgetInteractionFailed:\n return objectMerge(statuses, {\n isWidgetInteracting: false,\n widgetInteractionMethodId: undefined,\n });\n\n default:\n return statuses;\n }\n}\n","import { SignInEmail } from './signin-email';\n\nexport default interface SignInEmailState {\n data?: SignInEmail;\n errors: SignInEmailErrorsState;\n statuses: SignInEmailStatusesState;\n}\n\nexport interface SignInEmailErrorsState {\n sendError?: Error;\n}\n\nexport interface SignInEmailStatusesState {\n isSending?: boolean;\n}\n\nexport const DEFAULT_STATE: SignInEmailState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\n\nimport { SignInEmail } from './signin-email';\nimport { SendSignInEmailAction, SignInEmailActionType } from './signin-email-actions';\nimport SignInEmailState, {\n DEFAULT_STATE,\n SignInEmailErrorsState,\n SignInEmailStatusesState,\n} from './signin-email-state';\n\nexport default function signInEmailReducer(\n state: SignInEmailState = DEFAULT_STATE,\n action: Action,\n): SignInEmailState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: SignInEmail | undefined,\n action: SendSignInEmailAction,\n): SignInEmail | undefined {\n switch (action.type) {\n case SignInEmailActionType.SendSignInEmailSucceeded:\n return objectMerge(data, action.payload);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: SignInEmailErrorsState = DEFAULT_STATE.errors,\n action: SendSignInEmailAction,\n): SignInEmailErrorsState {\n switch (action.type) {\n case SignInEmailActionType.SendSignInEmailRequested:\n case SignInEmailActionType.SendSignInEmailSucceeded:\n return objectSet(errors, 'sendError', undefined);\n\n case SignInEmailActionType.SendSignInEmailFailed:\n return objectSet(errors, 'sendError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: SignInEmailStatusesState = DEFAULT_STATE.statuses,\n action: SendSignInEmailAction,\n): SignInEmailStatusesState {\n switch (action.type) {\n case SignInEmailActionType.SendSignInEmailRequested:\n return objectSet(statuses, 'isSending', true);\n\n case SignInEmailActionType.SendSignInEmailFailed:\n case SignInEmailActionType.SendSignInEmailSucceeded:\n return objectSet(statuses, 'isSending', false);\n\n default:\n return statuses;\n }\n}\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectSet } from '../common/utility';\n\nimport { StoreCreditAction, StoreCreditActionType } from './store-credit-actions';\nimport StoreCreditState, {\n StoreCreditErrorsState,\n StoreCreditStatusesState,\n} from './store-credit-state';\n\nconst DEFAULT_STATE: StoreCreditState = {\n errors: {},\n statuses: {},\n};\n\nexport default function storeCreditReducer(\n state: StoreCreditState = DEFAULT_STATE,\n action: Action,\n): StoreCreditState {\n const reducer = combineReducers({\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction errorsReducer(\n errors: StoreCreditErrorsState = DEFAULT_STATE.errors,\n action: StoreCreditAction,\n): StoreCreditErrorsState {\n switch (action.type) {\n case StoreCreditActionType.ApplyStoreCreditRequested:\n case StoreCreditActionType.ApplyStoreCreditSucceeded:\n return objectSet(errors, 'applyError', undefined);\n\n case StoreCreditActionType.ApplyStoreCreditFailed:\n return objectSet(errors, 'applyError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: StoreCreditStatusesState = DEFAULT_STATE.statuses,\n action: StoreCreditAction,\n): StoreCreditStatusesState {\n switch (action.type) {\n case StoreCreditActionType.ApplyStoreCreditRequested:\n return objectSet(statuses, 'isApplying', true);\n\n case StoreCreditActionType.ApplyStoreCreditSucceeded:\n case StoreCreditActionType.ApplyStoreCreditFailed:\n return objectSet(statuses, 'isApplying', false);\n\n default:\n return statuses;\n }\n}\n","export default interface SubscriptionsState {\n errors: SubscriptionsErrorsState;\n statuses: SubscriptionsStatusesState;\n}\n\nexport interface SubscriptionsErrorsState {\n updateError?: Error;\n}\n\nexport interface SubscriptionsStatusesState {\n isUpdating?: boolean;\n}\n\nexport const DEFAULT_STATE: SubscriptionsState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\n\nimport { clearErrorReducer } from '../common/error';\nimport { objectSet } from '../common/utility';\nimport { SubscriptionsActionType, UpdateSubscriptionsAction } from '../subscription';\n\nimport SubscriptionsState, {\n DEFAULT_STATE,\n SubscriptionsErrorsState,\n SubscriptionsStatusesState,\n} from './subscriptions-state';\n\nexport default function subscriptionsReducer(\n state: SubscriptionsState = DEFAULT_STATE,\n action: Action,\n): SubscriptionsState {\n const reducer = combineReducers({\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction errorsReducer(\n errors: SubscriptionsErrorsState = DEFAULT_STATE.errors,\n action: UpdateSubscriptionsAction,\n): SubscriptionsErrorsState {\n switch (action.type) {\n case SubscriptionsActionType.UpdateSubscriptionsRequested:\n case SubscriptionsActionType.UpdateSubscriptionsSucceeded:\n return objectSet(errors, 'updateError', undefined);\n\n case SubscriptionsActionType.UpdateSubscriptionsFailed:\n return objectSet(errors, 'updateError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: SubscriptionsStatusesState = DEFAULT_STATE.statuses,\n action: UpdateSubscriptionsAction,\n): SubscriptionsStatusesState {\n switch (action.type) {\n case SubscriptionsActionType.UpdateSubscriptionsRequested:\n return objectSet(statuses, 'isUpdating', true);\n\n case SubscriptionsActionType.UpdateSubscriptionsFailed:\n case SubscriptionsActionType.UpdateSubscriptionsSucceeded:\n return objectSet(statuses, 'isUpdating', false);\n\n default:\n return statuses;\n }\n}\n","import { Omit } from '../common/types';\n\nimport Checkout from './checkout';\n\nexport default interface CheckoutState {\n data?: CheckoutDataState;\n errors: CheckoutErrorsState;\n statuses: CheckoutStatusesState;\n}\n\nexport type CheckoutDataState = Omit<\n Checkout,\n 'billingAddress' | 'cart' | 'consignments' | 'coupons' | 'giftCertificates'\n>;\n\nexport interface CheckoutErrorsState {\n loadError?: Error;\n updateError?: Error;\n}\n\nexport interface CheckoutStatusesState {\n isExecutingSpamCheck?: boolean;\n isLoading?: boolean;\n isUpdating?: boolean;\n}\n\nexport const DEFAULT_STATE: CheckoutState = {\n errors: {},\n statuses: {},\n};\n","import { Action, combineReducers, composeReducers } from '@bigcommerce/data-store';\nimport { omit } from 'lodash';\n\nimport { BillingAddressAction, BillingAddressActionType } from '../billing';\nimport { clearErrorReducer } from '../common/error';\nimport { objectMerge, objectSet } from '../common/utility';\nimport {\n CouponAction,\n CouponActionType,\n GiftCertificateAction,\n GiftCertificateActionType,\n} from '../coupon';\nimport { OrderAction, OrderActionType } from '../order';\nimport { ConsignmentAction, ConsignmentActionType } from '../shipping';\nimport { SpamProtectionAction, SpamProtectionActionType } from '../spam-protection';\nimport { StoreCreditAction, StoreCreditActionType } from '../store-credit';\n\nimport { CheckoutAction, CheckoutActionType } from './checkout-actions';\nimport CheckoutState, {\n CheckoutDataState,\n CheckoutErrorsState,\n CheckoutStatusesState,\n DEFAULT_STATE,\n} from './checkout-state';\n\nexport default function checkoutReducer(\n state: CheckoutState = DEFAULT_STATE,\n action: Action,\n): CheckoutState {\n const reducer = combineReducers({\n data: dataReducer,\n errors: composeReducers(errorsReducer, clearErrorReducer),\n statuses: statusesReducer,\n });\n\n return reducer(state, action);\n}\n\nfunction dataReducer(\n data: CheckoutDataState | undefined,\n action:\n | CheckoutAction\n | BillingAddressAction\n | ConsignmentAction\n | CouponAction\n | GiftCertificateAction\n | OrderAction\n | SpamProtectionAction\n | StoreCreditAction,\n): CheckoutDataState | undefined {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutSucceeded:\n case CheckoutActionType.UpdateCheckoutSucceeded:\n case StoreCreditActionType.ApplyStoreCreditSucceeded:\n case BillingAddressActionType.UpdateBillingAddressSucceeded:\n case CouponActionType.ApplyCouponSucceeded:\n case CouponActionType.RemoveCouponSucceeded:\n case ConsignmentActionType.CreateConsignmentsSucceeded:\n case ConsignmentActionType.UpdateConsignmentSucceeded:\n case ConsignmentActionType.DeleteConsignmentSucceeded:\n case ConsignmentActionType.UpdateShippingOptionSucceeded:\n case ConsignmentActionType.LoadShippingOptionsSucceeded:\n case GiftCertificateActionType.ApplyGiftCertificateSucceeded:\n case GiftCertificateActionType.RemoveGiftCertificateSucceeded:\n case SpamProtectionActionType.VerifyCheckoutSucceeded:\n return objectMerge(\n data,\n omit(action.payload, [\n 'billingAddress',\n 'cart',\n 'consignments',\n 'customer',\n 'coupons',\n 'giftCertificates',\n ]),\n ) as CheckoutDataState;\n\n case OrderActionType.SubmitOrderSucceeded:\n return objectSet(data, 'orderId', action.payload && action.payload.order.orderId);\n\n default:\n return data;\n }\n}\n\nfunction errorsReducer(\n errors: CheckoutErrorsState = DEFAULT_STATE.errors,\n action: CheckoutAction | OrderAction,\n): CheckoutErrorsState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return objectSet(errors, 'loadError', undefined);\n\n case CheckoutActionType.LoadCheckoutFailed:\n return objectSet(errors, 'loadError', action.payload);\n\n case CheckoutActionType.UpdateCheckoutRequested:\n case CheckoutActionType.UpdateCheckoutSucceeded:\n return objectSet(errors, 'updateError', undefined);\n\n case CheckoutActionType.UpdateCheckoutFailed:\n return objectSet(errors, 'updateError', action.payload);\n\n default:\n return errors;\n }\n}\n\nfunction statusesReducer(\n statuses: CheckoutStatusesState = DEFAULT_STATE.statuses,\n action: CheckoutAction | OrderAction | SpamProtectionAction,\n): CheckoutStatusesState {\n switch (action.type) {\n case CheckoutActionType.LoadCheckoutRequested:\n return objectSet(statuses, 'isLoading', true);\n\n case CheckoutActionType.LoadCheckoutFailed:\n case CheckoutActionType.LoadCheckoutSucceeded:\n return objectSet(statuses, 'isLoading', false);\n\n case CheckoutActionType.UpdateCheckoutRequested:\n return objectSet(statuses, 'isUpdating', true);\n\n case CheckoutActionType.UpdateCheckoutFailed:\n case CheckoutActionType.UpdateCheckoutSucceeded:\n return objectSet(statuses, 'isUpdating', false);\n\n case SpamProtectionActionType.ExecuteRequested:\n return objectSet(statuses, 'isExecutingSpamCheck', true);\n\n case SpamProtectionActionType.ExecuteFailed:\n case SpamProtectionActionType.ExecuteSucceeded:\n return objectSet(statuses, 'isExecutingSpamCheck', false);\n\n default:\n return statuses;\n }\n}\n","import { deepFreeze } from '@bigcommerce/data-store';\n\n// tslint:disable-next-line:ban-types\ntype FunctionProperties = { [K in keyof T]: T[K] extends Function ? T[K] : never };\n\nexport default function createFreezeProxy(target: T): T {\n return createProxy(\n target,\n (target, name) =>\n (...args: any[]) =>\n deepFreeze(target[name].call(target, ...args)),\n );\n}\n\nexport function createFreezeProxies(\n map: TMap,\n): TMap {\n return Object.keys(map).reduce((result, key) => {\n result[key] = createFreezeProxy(map[key]);\n\n return result;\n }, {} as { [key: string]: T }) as TMap;\n}\n\nfunction createProxy(\n target: T,\n trap: (target: FunctionProperties, name: keyof FunctionProperties, proxy: T) => any,\n): T {\n const proxy = Object.create(target);\n\n traversePrototypeOf(target, (prototype) => {\n Object.getOwnPropertyNames(prototype).forEach((name) => {\n if (\n name === 'constructor' ||\n typeof proxy[name] !== 'function' ||\n name.charAt(0) === '_'\n ) {\n return;\n }\n\n proxy[name] = trap(target as FunctionProperties, name as keyof T, proxy);\n });\n });\n\n return proxy;\n}\n\nfunction traversePrototypeOf(target: object, iteratee: (prototype: object) => void): void {\n let prototype = Object.getPrototypeOf(target);\n\n while (prototype) {\n iteratee(prototype);\n\n prototype = Object.getPrototypeOf(prototype);\n }\n}\n","import PaymentInstrument from './instrument';\n\ninterface SupportedInstruments {\n [key: string]: Pick;\n}\n\nconst supportedInstruments: SupportedInstruments = {\n 'mollie.credit_card': {\n provider: 'mollie',\n method: 'credit_card',\n },\n 'adyenv2.scheme': {\n provider: 'adyenv2',\n method: 'scheme',\n },\n 'adyenv3.scheme': {\n provider: 'adyenv3',\n method: 'scheme',\n },\n 'adyenv2.bcmc': {\n provider: 'adyenv2',\n method: 'bcmc',\n },\n 'adyenv2.ideal': {\n provider: 'adyenv2',\n method: 'ideal',\n },\n 'adyenv2.sepadirectdebit': {\n provider: 'adyenv2',\n method: 'sepadirectdebit',\n },\n 'adyenv2.directEbanking': {\n provider: 'adyenv2',\n method: 'directEbanking',\n },\n 'adyenv2.giropay': {\n provider: 'adyenv2',\n method: 'giropay',\n },\n barclays: {\n provider: 'barclays',\n method: 'credit_card',\n },\n braintree: {\n provider: 'braintree',\n method: 'credit_card',\n },\n braintreepaypal: {\n provider: 'braintree',\n method: 'paypal',\n },\n braintreeach: {\n provider: 'braintree',\n method: 'ach',\n },\n authorizenet: {\n provider: 'authorizenet',\n method: 'credit_card',\n },\n elavon: {\n provider: 'elavon',\n method: 'credit_card',\n },\n checkoutcom: {\n provider: 'checkoutcom',\n method: 'credit_card',\n },\n 'checkoutcom.credit_card': {\n provider: 'checkoutcom',\n method: 'credit_card',\n },\n 'checkoutcom.card': {\n provider: 'checkoutcom',\n method: 'card',\n },\n sagepay: {\n provider: 'sagepay',\n method: 'credit_card',\n },\n stripe: {\n provider: 'stripe',\n method: 'credit_card',\n },\n 'stripev3.card': {\n provider: 'stripev3',\n method: 'card',\n },\n 'stripeupe.card': {\n provider: 'stripeupe',\n method: 'card',\n },\n cybersource: {\n provider: 'cybersource',\n method: 'credit_card',\n },\n cybersourcev2: {\n provider: 'cybersourcev2',\n method: 'credit_card',\n },\n bnz: {\n provider: 'bnz',\n method: 'credit_card',\n },\n converge: {\n provider: 'converge',\n method: 'credit_card',\n },\n bluesnapv2: {\n provider: 'bluesnapv2',\n method: 'credit_card',\n },\n 'bluesnapdirect.credit_card': {\n provider: 'bluesnapdirect',\n method: 'credit_card',\n },\n orbital: {\n provider: 'orbital',\n method: 'credit_card',\n },\n paymetric: {\n provider: 'paymetric',\n method: 'credit_card',\n },\n bolt: {\n provider: 'bolt',\n method: 'credit_card',\n },\n 'barclaycard.credit_card': {\n provider: 'barclaycard',\n method: 'credit_card',\n },\n digitalriver: {\n provider: 'digitalriver',\n method: 'credit_card',\n },\n moneris: {\n provider: 'moneris',\n method: 'credit_card',\n },\n cba_mpgs: {\n provider: 'cba_mpgs',\n method: 'credit_card',\n },\n worldpayaccess: {\n provider: 'worldpayaccess',\n method: 'credit_card',\n },\n};\n\nexport default supportedInstruments;\n","import { identity, isEqual, pickBy } from 'lodash';\n\nimport Address from './address';\n\nexport default function isAddressEqual(\n addressA: Partial
,\n addressB: Partial
,\n): boolean {\n return isEqual(normalize(addressA), normalize(addressB));\n}\n\nfunction normalize(address: Partial
): Partial
{\n return pickBy(\n {\n firstName: address.firstName,\n lastName: address.lastName,\n company: address.company,\n address1: address.address1,\n address2: address.address2,\n city: address.city,\n stateOrProvince: address.stateOrProvince,\n countryCode: address.countryCode,\n postalCode: address.postalCode,\n phone: address.phone,\n customFields: address.customFields,\n },\n identity,\n );\n}\n","import { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RequestError } from '../common/error/errors';\n\nexport default interface StoreCreditState {\n errors: StoreCreditErrorsState;\n statuses: StoreCreditStatusesState;\n}\n\nexport interface StoreCreditErrorsState {\n applyError?: RequestError;\n}\n\nexport interface StoreCreditStatusesState {\n isApplying?: boolean;\n}\n\nexport const DEFAULT_STATE: StoreCreditState = {\n errors: {},\n statuses: {},\n};\n","import { createBillingAddressSelectorFactory } from '../billing';\nimport { createCartSelectorFactory } from '../cart';\nimport { createCheckoutButtonSelectorFactory } from '../checkout-buttons';\nimport { createFreezeProxies } from '../common/utility';\nimport { createConfigSelectorFactory } from '../config';\nimport { createCouponSelectorFactory, createGiftCertificateSelectorFactory } from '../coupon';\nimport { createCustomerSelectorFactory, createCustomerStrategySelectorFactory } from '../customer';\nimport { createExtensionSelectorFactory } from '../extension';\nimport { createFormSelectorFactory } from '../form';\nimport { createCountrySelectorFactory } from '../geography';\nimport { createOrderSelectorFactory } from '../order';\nimport { createOrderBillingAddressSelectorFactory } from '../order-billing-address';\nimport {\n createPaymentMethodSelectorFactory,\n createPaymentSelectorFactory,\n createPaymentStrategySelectorFactory,\n} from '../payment';\nimport { createInstrumentSelectorFactory } from '../payment/instrument';\nimport { createRemoteCheckoutSelectorFactory } from '../remote-checkout';\nimport {\n createConsignmentSelectorFactory,\n createPickupOptionSelectorFactory,\n createShippingAddressSelectorFactory,\n createShippingCountrySelectorFactory,\n createShippingStrategySelectorFactory,\n} from '../shipping';\nimport { createSignInEmailSelectorFactory } from '../signin-email';\nimport { createStoreCreditSelectorFactory } from '../store-credit';\nimport { createSubscriptionsSelectorFactory } from '../subscription';\n\nimport { createCheckoutSelectorFactory } from './checkout-selector';\nimport { CheckoutStoreOptions } from './checkout-store';\nimport CheckoutStoreState from './checkout-store-state';\nimport InternalCheckoutSelectors from './internal-checkout-selectors';\n\nexport type InternalCheckoutSelectorsFactory = (\n state: CheckoutStoreState,\n options?: CheckoutStoreOptions,\n) => InternalCheckoutSelectors;\n\nexport function createInternalCheckoutSelectorsFactory(): InternalCheckoutSelectorsFactory {\n const createBillingAddressSelector = createBillingAddressSelectorFactory();\n const createCartSelector = createCartSelectorFactory();\n const createCheckoutButtonSelector = createCheckoutButtonSelectorFactory();\n const createConfigSelector = createConfigSelectorFactory();\n const createCountrySelector = createCountrySelectorFactory();\n const createCouponSelector = createCouponSelectorFactory();\n const createCustomerSelector = createCustomerSelectorFactory();\n const createCustomerStrategySelector = createCustomerStrategySelectorFactory();\n const createGiftCertificateSelector = createGiftCertificateSelectorFactory();\n const createInstrumentSelector = createInstrumentSelectorFactory();\n const createFormSelector = createFormSelectorFactory();\n const createPaymentMethodSelector = createPaymentMethodSelectorFactory();\n const createPaymentStrategySelector = createPaymentStrategySelectorFactory();\n const createPickupOptionSelector = createPickupOptionSelectorFactory();\n const createRemoteCheckoutSelector = createRemoteCheckoutSelectorFactory();\n const createShippingAddressSelector = createShippingAddressSelectorFactory();\n const createShippingCountrySelector = createShippingCountrySelectorFactory();\n const createShippingStrategySelector = createShippingStrategySelectorFactory();\n const createConsignmentSelector = createConsignmentSelectorFactory();\n const createCheckoutSelector = createCheckoutSelectorFactory();\n const createOrderSelector = createOrderSelectorFactory();\n const createOrderBillingAddressSelector = createOrderBillingAddressSelectorFactory();\n const createPaymentSelector = createPaymentSelectorFactory();\n const createStoreCreditSelector = createStoreCreditSelectorFactory();\n const createSubscriptionsSelector = createSubscriptionsSelectorFactory();\n const createSignInEmailSelector = createSignInEmailSelectorFactory();\n const createExtensionSelector = createExtensionSelectorFactory();\n\n return (state, options = {}) => {\n const billingAddress = createBillingAddressSelector(state.billingAddress);\n const cart = createCartSelector(state.cart);\n const checkoutButton = createCheckoutButtonSelector(state.checkoutButton);\n const countries = createCountrySelector(state.countries);\n const coupons = createCouponSelector(state.coupons);\n const customer = createCustomerSelector(state.customer);\n const customerStrategies = createCustomerStrategySelector(state.customerStrategies);\n const extensions = createExtensionSelector(state.extensions);\n const form = createFormSelector(state.formFields);\n const giftCertificates = createGiftCertificateSelector(state.giftCertificates);\n const instruments = createInstrumentSelector(state.instruments);\n const orderBillingAddress = createOrderBillingAddressSelector(state.orderBillingAddress);\n const paymentMethods = createPaymentMethodSelector(state.paymentMethods);\n const paymentStrategies = createPaymentStrategySelector(state.paymentStrategies);\n const pickupOptions = createPickupOptionSelector(state.pickupOptions);\n const remoteCheckout = createRemoteCheckoutSelector(state.remoteCheckout);\n const shippingAddress = createShippingAddressSelector(state.consignments);\n const shippingCountries = createShippingCountrySelector(state.shippingCountries);\n const shippingStrategies = createShippingStrategySelector(state.shippingStrategies);\n const subscriptions = createSubscriptionsSelector(state.subscriptions);\n const storeCredit = createStoreCreditSelector(state.storeCredit);\n const signInEmail = createSignInEmailSelector(state.signInEmail);\n\n // Compose selectors\n const consignments = createConsignmentSelector(state.consignments, cart);\n const checkout = createCheckoutSelector(\n state.checkout,\n billingAddress,\n cart,\n consignments,\n coupons,\n customer,\n giftCertificates,\n );\n const order = createOrderSelector(state.order, orderBillingAddress, coupons);\n const payment = createPaymentSelector(checkout, order);\n const config = createConfigSelector(state.config, state.formFields);\n\n const selectors = {\n billingAddress,\n cart,\n checkout,\n checkoutButton,\n config,\n consignments,\n countries,\n coupons,\n customer,\n customerStrategies,\n extensions,\n form,\n giftCertificates,\n instruments,\n order,\n orderBillingAddress,\n payment,\n paymentMethods,\n paymentStrategies,\n pickupOptions,\n remoteCheckout,\n shippingAddress,\n shippingCountries,\n shippingStrategies,\n signInEmail,\n subscriptions,\n storeCredit,\n };\n\n return options.shouldWarnMutation ? createFreezeProxies(selectors) : selectors;\n };\n}\n\nexport default function createInternalCheckoutSelectors(\n state: CheckoutStoreState,\n options?: CheckoutStoreOptions,\n): InternalCheckoutSelectors {\n return createInternalCheckoutSelectorsFactory()(state, options);\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport BillingAddress from './billing-address';\nimport BillingAddressState, { DEFAULT_STATE } from './billing-address-state';\n\nexport default interface BillingAddressSelector {\n getBillingAddress(): BillingAddress | undefined;\n getBillingAddressOrThrow(): BillingAddress;\n getUpdateError(): Error | undefined;\n getContinueAsGuestError(): Error | undefined;\n getLoadError(): Error | undefined;\n isUpdating(): boolean;\n isContinuingAsGuest(): boolean;\n isLoading(): boolean;\n}\n\nexport type BillingAddressSelectorFactory = (state: BillingAddressState) => BillingAddressSelector;\n\nexport function createBillingAddressSelectorFactory(): BillingAddressSelectorFactory {\n const getBillingAddress = createSelector(\n (state: BillingAddressState) => state.data,\n (data) => () => data,\n );\n\n const getBillingAddressOrThrow = createSelector(\n getBillingAddress,\n (getBillingAddress) => () => {\n return guard(\n getBillingAddress(),\n () => new MissingDataError(MissingDataErrorType.MissingBillingAddress),\n );\n },\n );\n\n const getUpdateError = createSelector(\n (state: BillingAddressState) => state.errors.updateError,\n (error) => () => error,\n );\n\n const getContinueAsGuestError = createSelector(\n (state: BillingAddressState) => state.errors.continueAsGuestError,\n (error) => () => error,\n );\n\n const getLoadError = createSelector(\n (state: BillingAddressState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isUpdating = createSelector(\n (state: BillingAddressState) => !!state.statuses.isUpdating,\n (status) => () => status,\n );\n\n const isContinuingAsGuest = createSelector(\n (state: BillingAddressState) => !!state.statuses.isContinuingAsGuest,\n (status) => () => status,\n );\n\n const isLoading = createSelector(\n (state: BillingAddressState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne((state: BillingAddressState = DEFAULT_STATE): BillingAddressSelector => {\n return {\n getBillingAddress: getBillingAddress(state),\n getBillingAddressOrThrow: getBillingAddressOrThrow(state),\n getUpdateError: getUpdateError(state),\n getContinueAsGuestError: getContinueAsGuestError(state),\n getLoadError: getLoadError(state),\n isUpdating: isUpdating(state),\n isContinuingAsGuest: isContinuingAsGuest(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { memoize, memoizeOne } from '@bigcommerce/memoize';\nimport { find, some, values } from 'lodash';\n\nimport { createSelector } from '../common/selector';\n\nimport CheckoutButtonState, { DEFAULT_STATE } from './checkout-button-state';\nimport { CheckoutButtonMethodType } from './strategies';\n\nexport default interface CheckoutButtonSelector {\n getState(): CheckoutButtonState;\n isInitializing(methodId?: CheckoutButtonMethodType): boolean;\n isInitialized(methodId: CheckoutButtonMethodType, containerId?: string): boolean;\n isDeinitializing(methodId?: CheckoutButtonMethodType): boolean;\n getInitializeError(methodId?: CheckoutButtonMethodType): Error | undefined;\n getDeinitializeError(methodId?: CheckoutButtonMethodType): Error | undefined;\n}\n\nexport type CheckoutButtonSelectorFactory = (state: CheckoutButtonState) => CheckoutButtonSelector;\n\nexport function createCheckoutButtonSelectorFactory(): CheckoutButtonSelectorFactory {\n const getState = createSelector(\n (state: CheckoutButtonState) => state,\n (state) => () => state,\n );\n\n const isInitializing = createSelector(\n (state: CheckoutButtonState) => state.statuses,\n (statuses) =>\n memoize((methodId?: CheckoutButtonMethodType) => {\n if (methodId) {\n const method = statuses[methodId];\n\n return (method && method.isInitializing) === true;\n }\n\n return some(statuses, { isInitializing: true });\n }),\n );\n\n const isInitialized = createSelector(\n (state: CheckoutButtonState) => state.data,\n (data) =>\n memoize((methodId: CheckoutButtonMethodType, containerId?: string) => {\n const method = data[methodId];\n\n if (!method) {\n return false;\n }\n\n if (!containerId) {\n return some(\n method.initializedContainers,\n (isInitialized) => isInitialized === true,\n );\n }\n\n return method.initializedContainers[containerId] === true;\n }),\n );\n\n const isDeinitializing = createSelector(\n (state: CheckoutButtonState) => state.statuses,\n (statuses) =>\n memoize((methodId?: CheckoutButtonMethodType) => {\n if (methodId) {\n const method = statuses[methodId];\n\n return (method && method.isDeinitializing) === true;\n }\n\n return some(statuses, { isDeinitializing: true });\n }),\n );\n\n const getInitializeError = createSelector(\n (state: CheckoutButtonState) => state.errors,\n (errors) =>\n memoize((methodId?: CheckoutButtonMethodType) => {\n const method = methodId\n ? errors[methodId]\n : find(values(errors), (method) => !!(method && method.initializeError));\n\n return method && method.initializeError;\n }),\n );\n\n const getDeinitializeError = createSelector(\n (state: CheckoutButtonState) => state.errors,\n (errors) =>\n memoize((methodId?: CheckoutButtonMethodType) => {\n const method = methodId\n ? errors[methodId]\n : find(values(errors), (method) => !!(method && method.deinitializeError));\n\n return method && method.deinitializeError;\n }),\n );\n\n return memoizeOne((state: CheckoutButtonState = DEFAULT_STATE): CheckoutButtonSelector => {\n return {\n getState: getState(state),\n isInitializing: isInitializing(state),\n isInitialized: isInitialized(state),\n isDeinitializing: isDeinitializing(state),\n getInitializeError: getInitializeError(state),\n getDeinitializeError: getDeinitializeError(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { RequestError } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\n\nimport Coupon from './coupon';\nimport CouponState, { DEFAULT_STATE } from './coupon-state';\n\nexport default interface CouponSelector {\n getCoupons(): Coupon[] | undefined;\n getRemoveError(): RequestError | undefined;\n getApplyError(): RequestError | undefined;\n isApplying(): boolean;\n isRemoving(): boolean;\n}\n\nexport type CouponSelectorFactory = (state: CouponState) => CouponSelector;\n\nexport function createCouponSelectorFactory(): CouponSelectorFactory {\n const getCoupons = createSelector(\n (state: CouponState) => state.data,\n (data) => () => data,\n );\n\n const getRemoveError = createSelector(\n (state: CouponState) => state.errors.removeCouponError,\n (error) => () => error,\n );\n\n const getApplyError = createSelector(\n (state: CouponState) => state.errors.applyCouponError,\n (error) => () => error,\n );\n\n const isApplying = createSelector(\n (state: CouponState) => !!state.statuses.isApplyingCoupon,\n (status) => () => status,\n );\n\n const isRemoving = createSelector(\n (state: CouponState) => !!state.statuses.isRemovingCoupon,\n (status) => () => status,\n );\n\n return memoizeOne((state: CouponState = DEFAULT_STATE): CouponSelector => {\n return {\n getCoupons: getCoupons(state),\n getRemoveError: getRemoveError(state),\n getApplyError: getApplyError(state),\n isApplying: isApplying(state),\n isRemoving: isRemoving(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport Customer from './customer';\nimport CustomerState, { DEFAULT_STATE } from './customer-state';\n\nexport default interface CustomerSelector {\n getCustomer(): Customer | undefined;\n getCustomerOrThrow(): Customer;\n getCreateAccountError(): Error | undefined;\n isCreatingCustomerAccount(): boolean;\n getCreateAddressError(): Error | undefined;\n isCreatingCustomerAddress(): boolean;\n}\n\nexport type CustomerSelectorFactory = (state: CustomerState) => CustomerSelector;\n\nexport function createCustomerSelectorFactory(): CustomerSelectorFactory {\n const getCustomer = createSelector(\n (state: CustomerState) => state.data,\n (customer) => () => customer,\n );\n\n const getCustomerOrThrow = createSelector(getCustomer, (getCustomer) => () => {\n return guard(\n getCustomer(),\n () => new MissingDataError(MissingDataErrorType.MissingCustomer),\n );\n });\n\n const getCreateAccountError = createSelector(\n (state: CustomerState) => state.errors.createError,\n (error) => () => error,\n );\n\n const isCreatingCustomerAccount = createSelector(\n (state: CustomerState) => !!state.statuses.isCreating,\n (status) => () => status,\n );\n\n const getCreateAddressError = createSelector(\n (state: CustomerState) => state.errors.createAddressError,\n (error) => () => error,\n );\n\n const isCreatingCustomerAddress = createSelector(\n (state: CustomerState) => !!state.statuses.isCreatingAddress,\n (status) => () => status,\n );\n\n return memoizeOne((state: CustomerState = DEFAULT_STATE): CustomerSelector => {\n return {\n getCustomer: getCustomer(state),\n getCustomerOrThrow: getCustomerOrThrow(state),\n getCreateAccountError: getCreateAccountError(state),\n isCreatingCustomerAccount: isCreatingCustomerAccount(state),\n getCreateAddressError: getCreateAddressError(state),\n isCreatingCustomerAddress: isCreatingCustomerAddress(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport RemoteCheckoutState, {\n DEFAULT_STATE,\n RemoteCheckoutStateData,\n} from './remote-checkout-state';\n\nexport default interface RemoteCheckoutSelector {\n getCheckout(\n methodId: TMethodId,\n ): RemoteCheckoutStateData[TMethodId] | undefined;\n}\n\nexport type RemoteCheckoutSelectorFactory = (state: RemoteCheckoutState) => RemoteCheckoutSelector;\n\nexport function createRemoteCheckoutSelectorFactory(): RemoteCheckoutSelectorFactory {\n const getCheckout = createSelector(\n (state: RemoteCheckoutState) => state.data,\n (data) =>\n (methodId: TMethodId) => {\n return data[methodId];\n },\n );\n\n return memoizeOne((state: RemoteCheckoutState = DEFAULT_STATE): RemoteCheckoutSelector => {\n return {\n getCheckout: getCheckout(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { Address } from '../address';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport ConsignmentState, { DEFAULT_STATE } from './consignment-state';\n\nexport default interface ShippingAddressSelector {\n getShippingAddress(): Address | undefined;\n getShippingAddressOrThrow(): Address;\n getShippingAddresses(): Address[];\n getShippingAddressesOrThrow(): Address[];\n}\n\nexport type ShippingAddressSelectorFactory = (state: ConsignmentState) => ShippingAddressSelector;\n\nexport function createShippingAddressSelectorFactory(): ShippingAddressSelectorFactory {\n const getShippingAddress = createSelector(\n (state: ConsignmentState) => state.data,\n (consignments) => () => {\n const shippingConsignment = consignments?.find(\n (consignment) => !consignment.selectedPickupOption,\n );\n\n return shippingConsignment?.shippingAddress;\n },\n );\n\n const getShippingAddressOrThrow = createSelector(\n getShippingAddress,\n (getShippingAddress) => () => {\n return guard(\n getShippingAddress(),\n () => new MissingDataError(MissingDataErrorType.MissingShippingAddress),\n );\n },\n );\n\n const getShippingAddresses = createSelector(\n (state: ConsignmentState) => state.data,\n (consignments) => () => {\n const shippingConsignments = consignments?.filter(\n (consignment) => !consignment.selectedPickupOption,\n );\n\n return shippingConsignments\n ? shippingConsignments.map((consignment) => consignment.shippingAddress)\n : [];\n },\n );\n\n const getShippingAddressesOrThrow = createSelector(\n getShippingAddresses,\n (getShippingAddresses) => () => {\n return guard(\n getShippingAddresses(),\n () => new MissingDataError(MissingDataErrorType.MissingShippingAddress),\n );\n },\n );\n\n return memoizeOne((state: ConsignmentState = DEFAULT_STATE): ShippingAddressSelector => {\n return {\n getShippingAddress: getShippingAddress(state),\n getShippingAddressOrThrow: getShippingAddressOrThrow(state),\n getShippingAddresses: getShippingAddresses(state),\n getShippingAddressesOrThrow: getShippingAddressesOrThrow(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport OrderBillingAddressState, {\n DEFAULT_STATE,\n OrderBillingAddress,\n} from './order-billing-address-state';\n\nexport default interface OrderBillingAddressSelector {\n getOrderBillingAddress(): OrderBillingAddress | undefined;\n}\n\nexport type OrderBillingAddressSelectorFactory = (\n state: OrderBillingAddressState,\n) => OrderBillingAddressSelector;\n\nexport function createOrderBillingAddressSelectorFactory(): OrderBillingAddressSelectorFactory {\n const getOrderBillingAddress = createSelector(\n (state: OrderBillingAddressState) => state.data,\n (data) => () => data,\n );\n\n return memoizeOne(\n (state: OrderBillingAddressState = DEFAULT_STATE): OrderBillingAddressSelector => {\n return {\n getOrderBillingAddress: getOrderBillingAddress(state),\n };\n },\n );\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { find } from 'lodash';\n\nimport { CheckoutSelector } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\nimport { GatewayOrderPayment, OrderSelector } from '../order';\n\nimport PaymentMethod from './payment-method';\nimport { HOSTED } from './payment-method-types';\nimport { ACKNOWLEDGE, FINALIZE } from './payment-status-types';\n\nexport default interface PaymentSelector {\n getPaymentId(): { providerId: string; gatewayId?: string } | undefined;\n getPaymentIdOrThrow(): { providerId: string; gatewayId?: string };\n getPaymentStatus(): string | undefined;\n getPaymentStatusOrThrow(): string;\n getPaymentToken(): string | undefined;\n getPaymentTokenOrThrow(): string;\n getPaymentRedirectUrl(): string | undefined;\n getPaymentRedirectUrlOrThrow(): string;\n isPaymentDataRequired(useStoreCredit?: boolean): boolean;\n isPaymentDataSubmitted(paymentMethod?: PaymentMethod): boolean;\n}\n\nexport type PaymentSelectorFactory = (\n checkout: CheckoutSelector,\n order: OrderSelector,\n) => PaymentSelector;\n\ninterface PaymentSelectorDependencies {\n checkout: CheckoutSelector;\n order: OrderSelector;\n}\n\nexport function createPaymentSelectorFactory(): PaymentSelectorFactory {\n const getInternalPayment = createSelector(\n ({ order }: PaymentSelectorDependencies) => order.getOrderMeta,\n (getOrderMeta) => () => {\n const meta = getOrderMeta();\n\n return meta && meta.payment;\n },\n );\n\n const getGatewayPayment = createSelector(\n ({ order }: PaymentSelectorDependencies) => order.getOrder,\n (getOrder) => () => {\n const order = getOrder();\n\n return find(\n order && order.payments,\n ({ providerId }) =>\n providerId !== 'giftcertificate' && providerId !== 'storecredit',\n ) as GatewayOrderPayment;\n },\n );\n\n const getHostedPayment = createSelector(\n ({ checkout }: PaymentSelectorDependencies) => checkout.getCheckout,\n (getCheckout) => () => {\n const checkout = getCheckout();\n\n return find(\n checkout && checkout.payments,\n ({ providerType }) => providerType === HOSTED,\n );\n },\n );\n\n const getPaymentId = createSelector(\n getInternalPayment,\n getHostedPayment,\n getGatewayPayment,\n (getInternalPayment, getHostedPayment, getGatewayPayment) => () => {\n const internalPayment = getInternalPayment();\n\n if (internalPayment && internalPayment.id) {\n return {\n providerId: internalPayment.id,\n gatewayId: internalPayment.gateway,\n };\n }\n\n const payment = getHostedPayment() || getGatewayPayment();\n\n if (payment && payment.providerId) {\n return {\n providerId: payment.providerId,\n gatewayId: payment.gatewayId,\n };\n }\n },\n );\n\n const getPaymentIdOrThrow = createSelector(getPaymentId, (getPaymentId) => () => {\n return guard(\n getPaymentId(),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentId),\n );\n });\n\n const getPaymentStatus = createSelector(\n getInternalPayment,\n getHostedPayment,\n getGatewayPayment,\n (getInternalPayment, getHostedPayment, getGatewayPayment) => () => {\n const internalPayment = getInternalPayment();\n\n if (internalPayment && internalPayment.status) {\n return internalPayment.status.replace('PAYMENT_STATUS_', '');\n }\n\n const payment = getHostedPayment() || getGatewayPayment();\n\n if (payment) {\n return payment.detail.step;\n }\n },\n );\n\n const getPaymentStatusOrThrow = createSelector(getPaymentStatus, (getPaymentStatus) => () => {\n return guard(\n getPaymentStatus(),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentStatus),\n );\n });\n\n const getPaymentToken = createSelector(\n ({ order }: PaymentSelectorDependencies) => order.getOrderMeta,\n (getOrderMeta) => () => {\n const meta = getOrderMeta();\n\n return meta && meta.token;\n },\n );\n\n const getPaymentTokenOrThrow = createSelector(getPaymentToken, (getPaymentToken) => () => {\n return guard(\n getPaymentToken(),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentToken),\n );\n });\n\n const getPaymentRedirectUrl = createSelector(getInternalPayment, (getInternalPayment) => () => {\n const payment = getInternalPayment();\n\n return payment && payment.redirectUrl;\n });\n\n const getPaymentRedirectUrlOrThrow = createSelector(\n getPaymentRedirectUrl,\n (getPaymentRedirectUrl) => () => {\n return guard(\n getPaymentRedirectUrl(),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentRedirectUrl),\n );\n },\n );\n\n const isPaymentDataRequired = createSelector(\n ({ checkout }: PaymentSelectorDependencies) => checkout.getOutstandingBalance,\n (getOutstandingBalance) =>\n (useStoreCredit = false) => {\n const grandTotal = getOutstandingBalance(useStoreCredit);\n\n return grandTotal ? grandTotal > 0 : false;\n },\n );\n\n const isPaymentDataSubmitted = createSelector(\n getPaymentStatus,\n (getPaymentStatus) => (paymentMethod?: PaymentMethod) => {\n if (paymentMethod && paymentMethod.nonce) {\n return true;\n }\n\n return getPaymentStatus() === ACKNOWLEDGE || getPaymentStatus() === FINALIZE;\n },\n );\n\n return memoizeOne((checkout: CheckoutSelector, order: OrderSelector): PaymentSelector => {\n return {\n getPaymentId: getPaymentId({ checkout, order }),\n getPaymentIdOrThrow: getPaymentIdOrThrow({ checkout, order }),\n getPaymentStatus: getPaymentStatus({ checkout, order }),\n getPaymentStatusOrThrow: getPaymentStatusOrThrow({ checkout, order }),\n getPaymentToken: getPaymentToken({ checkout, order }),\n getPaymentTokenOrThrow: getPaymentTokenOrThrow({ checkout, order }),\n getPaymentRedirectUrl: getPaymentRedirectUrl({ checkout, order }),\n getPaymentRedirectUrlOrThrow: getPaymentRedirectUrlOrThrow({ checkout, order }),\n isPaymentDataRequired: isPaymentDataRequired({ checkout, order }),\n isPaymentDataSubmitted: isPaymentDataSubmitted({ checkout, order }),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport { SignInEmail } from './signin-email';\nimport SignInEmailState, { DEFAULT_STATE } from './signin-email-state';\n\nexport default interface SignInEmailSelector {\n getEmail(): SignInEmail | undefined;\n getSendError(): Error | undefined;\n isSending(): boolean;\n}\n\nexport type SignInEmailSelectorFactory = (state: SignInEmailState) => SignInEmailSelector;\n\nexport function createSignInEmailSelectorFactory(): SignInEmailSelectorFactory {\n const getEmail = createSelector(\n (state: SignInEmailState) => state.data,\n (signInEmail) => () => signInEmail,\n );\n\n const getSendError = createSelector(\n (state: SignInEmailState) => state.errors.sendError,\n (error) => () => error,\n );\n\n const isSending = createSelector(\n (state: SignInEmailState) => !!state.statuses.isSending,\n (status) => () => status,\n );\n\n return memoizeOne((state: SignInEmailState = DEFAULT_STATE): SignInEmailSelector => {\n return {\n getEmail: getEmail(state),\n getSendError: getSendError(state),\n isSending: isSending(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport Cart from './cart';\nimport CartState, { DEFAULT_STATE } from './cart-state';\n\nexport default interface CartSelector {\n getCart(): Cart | undefined;\n getCartOrThrow(): Cart;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type CartSelectorFactory = (state: CartState) => CartSelector;\n\nexport function createCartSelectorFactory() {\n const getCart = createSelector(\n (state: CartState) => state.data,\n (cart) => () => cart,\n );\n\n const getCartOrThrow = createSelector(getCart, (getCart) => () => {\n return guard(getCart(), () => new MissingDataError(MissingDataErrorType.MissingCart));\n });\n\n const getLoadError = createSelector(\n (state: CartState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: CartState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne((state: CartState = DEFAULT_STATE): CartSelector => {\n return {\n getCart: getCart(state),\n getCartOrThrow: getCartOrThrow(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\nimport { FormFieldsState } from '../form';\n\nimport Config, { ContextConfig, FlashMessage, FlashMessageType, StoreConfig } from './config';\nimport ConfigState, { DEFAULT_STATE } from './config-state';\n\nexport default interface ConfigSelector {\n getConfig(): Config | undefined;\n getFlashMessages(type?: FlashMessageType): FlashMessage[] | undefined;\n getStoreConfig(): StoreConfig | undefined;\n getStoreConfigOrThrow(): StoreConfig;\n getContextConfig(): ContextConfig | undefined;\n getExternalSource(): string | undefined;\n getHost(): string | undefined;\n getLocale(): string | undefined;\n getVariantIdentificationToken(): string | undefined;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type ConfigSelectorFactory = (\n state: ConfigState,\n formState: FormFieldsState,\n) => ConfigSelector;\n\ninterface ConfigSelectorDependencies {\n formState: FormFieldsState;\n}\n\nexport function createConfigSelectorFactory(): ConfigSelectorFactory {\n const getConfig = createSelector(\n (state: ConfigState) => state.data,\n (data) => () => data,\n );\n\n const getFlashMessages = createSelector(\n (state: ConfigState) => state.data,\n (data) => (filterType?: FlashMessageType) => {\n if (!data) {\n return;\n }\n\n const { flashMessages } = data.context;\n\n if (!flashMessages) {\n return;\n }\n\n return filterType !== undefined\n ? flashMessages.filter(({ type }) => filterType === type)\n : flashMessages;\n },\n );\n\n const getStoreConfig = createSelector(\n (state: ConfigState) => state.data,\n (_: ConfigState, { formState }: ConfigSelectorDependencies) => formState && formState.data,\n (data, formFields) => () =>\n data && formFields\n ? {\n ...data.storeConfig,\n formFields,\n }\n : undefined,\n );\n\n const getStoreConfigOrThrow = createSelector(getStoreConfig, (getStoreConfig) => () => {\n return guard(\n getStoreConfig(),\n () => new MissingDataError(MissingDataErrorType.MissingCheckoutConfig),\n );\n });\n\n const getContextConfig = createSelector(\n (state: ConfigState) => state.data && state.data.context,\n (data) => () => data,\n );\n\n const getExternalSource = createSelector(\n (state: ConfigState) => state.meta && state.meta.externalSource,\n (data) => () => data,\n );\n\n const getHost = createSelector(\n (state: ConfigState) => state.meta?.host,\n (data) => () => data,\n );\n\n const getLocale = createSelector(\n (state: ConfigState) => state.meta?.locale,\n (data) => () => data,\n );\n\n const getVariantIdentificationToken = createSelector(\n (state: ConfigState) => state.meta && state.meta.variantIdentificationToken,\n (data) => () => data,\n );\n\n const getLoadError = createSelector(\n (state: ConfigState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: ConfigState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne(\n (state: ConfigState = DEFAULT_STATE, formState: FormFieldsState): ConfigSelector => {\n return {\n getConfig: getConfig(state),\n getFlashMessages: getFlashMessages(state),\n getStoreConfig: getStoreConfig(state, { formState }),\n getStoreConfigOrThrow: getStoreConfigOrThrow(state, { formState }),\n getContextConfig: getContextConfig(state),\n getExternalSource: getExternalSource(state),\n getHost: getHost(state),\n getLocale: getLocale(state),\n getVariantIdentificationToken: getVariantIdentificationToken(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n },\n );\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport Country from './country';\nimport CountryState, { DEFAULT_STATE } from './country-state';\n\nexport default interface CountrySelector {\n getCountries(): Country[] | undefined;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type CountrySelectorFactory = (state: CountryState) => CountrySelector;\n\nexport function createCountrySelectorFactory(): CountrySelectorFactory {\n const getCountries = createSelector(\n (state: CountryState) => state.data,\n (countries) => () => countries,\n );\n\n const getLoadError = createSelector(\n (state: CountryState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: CountryState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne((state: CountryState = DEFAULT_STATE): CountrySelector => {\n return {\n getCountries: getCountries(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport CustomerStrategyState, { DEFAULT_STATE } from './customer-strategy-state';\n\nexport default interface CustomerStrategySelector {\n getSignInError(methodId?: string): Error | undefined;\n getSignOutError(methodId?: string): Error | undefined;\n getExecutePaymentMethodCheckoutError(methodId?: string): Error | undefined;\n getInitializeError(methodId?: string): Error | undefined;\n getWidgetInteractionError(methodId?: string): Error | undefined;\n isSigningIn(methodId?: string): boolean;\n isSigningOut(methodId?: string): boolean;\n isExecutingPaymentMethodCheckout(methodId?: string): boolean;\n isInitializing(methodId?: string): boolean;\n isInitialized(methodId: string): boolean;\n isWidgetInteracting(methodId?: string): boolean;\n}\n\nexport type CustomerStrategySelectorFactory = (\n state: CustomerStrategyState,\n) => CustomerStrategySelector;\n\nexport function createCustomerStrategySelectorFactory(): CustomerStrategySelectorFactory {\n const getSignInError = createSelector(\n (state: CustomerStrategyState) => state.errors.signInMethodId,\n (state: CustomerStrategyState) => state.errors.signInError,\n (signInMethodId, signInError) => (methodId?: string) => {\n if (methodId && signInMethodId !== methodId) {\n return;\n }\n\n return signInError;\n },\n );\n\n const getSignOutError = createSelector(\n (state: CustomerStrategyState) => state.errors.signOutMethodId,\n (state: CustomerStrategyState) => state.errors.signOutError,\n (signOutMethodId, signOutError) => (methodId?: string) => {\n if (methodId && signOutMethodId !== methodId) {\n return;\n }\n\n return signOutError;\n },\n );\n\n const getExecutePaymentMethodCheckoutError = createSelector(\n (state: CustomerStrategyState) => state.errors.executePaymentMethodCheckoutMethodId,\n (state: CustomerStrategyState) => state.errors.executePaymentMethodCheckoutError,\n (executePaymentMethodCheckoutMethodId, executePaymentMethodCheckoutError) =>\n (methodId?: string) => {\n if (methodId && executePaymentMethodCheckoutMethodId !== methodId) {\n return;\n }\n\n return executePaymentMethodCheckoutError;\n },\n );\n\n const getInitializeError = createSelector(\n (state: CustomerStrategyState) => state.errors.initializeMethodId,\n (state: CustomerStrategyState) => state.errors.initializeErrors,\n (initializeMethodId, initializeErrors) => (methodId?: string) => {\n if (!initializeMethodId || !initializeErrors) {\n return;\n }\n\n if (methodId) {\n return initializeErrors[methodId];\n }\n\n return initializeErrors[initializeMethodId];\n },\n );\n\n const getWidgetInteractionError = createSelector(\n (state: CustomerStrategyState) => state.errors.widgetInteractionMethodId,\n (state: CustomerStrategyState) => state.errors.widgetInteractionError,\n (widgetInteractionMethodId, widgetInteractionError) => (methodId?: string) => {\n if (methodId && widgetInteractionMethodId !== methodId) {\n return;\n }\n\n return widgetInteractionError;\n },\n );\n\n const isSigningIn = createSelector(\n (state: CustomerStrategyState) => state.statuses.signInMethodId,\n (state: CustomerStrategyState) => state.statuses.isSigningIn,\n (signInMethodId, isSigningIn) => (methodId?: string) => {\n if (methodId && signInMethodId !== methodId) {\n return false;\n }\n\n return !!isSigningIn;\n },\n );\n\n const isSigningOut = createSelector(\n (state: CustomerStrategyState) => state.statuses.signOutMethodId,\n (state: CustomerStrategyState) => state.statuses.isSigningOut,\n (signOutMethodId, isSigningOut) => (methodId?: string) => {\n if (methodId && signOutMethodId !== methodId) {\n return false;\n }\n\n return !!isSigningOut;\n },\n );\n\n const isExecutingPaymentMethodCheckout = createSelector(\n (state: CustomerStrategyState) => state.statuses.executePaymentMethodCheckoutMethodId,\n (state: CustomerStrategyState) => state.statuses.isExecutingPaymentMethodCheckout,\n (executePaymentMethodCheckoutMethodId, isExecutingPaymentMethodCheckout) =>\n (methodId?: string) => {\n if (methodId && executePaymentMethodCheckoutMethodId !== methodId) {\n return false;\n }\n\n return !!isExecutingPaymentMethodCheckout;\n },\n );\n\n const isInitializing = createSelector(\n (state: CustomerStrategyState) => state.statuses.initializeMethodId,\n (state: CustomerStrategyState) => state.statuses.isInitializing,\n (initializeMethodId, isInitializing) => (methodId?: string) => {\n if (methodId && initializeMethodId !== methodId) {\n return false;\n }\n\n return !!isInitializing;\n },\n );\n\n const isInitialized = createSelector(\n (state: CustomerStrategyState) => state.data,\n (data) => (methodId: string) => {\n return !!(data[methodId] && data[methodId].isInitialized);\n },\n );\n\n const isWidgetInteracting = createSelector(\n (state: CustomerStrategyState) => state.statuses.widgetInteractionMethodId,\n (state: CustomerStrategyState) => state.statuses.isWidgetInteracting,\n (widgetInteractionMethodId, isWidgetInteracting) => (methodId?: string) => {\n if (methodId && widgetInteractionMethodId !== methodId) {\n return false;\n }\n\n return !!isWidgetInteracting;\n },\n );\n\n return memoizeOne((state: CustomerStrategyState = DEFAULT_STATE): CustomerStrategySelector => {\n return {\n getSignInError: getSignInError(state),\n getSignOutError: getSignOutError(state),\n getExecutePaymentMethodCheckoutError: getExecutePaymentMethodCheckoutError(state),\n getInitializeError: getInitializeError(state),\n getWidgetInteractionError: getWidgetInteractionError(state),\n isSigningIn: isSigningIn(state),\n isSigningOut: isSigningOut(state),\n isExecutingPaymentMethodCheckout: isExecutingPaymentMethodCheckout(state),\n isInitializing: isInitializing(state),\n isInitialized: isInitialized(state),\n isWidgetInteracting: isWidgetInteracting(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { StorefrontErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RequestError } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\n\nimport GiftCertificate from './gift-certificate';\nimport GiftCertificateState, { DEFAULT_STATE } from './gift-certificate-state';\n\nexport default interface GiftCertificateSelector {\n getGiftCertificates(): GiftCertificate[] | undefined;\n getRemoveError(): RequestError | undefined;\n getApplyError(): RequestError | undefined;\n isApplying(): boolean;\n isRemoving(): boolean;\n}\n\nexport type GiftCertificateSelectorFactory = (\n state: GiftCertificateState,\n) => GiftCertificateSelector;\n\nexport function createGiftCertificateSelectorFactory(): GiftCertificateSelectorFactory {\n const getGiftCertificates = createSelector(\n (state: GiftCertificateState) => state.data,\n (data) => () => data,\n );\n\n const getRemoveError = createSelector(\n (state: GiftCertificateState) => state.errors.removeGiftCertificateError,\n (error) => () => error,\n );\n\n const getApplyError = createSelector(\n (state: GiftCertificateState) => state.errors.applyGiftCertificateError,\n (error) => () => error,\n );\n\n const isApplying = createSelector(\n (state: GiftCertificateState) => !!state.statuses.isApplyingGiftCertificate,\n (status) => () => status,\n );\n\n const isRemoving = createSelector(\n (state: GiftCertificateState) => !!state.statuses.isRemovingGiftCertificate,\n (status) => () => status,\n );\n\n return memoizeOne((state: GiftCertificateState = DEFAULT_STATE): GiftCertificateSelector => {\n return {\n getGiftCertificates: getGiftCertificates(state),\n getRemoveError: getRemoveError(state),\n getApplyError: getApplyError(state),\n isApplying: isApplying(state),\n isRemoving: isRemoving(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { filter, flatMap, isMatch, values } from 'lodash';\n\nimport { MissingDataError, MissingDataErrorType } from '../../common/error/errors';\nimport { createSelector } from '../../common/selector';\nimport { guard } from '../../common/utility';\nimport PaymentMethod from '../payment-method';\n\nimport PaymentInstrument, { CardInstrument } from './instrument';\nimport InstrumentState, { DEFAULT_STATE, InstrumentMeta } from './instrument-state';\nimport supportedInstruments from './supported-payment-instruments';\n\nexport default interface InstrumentSelector {\n getCardInstrument(instrumentId: string): CardInstrument | undefined;\n getCardInstrumentOrThrow(instrumentId: string): CardInstrument;\n getInstruments(): PaymentInstrument[] | undefined;\n getInstrumentsByPaymentMethod(paymentMethod: PaymentMethod): PaymentInstrument[] | undefined;\n getInstrumentsMeta(): InstrumentMeta | undefined;\n getLoadError(): Error | undefined;\n getDeleteError(instrumentId?: string): Error | undefined;\n isLoading(): boolean;\n isDeleting(instrumentId?: string): boolean;\n}\n\nexport type InstrumentSelectorFactory = (state: InstrumentState) => InstrumentSelector;\n\nexport function createInstrumentSelectorFactory(): InstrumentSelectorFactory {\n const getInstrumentsByPaymentMethod = createSelector(\n (state: InstrumentState) => state.data,\n (instruments) => (paymentMethod: PaymentMethod) => {\n if (!instruments) {\n return;\n }\n\n const paymentMethodKey = paymentMethod.gateway\n ? `${paymentMethod.gateway}.${paymentMethod.id}`\n : paymentMethod.id;\n\n const currentMethod = supportedInstruments[paymentMethodKey];\n\n if (!currentMethod) {\n return [];\n }\n\n return filter(instruments, currentMethod);\n },\n );\n\n const getCardInstrument = createSelector(\n (state: InstrumentState) => state.data,\n (instruments = []) =>\n (instrumentId: string) => {\n const cards = values(supportedInstruments);\n\n return instruments.find(\n (instrument): instrument is CardInstrument =>\n instrument.bigpayToken === instrumentId &&\n instrument.type === 'card' &&\n cards.some((card) => isMatch(instrument, card)),\n );\n },\n );\n\n const getCardInstrumentOrThrow = createSelector(\n getCardInstrument,\n (getCardInstrument) => (instrumentId: string) => {\n return guard(\n getCardInstrument(instrumentId),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentInstrument),\n );\n },\n );\n\n const getInstruments = createSelector(\n (state: InstrumentState) => state.data,\n (instruments) => () => {\n if (!instruments) {\n return;\n }\n\n const allSupportedInstruments = flatMap(supportedInstruments, (supportedProvider) =>\n filter(\n instruments,\n (instrument: PaymentInstrument): instrument is PaymentInstrument => {\n return isMatch(instrument, supportedProvider);\n },\n ),\n );\n\n return allSupportedInstruments;\n },\n );\n\n const getInstrumentsMeta = createSelector(\n (state: InstrumentState) => state.meta,\n (meta) => () => meta,\n );\n\n const getLoadError = createSelector(\n (state: InstrumentState) => state.errors.loadError,\n (loadError) => () => loadError,\n );\n\n const getDeleteError = createSelector(\n (state: InstrumentState) => state.errors.failedInstrument,\n (state: InstrumentState) => state.errors.deleteError,\n (failedInstrument, deleteError) => (instrumentId?: string) => {\n if (instrumentId && failedInstrument !== instrumentId) {\n return;\n }\n\n return deleteError;\n },\n );\n\n const isLoading = createSelector(\n (state: InstrumentState) => state.statuses.isLoading,\n (isLoading) => () => !!isLoading,\n );\n\n const isDeleting = createSelector(\n (state: InstrumentState) => state.statuses.deletingInstrument,\n (state: InstrumentState) => state.statuses.isDeleting,\n (deletingInstrument, isDeleting) => (instrumentId?: string) => {\n if (instrumentId && deletingInstrument !== instrumentId) {\n return false;\n }\n\n return !!isDeleting;\n },\n );\n\n return memoizeOne((state: InstrumentState = DEFAULT_STATE): InstrumentSelector => {\n return {\n getCardInstrument: getCardInstrument(state),\n getCardInstrumentOrThrow: getCardInstrumentOrThrow(state),\n getInstruments: getInstruments(state),\n getInstrumentsByPaymentMethod: getInstrumentsByPaymentMethod(state),\n getInstrumentsMeta: getInstrumentsMeta(state),\n getLoadError: getLoadError(state),\n getDeleteError: getDeleteError(state),\n isLoading: isLoading(state),\n isDeleting: isDeleting(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { find } from 'lodash';\n\nimport { createSelector } from '../common/selector';\nimport { Country } from '../geography';\n\nimport FormField from './form-field';\nimport FormFieldsState, { DEFAULT_STATE } from './form-fields-state';\n\nexport default interface FormSelector {\n getShippingAddressFields(countries: Country[] | undefined, countryCode: string): FormField[];\n getBillingAddressFields(countries: Country[] | undefined, countryCode: string): FormField[];\n getCustomerAccountFields(): FormField[];\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type FormSelectorFactory = (state: FormFieldsState) => FormSelector;\n\nexport function createFormSelectorFactory(): FormSelectorFactory {\n const getShippingAddressFields = createSelector(\n (state: FormFieldsState) => state.data,\n (formFields) =>\n (countries: Country[] = [], countryCode: string) => {\n const selectedCountry = find(countries, { code: countryCode });\n const fields = formFields ? formFields.shippingAddress : [];\n\n return fields.map((field: any) => processField(field, countries, selectedCountry));\n },\n );\n\n const getBillingAddressFields = createSelector(\n (state: FormFieldsState) => state.data,\n (formFields) =>\n (countries: Country[] = [], countryCode: string) => {\n const selectedCountry = find(countries, { code: countryCode });\n const fields = formFields ? formFields.billingAddress : [];\n\n return fields.map((field: any) => processField(field, countries, selectedCountry));\n },\n );\n\n const getCustomerAccountFields = createSelector(\n (state: FormFieldsState) => state.data,\n (formFields) => () => formFields ? formFields.customerAccount : [],\n );\n\n const getLoadError = createSelector(\n (state: FormFieldsState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: FormFieldsState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n function processField(\n field: FormField,\n countries: Country[],\n selectedCountry?: Country,\n ): FormField {\n if (field.name === 'countryCode') {\n return processCountry(field, countries, selectedCountry);\n }\n\n if (field.name === 'stateOrProvince') {\n return processProvince(field, selectedCountry);\n }\n\n if (field.name === 'postalCode') {\n return processsPostCode(field, selectedCountry);\n }\n\n return field;\n }\n\n function processCountry(\n field: FormField,\n countries: Country[] = [],\n country?: Country,\n ): FormField {\n if (!countries.length) {\n return field;\n }\n\n const { code = '' } = country || {};\n const items = countries.map(({ code, name }: any) => ({\n value: code,\n label: name,\n }));\n\n return {\n ...field,\n options: { items },\n default: code,\n type: 'array',\n fieldType: 'dropdown',\n itemtype: 'string',\n };\n }\n\n function processProvince(field: FormField, country?: Country): FormField {\n const { subdivisions = [], requiresState } = country || {};\n\n if (!subdivisions.length) {\n return {\n ...field,\n required: requiresState == null ? false : requiresState,\n };\n }\n\n const items = subdivisions.map(({ code, name }: any) => ({\n value: code,\n label: name,\n }));\n\n return {\n ...field,\n name: 'stateOrProvinceCode',\n options: { items },\n required: requiresState == null ? true : requiresState,\n type: 'array',\n fieldType: 'dropdown',\n itemtype: 'string',\n };\n }\n\n function processsPostCode(field: FormField, country?: Country): FormField {\n const { hasPostalCodes = [] } = country || {};\n\n if (hasPostalCodes === undefined) {\n return field;\n }\n\n return { ...field, required: Boolean(hasPostalCodes) };\n }\n\n return memoizeOne((state: FormFieldsState = DEFAULT_STATE): FormSelector => {\n return {\n getShippingAddressFields: getShippingAddressFields(state),\n getBillingAddressFields: getBillingAddressFields(state),\n getCustomerAccountFields: getCustomerAccountFields(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { find } from 'lodash';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport PaymentMethod from './payment-method';\nimport PaymentMethodMeta from './payment-method-meta';\nimport PaymentMethodState, { DEFAULT_STATE } from './payment-method-state';\n\nexport default interface PaymentMethodSelector {\n getPaymentMethods(): PaymentMethod[] | undefined;\n getPaymentMethodsMeta(): PaymentMethodMeta | undefined;\n getPaymentMethod(methodId: string, gatewayId?: string): PaymentMethod | undefined;\n getPaymentMethodOrThrow(methodId: string, gatewayId?: string): PaymentMethod;\n getLoadError(): Error | undefined;\n getLoadMethodError(methodId?: string): Error | undefined;\n isLoading(): boolean;\n isLoadingMethod(methodId?: string): boolean;\n}\n\nexport type PaymentMethodSelectorFactory = (state: PaymentMethodState) => PaymentMethodSelector;\n\nexport function createPaymentMethodSelectorFactory(): PaymentMethodSelectorFactory {\n const getPaymentMethods = createSelector(\n (state: PaymentMethodState) => state.data,\n (paymentMethods) => () => paymentMethods,\n );\n\n const getPaymentMethodsMeta = createSelector(\n (state: PaymentMethodState) => state.meta,\n (meta) => () => meta,\n );\n\n const getPaymentMethod = createSelector(\n (state: PaymentMethodState) => state.data,\n (paymentMethods) => (methodId: string, gatewayId?: string) => {\n return gatewayId\n ? find(paymentMethods, { id: methodId, gateway: gatewayId })\n : find(paymentMethods, { id: methodId });\n },\n );\n\n const getPaymentMethodOrThrow = createSelector(\n getPaymentMethod,\n (getPaymentMethod) => (methodId: string, gatewayId?: string) => {\n return guard(\n getPaymentMethod(methodId, gatewayId),\n () => new MissingDataError(MissingDataErrorType.MissingPaymentMethod),\n );\n },\n );\n\n const getLoadError = createSelector(\n (state: PaymentMethodState) => state.errors.loadError,\n (loadError) => () => loadError,\n );\n\n const getLoadMethodError = createSelector(\n (state: PaymentMethodState) => state.errors.loadMethodId,\n (state: PaymentMethodState) => state.errors.loadMethodError,\n (loadMethodId, loadMethodError) => (methodId?: string) => {\n if (methodId && loadMethodId !== methodId) {\n return;\n }\n\n return loadMethodError;\n },\n );\n\n const isLoading = createSelector(\n (state: PaymentMethodState) => state.statuses.isLoading,\n (isLoading) => () => !!isLoading,\n );\n\n const isLoadingMethod = createSelector(\n (state: PaymentMethodState) => state.statuses.loadMethodId,\n (state: PaymentMethodState) => state.statuses.isLoadingMethod,\n (loadMethodId, isLoadingMethod) => (methodId?: string) => {\n if (methodId && loadMethodId !== methodId) {\n return false;\n }\n\n return !!isLoadingMethod;\n },\n );\n\n return memoizeOne((state: PaymentMethodState = DEFAULT_STATE): PaymentMethodSelector => {\n return {\n getPaymentMethods: getPaymentMethods(state),\n getPaymentMethodsMeta: getPaymentMethodsMeta(state),\n getPaymentMethod: getPaymentMethod(state),\n getPaymentMethodOrThrow: getPaymentMethodOrThrow(state),\n getLoadError: getLoadError(state),\n getLoadMethodError: getLoadMethodError(state),\n isLoading: isLoading(state),\n isLoadingMethod: isLoadingMethod(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport PaymentStrategyState, { DEFAULT_STATE } from './payment-strategy-state';\n\ninterface InitiaizedQuery {\n methodId: string;\n gatewayId?: string;\n}\n\nexport default interface PaymentStrategySelector {\n getInitializeError(methodId?: string): Error | undefined;\n getExecuteError(methodId?: string): Error | undefined;\n getFinalizeError(methodId?: string): Error | undefined;\n getWidgetInteractingError(methodId?: string): Error | undefined;\n isInitializing(methodId?: string): boolean;\n isInitialized(query: InitiaizedQuery): boolean;\n isExecuting(methodId?: string): boolean;\n isFinalizing(methodId?: string): boolean;\n isWidgetInteracting(methodId?: string): boolean;\n}\n\nexport type PaymentStrategySelectorFactory = (\n state: PaymentStrategyState,\n) => PaymentStrategySelector;\n\nexport function createPaymentStrategySelectorFactory(): PaymentStrategySelectorFactory {\n const getInitializeError = createSelector(\n (state: PaymentStrategyState) => state.errors.initializeMethodId,\n (state: PaymentStrategyState) => state.errors.initializeError,\n (initializeMethodId, initializeError) => (methodId?: string) => {\n if (methodId && initializeMethodId !== methodId) {\n return;\n }\n\n return initializeError;\n },\n );\n\n const getExecuteError = createSelector(\n (state: PaymentStrategyState) => state.errors.executeMethodId,\n (state: PaymentStrategyState) => state.errors.executeError,\n (executeMethodId, executeError) => (methodId?: string) => {\n if (methodId && executeMethodId !== methodId) {\n return;\n }\n\n return executeError;\n },\n );\n\n const getFinalizeError = createSelector(\n (state: PaymentStrategyState) => state.errors.finalizeMethodId,\n (state: PaymentStrategyState) => state.errors.finalizeError,\n (finalizeMethodId, finalizeError) => (methodId?: string) => {\n if (methodId && finalizeMethodId !== methodId) {\n return;\n }\n\n return finalizeError;\n },\n );\n\n const getWidgetInteractingError = createSelector(\n (state: PaymentStrategyState) => state.errors.widgetInteractionMethodId,\n (state: PaymentStrategyState) => state.errors.widgetInteractionError,\n (widgetInteractionMethodId, widgetInteractionError) => (methodId?: string) => {\n if (methodId && widgetInteractionMethodId !== methodId) {\n return;\n }\n\n return widgetInteractionError;\n },\n );\n\n const isInitializing = createSelector(\n (state: PaymentStrategyState) => state.statuses.initializeMethodId,\n (state: PaymentStrategyState) => state.statuses.isInitializing,\n (initializeMethodId, isInitializing) => (key?: string) => {\n if (key && initializeMethodId !== key) {\n return false;\n }\n\n return !!isInitializing;\n },\n );\n\n const isInitialized = createSelector(\n (state: PaymentStrategyState) => state.data,\n (data) => (query: InitiaizedQuery) => {\n const key = query.gatewayId ? `${query.methodId}.${query.gatewayId}` : query.methodId;\n\n return !!(data[key] && data[key].isInitialized);\n },\n );\n\n const isExecuting = createSelector(\n (state: PaymentStrategyState) => state.statuses.executeMethodId,\n (state: PaymentStrategyState) => state.statuses.isExecuting,\n (executeMethodId, isExecuting) => (methodId?: string) => {\n if (methodId && executeMethodId !== methodId) {\n return false;\n }\n\n return !!isExecuting;\n },\n );\n\n const isFinalizing = createSelector(\n (state: PaymentStrategyState) => state.statuses.finalizeMethodId,\n (state: PaymentStrategyState) => state.statuses.isFinalizing,\n (finalizeMethodId, isFinalizing) => (methodId?: string) => {\n if (methodId && finalizeMethodId !== methodId) {\n return false;\n }\n\n return !!isFinalizing;\n },\n );\n\n const isWidgetInteracting = createSelector(\n (state: PaymentStrategyState) => state.statuses.widgetInteractionMethodId,\n (state: PaymentStrategyState) => state.statuses.isWidgetInteracting,\n (widgetInteractionMethodId, isWidgetInteracting) => (methodId?: string) => {\n if (methodId && widgetInteractionMethodId !== methodId) {\n return false;\n }\n\n return !!isWidgetInteracting;\n },\n );\n\n return memoizeOne((state: PaymentStrategyState = DEFAULT_STATE): PaymentStrategySelector => {\n return {\n getInitializeError: getInitializeError(state),\n getExecuteError: getExecuteError(state),\n getFinalizeError: getFinalizeError(state),\n getWidgetInteractingError: getWidgetInteractingError(state),\n isInitializing: isInitializing(state),\n isInitialized: isInitialized(state),\n isExecuting: isExecuting(state),\n isFinalizing: isFinalizing(state),\n isWidgetInteracting: isWidgetInteracting(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\nimport { objectFlatten, objectWithSortedKeys } from '../common/utility';\n\nimport { PickupOptionResult, SearchArea } from './pickup-option';\nimport PickupOptionState, { DEFAULT_STATE } from './pickup-option-state';\n\nexport default interface PickupOptionSelector {\n getPickupOptions(\n consignmentId: string,\n searchArea: SearchArea,\n ): PickupOptionResult[] | undefined;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type PickupOptionSelectorFactory = (state: PickupOptionState) => PickupOptionSelector;\n\nexport function createPickupOptionSelectorFactory(): PickupOptionSelectorFactory {\n const getPickupOptions = createSelector(\n (state: PickupOptionState) => state.data,\n (pickupOptions) => (consignmentId: string, searchArea: SearchArea) => {\n if (!pickupOptions) {\n return;\n }\n\n const flattenedParams = objectFlatten({ consignmentId, searchArea });\n const sortedFlattenedParams = objectWithSortedKeys(flattenedParams);\n const keyString = btoa(`${JSON.stringify(sortedFlattenedParams)}`);\n\n return pickupOptions[keyString];\n },\n );\n\n const getLoadError = createSelector(\n (state: PickupOptionState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: PickupOptionState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne((state: PickupOptionState = DEFAULT_STATE): PickupOptionSelector => {\n return {\n getPickupOptions: getPickupOptions(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\nimport { Country } from '../geography';\n\nimport ShippingCountryState, { DEFAULT_STATE } from './shipping-country-state';\n\nexport default interface ShippingCountrySelector {\n getShippingCountries(): Country[] | undefined;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type ShippingCountrySelectorFactory = (\n state: ShippingCountryState,\n) => ShippingCountrySelector;\n\nexport function createShippingCountrySelectorFactory(): ShippingCountrySelectorFactory {\n const getShippingCountries = createSelector(\n (state: ShippingCountryState) => state.data,\n (data) => () => data,\n );\n\n const getLoadError = createSelector(\n (state: ShippingCountryState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: ShippingCountryState) => state.statuses.isLoading,\n (status) => () => !!status,\n );\n\n return memoizeOne((state: ShippingCountryState = DEFAULT_STATE): ShippingCountrySelector => {\n return {\n getShippingCountries: getShippingCountries(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport ShippingStrategyState, { DEFAULT_STATE } from './shipping-strategy-state';\n\nexport default interface ShippingStrategySelector {\n getUpdateAddressError(methodId?: string): Error | undefined;\n getSelectOptionError(methodId?: string): Error | undefined;\n getInitializeError(methodId?: string): Error | undefined;\n getWidgetInteractionError(methodId?: string): Error | undefined;\n isUpdatingAddress(methodId?: string): boolean;\n isSelectingOption(methodId?: string): boolean;\n isInitializing(methodId?: string): boolean;\n isInitialized(methodId: string): boolean;\n isWidgetInteracting(methodId?: string): boolean;\n}\n\nexport type ShippingStrategySelectorFactory = (\n state: ShippingStrategyState,\n) => ShippingStrategySelector;\n\nexport function createShippingStrategySelectorFactory(): ShippingStrategySelectorFactory {\n const getUpdateAddressError = createSelector(\n (state: ShippingStrategyState) => state.errors.updateAddressMethodId,\n (state: ShippingStrategyState) => state.errors.updateAddressError,\n (updateAddressMethodId, updateAddressError) => (methodId?: string) => {\n if (methodId && updateAddressMethodId !== methodId) {\n return;\n }\n\n return updateAddressError;\n },\n );\n\n const getSelectOptionError = createSelector(\n (state: ShippingStrategyState) => state.errors.selectOptionMethodId,\n (state: ShippingStrategyState) => state.errors.selectOptionError,\n (selectOptionMethodId, selectOptionError) => (methodId?: string) => {\n if (methodId && selectOptionMethodId !== methodId) {\n return;\n }\n\n return selectOptionError;\n },\n );\n\n const getInitializeError = createSelector(\n (state: ShippingStrategyState) => state.errors.initializeMethodId,\n (state: ShippingStrategyState) => state.errors.initializeError,\n (initializeMethodId, initializeError) => (methodId?: string) => {\n if (methodId && initializeMethodId !== methodId) {\n return;\n }\n\n return initializeError;\n },\n );\n\n const getWidgetInteractionError = createSelector(\n (state: ShippingStrategyState) => state.errors.widgetInteractionMethodId,\n (state: ShippingStrategyState) => state.errors.widgetInteractionError,\n (widgetInteractionMethodId, widgetInteractionError) => (methodId?: string) => {\n if (methodId && widgetInteractionMethodId !== methodId) {\n return;\n }\n\n return widgetInteractionError;\n },\n );\n\n const isUpdatingAddress = createSelector(\n (state: ShippingStrategyState) => state.statuses.updateAddressMethodId,\n (state: ShippingStrategyState) => state.statuses.isUpdatingAddress,\n (updateAddressMethodId, isUpdatingAddress) => (methodId?: string) => {\n if (methodId && updateAddressMethodId !== methodId) {\n return false;\n }\n\n return !!isUpdatingAddress;\n },\n );\n\n const isSelectingOption = createSelector(\n (state: ShippingStrategyState) => state.statuses.selectOptionMethodId,\n (state: ShippingStrategyState) => state.statuses.isSelectingOption,\n (selectOptionMethodId, isSelectingOption) => (methodId?: string) => {\n if (methodId && selectOptionMethodId !== methodId) {\n return false;\n }\n\n return !!isSelectingOption;\n },\n );\n\n const isInitializing = createSelector(\n (state: ShippingStrategyState) => state.statuses.initializeMethodId,\n (state: ShippingStrategyState) => state.statuses.isInitializing,\n (initializeMethodId, isInitializing) => (methodId?: string) => {\n if (methodId && initializeMethodId !== methodId) {\n return false;\n }\n\n return !!isInitializing;\n },\n );\n\n const isInitialized = createSelector(\n (state: ShippingStrategyState) => state.data,\n (data) => (methodId: string) => {\n return !!(data[methodId] && data[methodId].isInitialized);\n },\n );\n\n const isWidgetInteracting = createSelector(\n (state: ShippingStrategyState) => state.statuses.widgetInteractionMethodId,\n (state: ShippingStrategyState) => state.statuses.isWidgetInteracting,\n (widgetInteractionMethodId, isWidgetInteracting) => (methodId?: string) => {\n if (methodId && widgetInteractionMethodId !== methodId) {\n return false;\n }\n\n return !!isWidgetInteracting;\n },\n );\n\n return memoizeOne((state: ShippingStrategyState = DEFAULT_STATE): ShippingStrategySelector => {\n return {\n getUpdateAddressError: getUpdateAddressError(state),\n getSelectOptionError: getSelectOptionError(state),\n getInitializeError: getInitializeError(state),\n getWidgetInteractionError: getWidgetInteractionError(state),\n isUpdatingAddress: isUpdatingAddress(state),\n isSelectingOption: isSelectingOption(state),\n isInitializing: isInitializing(state),\n isInitialized: isInitialized(state),\n isWidgetInteracting: isWidgetInteracting(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\nimport { find } from 'lodash';\n\nimport { AddressRequestBody, isAddressEqual } from '../address';\nimport { CartSelector, PhysicalItem } from '../cart';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\n\nimport Consignment from './consignment';\nimport ConsignmentState, { DEFAULT_STATE } from './consignment-state';\nimport ShippingOption from './shipping-option';\n\nexport default interface ConsignmentSelector {\n getConsignments(): Consignment[] | undefined;\n getConsignmentsOrThrow(): Consignment[];\n getConsignmentById(id: string): Consignment | undefined;\n getConsignmentByAddress(address: AddressRequestBody): Consignment | undefined;\n getShippingOption(): ShippingOption | undefined;\n getLoadError(): Error | undefined;\n getCreateError(): Error | undefined;\n getLoadShippingOptionsError(): Error | undefined;\n getUnassignedItems(): PhysicalItem[];\n getUpdateError(consignmentId?: string): Error | undefined;\n getDeleteError(consignmentId?: string): Error | undefined;\n getItemAssignmentError(address: AddressRequestBody): Error | undefined;\n getUpdateShippingOptionError(consignmentId?: string): Error | undefined;\n isLoading(): boolean;\n isLoadingShippingOptions(): boolean;\n isCreating(): boolean;\n isUpdating(consignmentId?: string): boolean;\n isDeleting(consignmentId?: string): boolean;\n isAssigningItems(address: AddressRequestBody): boolean;\n isUpdatingShippingOption(consignmentId?: string): boolean;\n}\n\nexport type ConsignmentSelectorFactory = (\n state: ConsignmentState,\n cart: CartSelector,\n) => ConsignmentSelector;\n\ninterface ConsignmentSelectorDependencies {\n cart: CartSelector;\n}\n\nexport function createConsignmentSelectorFactory(): ConsignmentSelectorFactory {\n const getConsignments = createSelector(\n (state: ConsignmentState) => state.data,\n (consignments) => () => consignments,\n );\n\n const getConsignmentsOrThrow = createSelector(getConsignments, (getConsignments) => () => {\n return guard(\n getConsignments(),\n () => new MissingDataError(MissingDataErrorType.MissingConsignments),\n );\n });\n\n const getConsignmentById = createSelector(\n (state: ConsignmentState) => state.data,\n (consignments) => (id: string) => {\n if (!consignments || !consignments.length) {\n return;\n }\n\n return find(consignments, { id });\n },\n );\n\n const getConsignmentByAddress = createSelector(\n (state: ConsignmentState) => state.data,\n (consignments) => (address: AddressRequestBody) => {\n if (!consignments || !consignments.length) {\n return;\n }\n\n return find(consignments, (consignment) =>\n isAddressEqual(consignment.shippingAddress, address),\n );\n },\n );\n\n const getShippingOption = createSelector(\n (state: ConsignmentState) => state.data,\n (consignments) => () => {\n if (consignments && consignments.length) {\n return consignments[0].selectedShippingOption;\n }\n },\n );\n\n const getLoadError = createSelector(\n (state: ConsignmentState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const getCreateError = createSelector(\n (state: ConsignmentState) => state.errors.createError,\n (error) => () => error,\n );\n\n const getLoadShippingOptionsError = createSelector(\n (state: ConsignmentState) => state.errors.loadShippingOptionsError,\n (error) => () => error,\n );\n\n const getUnassignedItems = createSelector(\n getConsignments,\n (_: ConsignmentState, { cart }: ConsignmentSelectorDependencies) => cart.getCart,\n (getConsignments, getCart) => () => {\n const cart = getCart();\n\n if (!cart) {\n return [];\n }\n\n const assignedLineItemIds = (getConsignments() || []).reduce(\n (itemIds, consignment) => itemIds.concat(consignment.lineItemIds),\n [] as string[],\n );\n\n return (cart.lineItems.physicalItems || []).filter(\n (item) => assignedLineItemIds.indexOf(item.id as string) < 0,\n );\n },\n );\n\n const getUpdateError = createSelector(\n (state: ConsignmentState) => state.errors.updateError,\n (updateError) => (consignmentId?: string) => {\n if (consignmentId) {\n return updateError[consignmentId];\n }\n\n return find(updateError);\n },\n );\n\n const getDeleteError = createSelector(\n (state: ConsignmentState) => state.errors.deleteError,\n (deleteError) => (consignmentId?: string) => {\n if (consignmentId) {\n return deleteError[consignmentId];\n }\n\n return find(deleteError);\n },\n );\n\n const getItemAssignmentError = createSelector(\n getConsignmentByAddress,\n getUpdateError,\n getCreateError,\n (getConsignmentByAddress, getUpdateError, getCreateError) =>\n (address: AddressRequestBody) => {\n const consignment = getConsignmentByAddress(address);\n\n return consignment ? getUpdateError(consignment.id) : getCreateError();\n },\n );\n\n const getUpdateShippingOptionError = createSelector(\n (state: ConsignmentState) => state.errors.updateShippingOptionError,\n (updateShippingOptionError) => (consignmentId?: string) => {\n if (consignmentId) {\n return updateShippingOptionError[consignmentId];\n }\n\n return find(updateShippingOptionError);\n },\n );\n\n const isLoading = createSelector(\n (state: ConsignmentState) => state.statuses.isLoading,\n (isLoading) => () => isLoading === true,\n );\n\n const isLoadingShippingOptions = createSelector(\n (state: ConsignmentState) => state.statuses.isLoadingShippingOptions,\n (isLoadingShippingOptions) => () => isLoadingShippingOptions === true,\n );\n\n const isCreating = createSelector(\n (state: ConsignmentState) => state.statuses.isCreating,\n (isCreating) => () => isCreating === true,\n );\n\n const isUpdating = createSelector(\n (state: ConsignmentState) => state.statuses.isUpdating,\n (isUpdating) => (consignmentId?: string) => {\n if (consignmentId) {\n return isUpdating[consignmentId] === true;\n }\n\n return find(isUpdating) === true;\n },\n );\n\n const isDeleting = createSelector(\n (state: ConsignmentState) => state.statuses.isDeleting,\n (isDeleting) => (consignmentId?: string) => {\n if (consignmentId) {\n return isDeleting[consignmentId] === true;\n }\n\n return find(isDeleting) === true;\n },\n );\n\n const isAssigningItems = createSelector(\n getConsignmentByAddress,\n isUpdating,\n isCreating,\n (getConsignmentByAddress, isUpdating, isCreating) => (address: AddressRequestBody) => {\n const consignment = getConsignmentByAddress(address);\n\n return consignment ? isUpdating(consignment.id) : isCreating();\n },\n );\n\n const isUpdatingShippingOption = createSelector(\n (state: ConsignmentState) => state.statuses.isUpdatingShippingOption,\n (isUpdatingShippingOption) => (consignmentId?: string) => {\n if (consignmentId) {\n return isUpdatingShippingOption[consignmentId] === true;\n }\n\n return find(isUpdatingShippingOption) === true;\n },\n );\n\n return memoizeOne(\n (state: ConsignmentState = DEFAULT_STATE, cart: CartSelector): ConsignmentSelector => {\n return {\n getConsignments: getConsignments(state),\n getConsignmentsOrThrow: getConsignmentsOrThrow(state),\n getConsignmentById: getConsignmentById(state),\n getConsignmentByAddress: getConsignmentByAddress(state),\n getShippingOption: getShippingOption(state),\n getLoadError: getLoadError(state),\n getCreateError: getCreateError(state),\n getLoadShippingOptionsError: getLoadShippingOptionsError(state),\n getUnassignedItems: getUnassignedItems(state, { cart }),\n getUpdateError: getUpdateError(state),\n getDeleteError: getDeleteError(state),\n getItemAssignmentError: getItemAssignmentError(state),\n getUpdateShippingOptionError: getUpdateShippingOptionError(state),\n isLoading: isLoading(state),\n isLoadingShippingOptions: isLoadingShippingOptions(state),\n isCreating: isCreating(state),\n isUpdating: isUpdating(state),\n isDeleting: isDeleting(state),\n isAssigningItems: isAssigningItems(state),\n isUpdatingShippingOption: isUpdatingShippingOption(state),\n };\n },\n );\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { BillingAddressSelector } from '../billing';\nimport { CartSelector } from '../cart';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\nimport { CouponSelector, GiftCertificateSelector } from '../coupon';\nimport { CustomerSelector } from '../customer';\nimport { ConsignmentSelector } from '../shipping';\n\nimport Checkout from './checkout';\nimport CheckoutState, { DEFAULT_STATE } from './checkout-state';\n\nexport default interface CheckoutSelector {\n getCheckout(): Checkout | undefined;\n getCheckoutOrThrow(): Checkout;\n getOutstandingBalance(useStoreCredit?: boolean): number | undefined;\n getLoadError(): Error | undefined;\n getUpdateError(): Error | undefined;\n isExecutingSpamCheck(): boolean;\n isLoading(): boolean;\n isUpdating(): boolean;\n}\n\nexport type CheckoutSelectorFactory = (\n state: CheckoutState,\n billingAddress: BillingAddressSelector,\n cart: CartSelector,\n consignments: ConsignmentSelector,\n coupons: CouponSelector,\n customer: CustomerSelector,\n giftCertificates: GiftCertificateSelector,\n) => CheckoutSelector;\n\ninterface CheckoutSelectorDependencies {\n billingAddress: BillingAddressSelector;\n cart: CartSelector;\n consignments: ConsignmentSelector;\n coupons: CouponSelector;\n customer: CustomerSelector;\n giftCertificates: GiftCertificateSelector;\n}\n\nexport function createCheckoutSelectorFactory(): CheckoutSelectorFactory {\n const getCheckout = createSelector(\n (state: CheckoutState) => state.data,\n (_: CheckoutState, { billingAddress }: CheckoutSelectorDependencies) =>\n billingAddress.getBillingAddress,\n (_: CheckoutState, { cart }: CheckoutSelectorDependencies) => cart.getCart,\n (_: CheckoutState, { customer }: CheckoutSelectorDependencies) => customer.getCustomer,\n (_: CheckoutState, { consignments }: CheckoutSelectorDependencies) =>\n consignments.getConsignments,\n (_: CheckoutState, { coupons }: CheckoutSelectorDependencies) => coupons.getCoupons,\n (_: CheckoutState, { giftCertificates }: CheckoutSelectorDependencies) =>\n giftCertificates.getGiftCertificates,\n (\n data,\n getBillingAddress,\n getCart,\n getCustomer,\n getConsignments,\n getCoupons,\n getGiftCertificates,\n ) =>\n () => {\n const billingAddress = getBillingAddress();\n const cart = getCart();\n const customer = getCustomer();\n const consignments = getConsignments() || [];\n const coupons = getCoupons() || [];\n const giftCertificates = getGiftCertificates() || [];\n\n if (!data || !cart || !customer) {\n return;\n }\n\n return {\n ...data,\n billingAddress,\n cart,\n customer,\n consignments,\n coupons,\n giftCertificates,\n };\n },\n );\n\n const getCheckoutOrThrow = createSelector(getCheckout, (getCheckout) => () => {\n return guard(\n getCheckout(),\n () => new MissingDataError(MissingDataErrorType.MissingCheckout),\n );\n });\n\n const getOutstandingBalance = createSelector(\n getCheckout,\n (getCheckout) => (useStoreCredit?: boolean) => {\n const checkout = getCheckout();\n\n if (!checkout) {\n return;\n }\n\n const grandTotal = checkout.grandTotal || 0;\n const storeCredit = checkout.customer.storeCredit || 0;\n\n return useStoreCredit\n ? Math.max(grandTotal - storeCredit, 0)\n : checkout.outstandingBalance;\n },\n );\n\n const getLoadError = createSelector(\n (state: CheckoutState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const getUpdateError = createSelector(\n (state: CheckoutState) => state.errors.updateError,\n (error) => () => error,\n );\n\n const isExecutingSpamCheck = createSelector(\n (state: CheckoutState) => state.statuses.isExecutingSpamCheck,\n (isExecutingSpamCheck) => () => isExecutingSpamCheck === true,\n );\n\n const isLoading = createSelector(\n (state: CheckoutState) => state.statuses.isLoading,\n (isLoading) => () => isLoading === true,\n );\n\n const isUpdating = createSelector(\n (state: CheckoutState) => state.statuses.isUpdating,\n (isUpdating) => () => isUpdating === true,\n );\n\n return memoizeOne(\n (\n state: CheckoutState = DEFAULT_STATE,\n billingAddress: BillingAddressSelector,\n cart: CartSelector,\n consignments: ConsignmentSelector,\n coupons: CouponSelector,\n customer: CustomerSelector,\n giftCertificates: GiftCertificateSelector,\n ): CheckoutSelector => {\n return {\n getCheckout: getCheckout(state, {\n billingAddress,\n cart,\n consignments,\n coupons,\n customer,\n giftCertificates,\n }),\n getCheckoutOrThrow: getCheckoutOrThrow(state, {\n billingAddress,\n cart,\n consignments,\n coupons,\n customer,\n giftCertificates,\n }),\n getOutstandingBalance: getOutstandingBalance(state, {\n billingAddress,\n cart,\n consignments,\n coupons,\n customer,\n giftCertificates,\n }),\n getLoadError: getLoadError(state),\n getUpdateError: getUpdateError(state),\n isExecutingSpamCheck: isExecutingSpamCheck(state),\n isLoading: isLoading(state),\n isUpdating: isUpdating(state),\n };\n },\n );\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\nimport { guard } from '../common/utility';\nimport { CouponSelector } from '../coupon';\nimport OrderBillingAddressSelector from '../order-billing-address/order-billing-address-selector';\n\nimport Order from './order';\nimport OrderState, { DEFAULT_STATE, OrderMetaState } from './order-state';\n\nexport default interface OrderSelector {\n getOrder(): Order | undefined;\n getOrderOrThrow(): Order;\n getOrderMeta(): OrderMetaState | undefined;\n getLoadError(): Error | undefined;\n getPaymentId(methodId: string): string | undefined;\n isLoading(): boolean;\n}\n\nexport type OrderSelectorFactory = (\n state: OrderState,\n billingAddress: OrderBillingAddressSelector,\n coupons: CouponSelector,\n) => OrderSelector;\n\ninterface OrderSelectorDependencies {\n billingAddress: OrderBillingAddressSelector;\n coupons: CouponSelector;\n}\n\nexport function createOrderSelectorFactory(): OrderSelectorFactory {\n const getOrder = createSelector(\n (state: OrderState) => state.data,\n (_: OrderState, { billingAddress }: OrderSelectorDependencies) =>\n billingAddress.getOrderBillingAddress(),\n (_: OrderState, { coupons }: OrderSelectorDependencies) => coupons.getCoupons(),\n (data, billingAddress, coupons = []) =>\n () => {\n if (!data || !billingAddress) {\n return;\n }\n\n return {\n ...data,\n billingAddress,\n coupons,\n };\n },\n );\n\n const getOrderOrThrow = createSelector(getOrder, (getOrder) => () => {\n return guard(getOrder(), () => new MissingDataError(MissingDataErrorType.MissingOrder));\n });\n\n const getOrderMeta = createSelector(\n (state: OrderState) => state.meta,\n (meta) => () => meta,\n );\n\n const getLoadError = createSelector(\n (state: OrderState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const getPaymentId = createSelector(\n (state: OrderState) => state.data?.payments,\n (payments = []) =>\n (methodId: string) => {\n const currentPayment = payments.find(({ providerId }) => providerId === methodId);\n\n return currentPayment?.paymentId;\n },\n );\n\n const isLoading = createSelector(\n (state: OrderState) => !!state.statuses.isLoading,\n (status) => () => status,\n );\n\n return memoizeOne(\n (\n state: OrderState = DEFAULT_STATE,\n billingAddress: OrderBillingAddressSelector,\n coupons: CouponSelector,\n ): OrderSelector => {\n return {\n getOrder: getOrder(state, { billingAddress, coupons }),\n getOrderOrThrow: getOrderOrThrow(state, { billingAddress, coupons }),\n getOrderMeta: getOrderMeta(state),\n getLoadError: getLoadError(state),\n getPaymentId: getPaymentId(state),\n isLoading: isLoading(state),\n };\n },\n );\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { RequestError } from '../common/error/errors';\nimport { createSelector } from '../common/selector';\n\nimport StoreCreditState, { DEFAULT_STATE } from './store-credit-state';\n\nexport default interface StoreCreditSelector {\n getApplyError(): RequestError | undefined;\n isApplying(): boolean;\n}\n\nexport type StoreCreditSelectorFactory = (state: StoreCreditState) => StoreCreditSelector;\n\nexport function createStoreCreditSelectorFactory(): StoreCreditSelectorFactory {\n const getApplyError = createSelector(\n (state: StoreCreditState) => state.errors.applyError,\n (error) => () => error,\n );\n\n const isApplying = createSelector(\n (state: StoreCreditState) => !!state.statuses.isApplying,\n (status) => () => status,\n );\n\n return memoizeOne((state: StoreCreditState = DEFAULT_STATE): StoreCreditSelector => {\n return {\n getApplyError: getApplyError(state),\n isApplying: isApplying(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport SubscriptionsState, { DEFAULT_STATE } from './subscriptions-state';\n\nexport default interface SubscriptionsSelector {\n getUpdateError(): Error | undefined;\n isUpdating(): boolean;\n}\n\nexport type SubscriptionsSelectorFactory = (state: SubscriptionsState) => SubscriptionsSelector;\n\nexport function createSubscriptionsSelectorFactory(): SubscriptionsSelectorFactory {\n const getUpdateError = createSelector(\n (state: SubscriptionsState) => state.errors.updateError,\n (error) => () => error,\n );\n\n const isUpdating = createSelector(\n (state: SubscriptionsState) => !!state.statuses.isUpdating,\n (status) => () => status,\n );\n\n return memoizeOne((state: SubscriptionsState = DEFAULT_STATE): SubscriptionsSelector => {\n return {\n getUpdateError: getUpdateError(state),\n isUpdating: isUpdating(state),\n };\n });\n}\n","import { memoizeOne } from '@bigcommerce/memoize';\n\nimport { createSelector } from '../common/selector';\n\nimport { Extension, ExtensionRegion } from './extension';\nimport { DEFAULT_STATE, ExtensionState } from './extension-state';\n\nexport interface ExtensionSelector {\n getExtensions(): Extension[] | undefined;\n getExtensionByRegion(region: ExtensionRegion): Extension | undefined;\n getLoadError(): Error | undefined;\n isLoading(): boolean;\n}\n\nexport type ExtensionSelectorFactory = (state: ExtensionState) => ExtensionSelector;\n\nexport function createExtensionSelectorFactory(): ExtensionSelectorFactory {\n const getExtensions = createSelector(\n (state: ExtensionState) => state.data,\n (data) => () => data,\n );\n\n const getExtensionByRegion = createSelector(\n (state: ExtensionState) => state.data,\n (data) => (region: ExtensionRegion) => data?.find((e) => e.region === region),\n );\n\n const getLoadError = createSelector(\n (state: ExtensionState) => state.errors.loadError,\n (error) => () => error,\n );\n\n const isLoading = createSelector(\n (state: ExtensionState) => state.statuses.isLoading,\n (isLoading) => () => !!isLoading,\n );\n\n return memoizeOne((state: ExtensionState = DEFAULT_STATE): ExtensionSelector => {\n return {\n getExtensions: getExtensions(state),\n getExtensionByRegion: getExtensionByRegion(state),\n getLoadError: getLoadError(state),\n isLoading: isLoading(state),\n };\n });\n}\n","import { createDataStore } from '@bigcommerce/data-store';\n\nimport { createRequestErrorFactory } from '../common/error';\n\nimport CheckoutStore, { CheckoutStoreOptions } from './checkout-store';\nimport CheckoutStoreState from './checkout-store-state';\nimport createActionTransformer from './create-action-transformer';\nimport createCheckoutStoreReducer from './create-checkout-store-reducer';\nimport { createInternalCheckoutSelectorsFactory } from './create-internal-checkout-selectors';\n\nexport default function createCheckoutStore(\n initialState: Partial = {},\n options?: CheckoutStoreOptions,\n): CheckoutStore {\n const actionTransformer = createActionTransformer(createRequestErrorFactory());\n const createInternalCheckoutSelectors = createInternalCheckoutSelectorsFactory();\n const stateTransformer = (state: CheckoutStoreState) => createInternalCheckoutSelectors(state);\n\n return createDataStore(createCheckoutStoreReducer(), initialState, {\n actionTransformer,\n stateTransformer,\n ...options,\n });\n}\n","import { PaymentMethodInvalidError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { UnrecoverableError } from './errors';\nimport RequestErrorFactory from './request-error-factory';\n\nexport default function createRequestErrorFactory(): RequestErrorFactory {\n const factory = new RequestErrorFactory();\n\n const unrecoverableErrorTypes = [\n 'catalog_only',\n 'empty_cart',\n 'invalid_order_id',\n 'invalid_order_token',\n 'missing_order_token',\n 'missing_provider_token',\n 'missing_shipping_method',\n 'order_completion_error',\n 'order_could_not_be_finalized_error',\n 'order_create_failed',\n 'provider_fatal_error',\n 'provider_setup_error',\n 'stock_too_low',\n ];\n\n unrecoverableErrorTypes.forEach((type) => {\n factory.register(type, (response, message) => new UnrecoverableError(response, message));\n });\n\n factory.register(\n 'invalid_payment_provider',\n (response) => new PaymentMethodInvalidError(response),\n );\n factory.register(\n 'payment_config_not_found',\n (response) => new PaymentMethodInvalidError(response),\n );\n\n return factory;\n}\n","import { Action } from '@bigcommerce/data-store';\nimport { from, Observable, Subscribable } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { RequestErrorFactory } from '../common/error';\n\nexport default function createActionTransformer(\n requestErrorFactory: RequestErrorFactory,\n): (action: Subscribable) => Observable {\n return (action$) =>\n from(action$).pipe(\n catchError((action) => {\n if (action instanceof Error || action.payload instanceof Error) {\n throw action;\n }\n\n if (isResponse(action.payload)) {\n const message = action.payload.body && action.payload.body.detail;\n\n throw {\n ...action,\n payload: requestErrorFactory.createError(action.payload, message),\n };\n }\n\n throw action;\n }),\n );\n}\n\nfunction isResponse(object: any) {\n if (!object || typeof object !== 'object') {\n return false;\n }\n\n return ['body', 'headers', 'status', 'statusText'].every((key) =>\n Object.prototype.hasOwnProperty.call(object, key),\n );\n}\n","import { Action, combineReducers, Reducer } from '@bigcommerce/data-store';\n\nimport { billingAddressReducer } from '../billing';\nimport { cartReducer } from '../cart';\nimport { checkoutButtonReducer } from '../checkout-buttons';\nimport { configReducer } from '../config';\nimport { couponReducer, giftCertificateReducer } from '../coupon';\nimport { customerReducer, customerStrategyReducer } from '../customer';\nimport { extensionReducer } from '../extension';\nimport { formFieldsReducer } from '../form';\nimport { countryReducer } from '../geography';\nimport { orderReducer } from '../order';\nimport { orderBillingAddressReducer } from '../order-billing-address';\nimport { paymentMethodReducer, paymentReducer, paymentStrategyReducer } from '../payment';\nimport { instrumentReducer } from '../payment/instrument';\nimport { remoteCheckoutReducer } from '../remote-checkout';\nimport {\n consignmentReducer,\n pickupOptionReducer,\n shippingCountryReducer,\n shippingStrategyReducer,\n} from '../shipping';\nimport { signInEmailReducer } from '../signin-email';\nimport { storeCreditReducer } from '../store-credit';\nimport { subscriptionsReducer } from '../subscription';\n\nimport checkoutReducer from './checkout-reducer';\nimport CheckoutStoreState from './checkout-store-state';\n\nexport default function createCheckoutStoreReducer(): Reducer {\n return combineReducers({\n billingAddress: billingAddressReducer,\n cart: cartReducer,\n checkout: checkoutReducer,\n checkoutButton: checkoutButtonReducer,\n config: configReducer,\n consignments: consignmentReducer,\n countries: countryReducer,\n coupons: couponReducer,\n customer: customerReducer,\n customerStrategies: customerStrategyReducer,\n extensions: extensionReducer,\n formFields: formFieldsReducer,\n giftCertificates: giftCertificateReducer,\n instruments: instrumentReducer,\n orderBillingAddress: orderBillingAddressReducer,\n order: orderReducer,\n payment: paymentReducer,\n paymentMethods: paymentMethodReducer,\n paymentStrategies: paymentStrategyReducer,\n pickupOptions: pickupOptionReducer,\n remoteCheckout: remoteCheckoutReducer,\n shippingCountries: shippingCountryReducer,\n shippingStrategies: shippingStrategyReducer,\n signInEmail: signInEmailReducer,\n subscriptions: subscriptionsReducer,\n storeCredit: storeCreditReducer,\n });\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\nimport { createScriptLoader } from '@bigcommerce/script-loader';\n\nimport { BillingAddressActionCreator, BillingAddressRequestSender } from '../billing';\nimport { ErrorActionCreator } from '../common/error';\nimport { getDefaultLogger } from '../common/log';\nimport { getEnvironment } from '../common/utility';\nimport { ConfigActionCreator, ConfigRequestSender, ConfigState, ConfigWindow } from '../config';\nimport {\n CouponActionCreator,\n CouponRequestSender,\n GiftCertificateActionCreator,\n GiftCertificateRequestSender,\n} from '../coupon';\nimport {\n createCustomerStrategyRegistry,\n createCustomerStrategyRegistryV2,\n CustomerActionCreator,\n CustomerRequestSender,\n CustomerStrategyActionCreator,\n} from '../customer';\nimport { ExtensionActionCreator, ExtensionRequestSender } from '../extension';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport * as defaultPaymentStrategyFactories from '../generated/payment-strategies';\nimport { CountryActionCreator, CountryRequestSender } from '../geography';\nimport { OrderActionCreator, OrderRequestSender } from '../order';\nimport {\n createPaymentClient,\n createPaymentStrategyRegistry,\n createPaymentStrategyRegistryV2,\n PaymentMethodActionCreator,\n PaymentMethodRequestSender,\n PaymentStrategyActionCreator,\n} from '../payment';\nimport { createPaymentIntegrationService } from '../payment-integration';\nimport { InstrumentActionCreator, InstrumentRequestSender } from '../payment/instrument';\nimport {\n ConsignmentActionCreator,\n ConsignmentRequestSender,\n createShippingStrategyRegistry,\n PickupOptionActionCreator,\n PickupOptionRequestSender,\n ShippingCountryActionCreator,\n ShippingCountryRequestSender,\n ShippingStrategyActionCreator,\n} from '../shipping';\nimport { SignInEmailActionCreator, SignInEmailRequestSender } from '../signin-email';\nimport {\n createSpamProtection,\n SpamProtectionActionCreator,\n SpamProtectionRequestSender,\n} from '../spam-protection';\nimport { StoreCreditActionCreator, StoreCreditRequestSender } from '../store-credit';\nimport { SubscriptionsActionCreator, SubscriptionsRequestSender } from '../subscription';\n\nimport CheckoutActionCreator from './checkout-action-creator';\nimport CheckoutRequestSender from './checkout-request-sender';\nimport CheckoutService from './checkout-service';\nimport CheckoutValidator from './checkout-validator';\nimport createCheckoutStore from './create-checkout-store';\n\n/**\n * Creates an instance of `CheckoutService`.\n *\n * @remarks\n * ```js\n * const service = createCheckoutService();\n *\n * service.subscribe(state => {\n * console.log(state);\n * });\n *\n * service.loadCheckout();\n * ```\n *\n * @param options - A set of construction options.\n * @returns an instance of `CheckoutService`.\n */\nexport default function createCheckoutService(options?: CheckoutServiceOptions): CheckoutService {\n if (document.location.protocol !== 'https:') {\n getDefaultLogger().warn(\n 'The BigCommerce Checkout SDK should not be used on a non-HTTPS page',\n );\n }\n\n if (getEnvironment() !== 'production') {\n getDefaultLogger().warn(\n 'Note that the development build is not optimized. To create a production build, set process.env.NODE_ENV to `production`.',\n );\n }\n\n const config: ConfigState = {\n meta: {\n externalSource: options && options.externalSource,\n host: options?.host,\n locale: options?.locale,\n variantIdentificationToken: (window as ConfigWindow).checkoutVariantIdentificationToken,\n },\n errors: {},\n statuses: {},\n };\n const { locale = '', shouldWarnMutation = true } = options || {};\n const requestSender = createRequestSender({ host: options && options.host });\n const store = createCheckoutStore({ config }, { shouldWarnMutation });\n const paymentClient = createPaymentClient(store);\n const orderRequestSender = new OrderRequestSender(requestSender);\n const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n const configActionCreator = new ConfigActionCreator(new ConfigRequestSender(requestSender));\n const spamProtection = createSpamProtection(createScriptLoader());\n const spamProtectionRequestSender = new SpamProtectionRequestSender(requestSender);\n const spamProtectionActionCreator = new SpamProtectionActionCreator(\n spamProtection,\n spamProtectionRequestSender,\n );\n const orderActionCreator = new OrderActionCreator(\n orderRequestSender,\n new CheckoutValidator(checkoutRequestSender),\n );\n const subscriptionsActionCreator = new SubscriptionsActionCreator(\n new SubscriptionsRequestSender(requestSender),\n );\n const formFieldsActionCreator = new FormFieldsActionCreator(\n new FormFieldsRequestSender(requestSender),\n );\n const checkoutActionCreator = new CheckoutActionCreator(\n checkoutRequestSender,\n configActionCreator,\n formFieldsActionCreator,\n );\n const paymentIntegrationService = createPaymentIntegrationService(store);\n const registryV2 = createPaymentStrategyRegistryV2(\n paymentIntegrationService,\n defaultPaymentStrategyFactories,\n { useFallback: true },\n );\n const customerRegistryV2 = createCustomerStrategyRegistryV2(paymentIntegrationService);\n const extensionActionCreator = new ExtensionActionCreator(\n new ExtensionRequestSender(requestSender),\n );\n\n return new CheckoutService(\n store,\n new BillingAddressActionCreator(\n new BillingAddressRequestSender(requestSender),\n subscriptionsActionCreator,\n ),\n checkoutActionCreator,\n configActionCreator,\n new CustomerActionCreator(\n new CustomerRequestSender(requestSender),\n checkoutActionCreator,\n spamProtectionActionCreator,\n ),\n new ConsignmentActionCreator(\n new ConsignmentRequestSender(requestSender),\n checkoutRequestSender,\n ),\n new CountryActionCreator(new CountryRequestSender(requestSender, { locale })),\n new CouponActionCreator(new CouponRequestSender(requestSender)),\n new CustomerStrategyActionCreator(\n createCustomerStrategyRegistry(store, requestSender, locale),\n customerRegistryV2,\n ),\n new ErrorActionCreator(),\n new GiftCertificateActionCreator(new GiftCertificateRequestSender(requestSender)),\n new InstrumentActionCreator(new InstrumentRequestSender(paymentClient, requestSender)),\n orderActionCreator,\n new PaymentMethodActionCreator(new PaymentMethodRequestSender(requestSender)),\n new PaymentStrategyActionCreator(\n createPaymentStrategyRegistry(\n store,\n paymentClient,\n requestSender,\n spamProtection,\n locale,\n ),\n registryV2,\n orderActionCreator,\n spamProtectionActionCreator,\n ),\n new PickupOptionActionCreator(new PickupOptionRequestSender(requestSender)),\n new ShippingCountryActionCreator(\n new ShippingCountryRequestSender(requestSender, { locale }),\n ),\n new ShippingStrategyActionCreator(createShippingStrategyRegistry(store, requestSender)),\n new SignInEmailActionCreator(new SignInEmailRequestSender(requestSender)),\n spamProtectionActionCreator,\n new StoreCreditActionCreator(new StoreCreditRequestSender(requestSender)),\n subscriptionsActionCreator,\n formFieldsActionCreator,\n extensionActionCreator,\n );\n}\n\nexport interface CheckoutServiceOptions {\n locale?: string;\n host?: string;\n shouldWarnMutation?: boolean;\n externalSource?: string;\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { RequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { CheckoutActionCreator, CheckoutRequestSender, CheckoutStore } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { ConfigActionCreator, ConfigRequestSender } from '../config';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport { PaymentMethodActionCreator, PaymentMethodRequestSender } from '../payment';\nimport { createPaymentIntegrationService } from '../payment-integration';\nimport { createAmazonPayV2PaymentProcessor } from '../payment/strategies/amazon-pay-v2';\nimport {\n BraintreeScriptLoader,\n BraintreeSDKCreator,\n createBraintreeVisaCheckoutPaymentProcessor,\n VisaCheckoutScriptLoader,\n} from '../payment/strategies/braintree';\nimport { ChasePayScriptLoader } from '../payment/strategies/chasepay';\nimport {\n createGooglePayPaymentProcessor,\n GooglePayAdyenV2Initializer,\n GooglePayAdyenV3Initializer,\n GooglePayAuthorizeNetInitializer,\n GooglePayBNZInitializer,\n GooglePayBraintreeInitializer,\n GooglePayCheckoutcomInitializer,\n GooglePayCybersourceV2Initializer,\n GooglePayOrbitalInitializer,\n GooglePayStripeInitializer,\n GooglePayStripeUPEInitializer,\n GooglePayWorldpayAccessInitializer,\n} from '../payment/strategies/googlepay';\nimport { MasterpassScriptLoader } from '../payment/strategies/masterpass';\nimport { StripeScriptLoader } from '../payment/strategies/stripe-upe';\nimport { RemoteCheckoutActionCreator, RemoteCheckoutRequestSender } from '../remote-checkout';\nimport { ConsignmentActionCreator, ConsignmentRequestSender } from '../shipping';\nimport {\n createSpamProtection,\n SpamProtectionActionCreator,\n SpamProtectionRequestSender,\n} from '../spam-protection';\n\nimport createCustomerStrategyRegistryV2 from './create-customer-strategy-registry-v2';\nimport CustomerActionCreator from './customer-action-creator';\nimport CustomerRequestSender from './customer-request-sender';\nimport CustomerStrategyActionCreator from './customer-strategy-action-creator';\nimport { CustomerStrategy } from './strategies';\nimport { AmazonPayV2CustomerStrategy } from './strategies/amazon-pay-v2';\nimport {\n BraintreePaypalCreditCustomerStrategy,\n BraintreeVisaCheckoutCustomerStrategy,\n} from './strategies/braintree';\nimport { ChasePayCustomerStrategy } from './strategies/chasepay';\nimport { DefaultCustomerStrategy } from './strategies/default';\nimport { GooglePayCustomerStrategy } from './strategies/googlepay';\nimport { MasterpassCustomerStrategy } from './strategies/masterpass';\nimport { SquareCustomerStrategy } from './strategies/square';\nimport { StripeUPECustomerStrategy } from './strategies/stripe-upe';\n\nexport default function createCustomerStrategyRegistry(\n store: CheckoutStore,\n requestSender: RequestSender,\n locale: string,\n): Registry {\n const registry = new Registry();\n const scriptLoader = getScriptLoader();\n const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n const checkoutActionCreator = new CheckoutActionCreator(\n checkoutRequestSender,\n new ConfigActionCreator(new ConfigRequestSender(requestSender)),\n new FormFieldsActionCreator(new FormFieldsRequestSender(requestSender)),\n );\n const formPoster = createFormPoster();\n const paymentMethodActionCreator = new PaymentMethodActionCreator(\n new PaymentMethodRequestSender(requestSender),\n );\n const remoteCheckoutRequestSender = new RemoteCheckoutRequestSender(requestSender);\n const remoteCheckoutActionCreator = new RemoteCheckoutActionCreator(\n remoteCheckoutRequestSender,\n checkoutActionCreator,\n );\n const spamProtectionActionCreator = new SpamProtectionActionCreator(\n createSpamProtection(scriptLoader),\n new SpamProtectionRequestSender(requestSender),\n );\n const customerActionCreator = new CustomerActionCreator(\n new CustomerRequestSender(requestSender),\n checkoutActionCreator,\n spamProtectionActionCreator,\n );\n\n const braintreeSDKCreator = new BraintreeSDKCreator(new BraintreeScriptLoader(scriptLoader));\n const paymentIntegrationService = createPaymentIntegrationService(store);\n const customerRegistryV2 = createCustomerStrategyRegistryV2(paymentIntegrationService);\n\n registry.register(\n 'googlepayadyenv2',\n () =>\n new GooglePayCustomerStrategy(\n store,\n remoteCheckoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayAdyenV2Initializer()),\n formPoster,\n ),\n );\n\n registry.register(\n 'googlepayadyenv3',\n () =>\n new GooglePayCustomerStrategy(\n store,\n remoteCheckoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayAdyenV3Initializer()),\n formPoster,\n ),\n );\n\n registry.register(\n 'amazonpay',\n () =>\n new AmazonPayV2CustomerStrategy(\n store,\n paymentMethodActionCreator,\n remoteCheckoutActionCreator,\n createAmazonPayV2PaymentProcessor(),\n ),\n );\n\n registry.register(\n 'braintreevisacheckout',\n () =>\n new BraintreeVisaCheckoutCustomerStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n new CustomerStrategyActionCreator(registry, customerRegistryV2),\n remoteCheckoutActionCreator,\n createBraintreeVisaCheckoutPaymentProcessor(scriptLoader, requestSender),\n new VisaCheckoutScriptLoader(scriptLoader),\n formPoster,\n ),\n );\n\n registry.register(\n 'braintreepaypalcredit',\n () =>\n new BraintreePaypalCreditCustomerStrategy(\n store,\n checkoutActionCreator,\n customerActionCreator,\n paymentMethodActionCreator,\n braintreeSDKCreator,\n formPoster,\n window,\n ),\n );\n\n registry.register(\n 'chasepay',\n () =>\n new ChasePayCustomerStrategy(\n store,\n paymentMethodActionCreator,\n remoteCheckoutActionCreator,\n new ChasePayScriptLoader(scriptLoader),\n requestSender,\n formPoster,\n ),\n );\n\n registry.register(\n 'squarev2',\n () =>\n new SquareCustomerStrategy(\n store,\n new RemoteCheckoutActionCreator(remoteCheckoutRequestSender, checkoutActionCreator),\n ),\n );\n\n registry.register(\n 'masterpass',\n () =>\n new MasterpassCustomerStrategy(\n store,\n paymentMethodActionCreator,\n remoteCheckoutActionCreator,\n new MasterpassScriptLoader(scriptLoader),\n locale,\n ),\n );\n\n registry.register(\n 'googlepayauthorizenet',\n () =>\n new GooglePayCustomerStrategy(\n store,\n remoteCheckoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayAuthorizeNetInitializer()),\n formPoster,\n ),\n );\n\n registry.register(\n 'googlepaybnz',\n () =>\n new GooglePayCustomerStrategy(\n store,\n remoteCheckoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayBNZInitializer()),\n formPoster,\n ),\n );\n\n registry.register(\n 'googlepaybraintree',\n () =>\n new GooglePayCustomerStrategy(\n store,\n remoteCheckoutActionCreator,\n createGooglePayPaymentProcessor(\n store,\n new GooglePayBraintreeInitializer(braintreeSDKCreator),\n ),\n formPoster,\n ),\n );\n\n registry.register(\n 'googlepaycheckoutcom',\n () =>\n new GooglePayCustomerStrategy(\n store,\n remoteCheckoutActionCreator,\n createGooglePayPaymentProcessor(\n store,\n new GooglePayCheckoutcomInitializer(requestSender),\n ),\n formPoster,\n ),\n );\n\n registry.register(\n 'googlepaycybersourcev2',\n () =>\n new GooglePayCustomerStrategy(\n store,\n remoteCheckoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayCybersourceV2Initializer()),\n formPoster,\n ),\n );\n\n registry.register(\n 'googlepayorbital',\n () =>\n new GooglePayCustomerStrategy(\n store,\n remoteCheckoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayOrbitalInitializer()),\n formPoster,\n ),\n );\n\n registry.register(\n 'googlepaystripe',\n () =>\n new GooglePayCustomerStrategy(\n store,\n remoteCheckoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayStripeInitializer()),\n formPoster,\n ),\n );\n\n registry.register(\n 'googlepaystripeupe',\n () =>\n new GooglePayCustomerStrategy(\n store,\n remoteCheckoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayStripeUPEInitializer()),\n formPoster,\n ),\n );\n\n registry.register(\n 'googlepayworldpayaccess',\n () =>\n new GooglePayCustomerStrategy(\n store,\n remoteCheckoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayWorldpayAccessInitializer()),\n formPoster,\n ),\n );\n\n registry.register(\n 'stripeupe',\n () =>\n new StripeUPECustomerStrategy(\n store,\n new StripeScriptLoader(scriptLoader),\n customerActionCreator,\n paymentMethodActionCreator,\n new ConsignmentActionCreator(\n new ConsignmentRequestSender(requestSender),\n new CheckoutRequestSender(requestSender),\n ),\n ),\n );\n\n registry.register('default', () => new DefaultCustomerStrategy(store, customerActionCreator));\n\n return registry;\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { RequestSender } from '@bigcommerce/request-sender';\nimport {\n createScriptLoader,\n getScriptLoader,\n getStylesheetLoader,\n} from '@bigcommerce/script-loader';\n\nimport { BillingAddressActionCreator, BillingAddressRequestSender } from '../billing';\nimport {\n CheckoutActionCreator,\n CheckoutRequestSender,\n CheckoutStore,\n CheckoutValidator,\n} from '../checkout';\nimport { BrowserStorage } from '../common/storage';\nimport { ConfigActionCreator, ConfigRequestSender } from '../config';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport { HostedFormFactory } from '../hosted-form';\nimport { OrderActionCreator, OrderRequestSender } from '../order';\nimport { createPaymentIntegrationService } from '../payment-integration';\nimport { RemoteCheckoutActionCreator, RemoteCheckoutRequestSender } from '../remote-checkout';\nimport {\n createSpamProtection,\n GoogleRecaptcha,\n PaymentHumanVerificationHandler,\n SpamProtectionActionCreator,\n SpamProtectionRequestSender,\n} from '../spam-protection';\nimport { StoreCreditActionCreator, StoreCreditRequestSender } from '../store-credit';\nimport { SubscriptionsActionCreator, SubscriptionsRequestSender } from '../subscription';\n\nimport createPaymentStrategyRegistryV2 from './create-payment-strategy-registry-v2';\nimport PaymentActionCreator from './payment-action-creator';\nimport PaymentMethodActionCreator from './payment-method-action-creator';\nimport PaymentMethodRequestSender from './payment-method-request-sender';\nimport PaymentRequestSender from './payment-request-sender';\nimport PaymentRequestTransformer from './payment-request-transformer';\nimport PaymentStrategyActionCreator from './payment-strategy-action-creator';\nimport PaymentStrategyRegistry from './payment-strategy-registry';\nimport PaymentStrategyType from './payment-strategy-type';\nimport StorefrontPaymentRequestSender from './storefront-payment-request-sender';\nimport { AdyenV2ScriptLoader } from './strategies/adyenv2';\nimport { AdyenV3ScriptLoader } from './strategies/adyenv3';\nimport { AffirmPaymentStrategy, AffirmScriptLoader } from './strategies/affirm';\nimport { AfterpayPaymentStrategy, AfterpayScriptLoader } from './strategies/afterpay';\nimport {\n AmazonPayV2PaymentStrategy,\n createAmazonPayV2PaymentProcessor,\n} from './strategies/amazon-pay-v2';\nimport { BarclaysPaymentStrategy } from './strategies/barclays';\nimport { BlueSnapV2PaymentStrategy } from './strategies/bluesnapv2';\nimport { BNZPaymentStrategy } from './strategies/bnz';\nimport {\n BraintreeCreditCardPaymentStrategy,\n BraintreePaypalPaymentStrategy,\n BraintreeScriptLoader,\n BraintreeSDKCreator,\n BraintreeVenmoPaymentStrategy,\n BraintreeVisaCheckoutPaymentStrategy,\n createBraintreePaymentProcessor,\n createBraintreeVisaCheckoutPaymentProcessor,\n VisaCheckoutScriptLoader,\n} from './strategies/braintree';\nimport {\n CardinalClient,\n CardinalScriptLoader,\n CardinalThreeDSecureFlow,\n CardinalThreeDSecureFlowV2,\n} from './strategies/cardinal';\nimport { CBAMPGSPaymentStrategy, CBAMPGSScriptLoader } from './strategies/cba-mpgs';\nimport { ChasePayPaymentStrategy, ChasePayScriptLoader } from './strategies/chasepay';\nimport {\n CheckoutcomAPMPaymentStrategy,\n CheckoutcomFawryPaymentStrategy,\n CheckoutcomiDealPaymentStrategy,\n CheckoutcomSEPAPaymentStrategy,\n} from './strategies/checkoutcom-custom';\nimport { ClearpayPaymentStrategy, ClearpayScriptLoader } from './strategies/clearpay';\nimport { ConvergePaymentStrategy } from './strategies/converge';\nimport { CreditCardRedirectPaymentStrategy } from './strategies/credit-card-redirect';\nimport { CyberSourcePaymentStrategy } from './strategies/cybersource/index';\nimport { CyberSourceV2PaymentStrategy } from './strategies/cybersourcev2';\nimport { DigitalRiverPaymentStrategy, DigitalRiverScriptLoader } from './strategies/digitalriver';\nimport {\n createGooglePayPaymentProcessor,\n GooglePayAdyenV2Initializer,\n GooglePayAdyenV2PaymentProcessor,\n GooglePayAdyenV3Initializer,\n GooglePayAdyenV3PaymentProcessor,\n GooglePayAuthorizeNetInitializer,\n GooglePayBNZInitializer,\n GooglePayBraintreeInitializer,\n GooglePayCheckoutcomInitializer,\n GooglePayCheckoutcomPaymentProcessor,\n GooglePayCybersourceV2Initializer,\n GooglePayOrbitalInitializer,\n GooglePayPaymentStrategy,\n GooglePayStripeInitializer,\n GooglePayStripeUPEInitializer,\n GooglePayWorldpayAccessInitializer,\n} from './strategies/googlepay';\nimport { HummPaymentStrategy } from './strategies/humm';\nimport { KlarnaPaymentStrategy, KlarnaScriptLoader } from './strategies/klarna';\nimport {\n KlarnaV2PaymentStrategy,\n KlarnaV2ScriptLoader,\n KlarnaV2TokenUpdater,\n} from './strategies/klarnav2';\nimport { MasterpassPaymentStrategy, MasterpassScriptLoader } from './strategies/masterpass';\nimport { MolliePaymentStrategy, MollieScriptLoader } from './strategies/mollie';\nimport { MonerisPaymentStrategy } from './strategies/moneris';\nimport { OpyPaymentStrategy, OpyScriptLoader } from './strategies/opy';\nimport {\n PaypalExpressPaymentStrategy,\n PaypalProPaymentStrategy,\n PaypalScriptLoader,\n} from './strategies/paypal';\nimport {\n createStepHandler,\n createSubStrategyRegistry,\n PaymentResumer,\n PPSDKStrategy,\n} from './strategies/ppsdk';\nimport { QuadpayPaymentStrategy } from './strategies/quadpay';\nimport { SagePayPaymentStrategy } from './strategies/sage-pay';\nimport { SquarePaymentStrategy, SquareScriptLoader } from './strategies/square';\nimport {\n StripeUPEPaymentStrategy,\n StripeScriptLoader as StripeUPEScriptLoader,\n} from './strategies/stripe-upe';\nimport {\n StripeV3PaymentStrategy,\n StripeScriptLoader as StripeV3ScriptLoader,\n} from './strategies/stripev3';\nimport { WepayPaymentStrategy, WepayRiskClient } from './strategies/wepay';\nimport { WorldpayaccessPaymetStrategy } from './strategies/worldpayaccess';\nimport { ZipPaymentStrategy } from './strategies/zip';\n\nexport default function createPaymentStrategyRegistry(\n store: CheckoutStore,\n paymentClient: any,\n requestSender: RequestSender,\n spamProtection: GoogleRecaptcha,\n locale: string,\n) {\n const registry = new PaymentStrategyRegistry(store, {\n defaultToken: PaymentStrategyType.CREDIT_CARD,\n });\n const scriptLoader = getScriptLoader();\n const paymentRequestTransformer = new PaymentRequestTransformer();\n const paymentRequestSender = new PaymentRequestSender(paymentClient);\n const billingAddressActionCreator = new BillingAddressActionCreator(\n new BillingAddressRequestSender(requestSender),\n new SubscriptionsActionCreator(new SubscriptionsRequestSender(requestSender)),\n );\n const paymentIntegrationService = createPaymentIntegrationService(store);\n const registryV2 = createPaymentStrategyRegistryV2(paymentIntegrationService);\n const braintreePaymentProcessor = createBraintreePaymentProcessor(scriptLoader);\n const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n const checkoutValidator = new CheckoutValidator(checkoutRequestSender);\n const spamProtectionActionCreator = new SpamProtectionActionCreator(\n spamProtection,\n new SpamProtectionRequestSender(requestSender),\n );\n const orderActionCreator = new OrderActionCreator(\n new OrderRequestSender(requestSender),\n checkoutValidator,\n );\n const storeCreditActionCreator = new StoreCreditActionCreator(\n new StoreCreditRequestSender(requestSender),\n );\n const paymentHumanVerificationHandler = new PaymentHumanVerificationHandler(\n createSpamProtection(createScriptLoader()),\n );\n const paymentActionCreator = new PaymentActionCreator(\n paymentRequestSender,\n orderActionCreator,\n paymentRequestTransformer,\n paymentHumanVerificationHandler,\n );\n const paymentMethodActionCreator = new PaymentMethodActionCreator(\n new PaymentMethodRequestSender(requestSender),\n );\n const remoteCheckoutRequestSender = new RemoteCheckoutRequestSender(requestSender);\n const configActionCreator = new ConfigActionCreator(new ConfigRequestSender(requestSender));\n const formFieldsActionCreator = new FormFieldsActionCreator(\n new FormFieldsRequestSender(requestSender),\n );\n const checkoutActionCreator = new CheckoutActionCreator(\n checkoutRequestSender,\n configActionCreator,\n formFieldsActionCreator,\n );\n const remoteCheckoutActionCreator = new RemoteCheckoutActionCreator(\n remoteCheckoutRequestSender,\n checkoutActionCreator,\n );\n const paymentStrategyActionCreator = new PaymentStrategyActionCreator(\n registry,\n registryV2,\n orderActionCreator,\n spamProtectionActionCreator,\n );\n const formPoster = createFormPoster();\n const stepHandler = createStepHandler(formPoster, paymentHumanVerificationHandler);\n const hostedFormFactory = new HostedFormFactory(store);\n const storefrontPaymentRequestSender = new StorefrontPaymentRequestSender(requestSender);\n\n registry.register(\n PaymentStrategyType.ADYENV2_GOOGLEPAY,\n () =>\n new GooglePayPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayAdyenV2Initializer()),\n new GooglePayAdyenV2PaymentProcessor(\n store,\n paymentActionCreator,\n new AdyenV2ScriptLoader(scriptLoader, getStylesheetLoader()),\n ),\n ),\n );\n\n registry.register(\n PaymentStrategyType.ADYENV3_GOOGLEPAY,\n () =>\n new GooglePayPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayAdyenV3Initializer()),\n new GooglePayAdyenV3PaymentProcessor(\n store,\n paymentActionCreator,\n new AdyenV3ScriptLoader(scriptLoader, getStylesheetLoader()),\n ),\n ),\n );\n\n registry.register(\n PaymentStrategyType.AFFIRM,\n () =>\n new AffirmPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n paymentMethodActionCreator,\n new AffirmScriptLoader(),\n ),\n );\n\n registry.register(\n PaymentStrategyType.AFTERPAY,\n () =>\n new AfterpayPaymentStrategy(\n store,\n checkoutValidator,\n orderActionCreator,\n paymentActionCreator,\n paymentMethodActionCreator,\n remoteCheckoutRequestSender,\n storeCreditActionCreator,\n new AfterpayScriptLoader(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.AMAZONPAY,\n () =>\n new AmazonPayV2PaymentStrategy(\n store,\n paymentStrategyActionCreator,\n orderActionCreator,\n paymentActionCreator,\n createAmazonPayV2PaymentProcessor(),\n ),\n );\n\n registry.register(\n PaymentStrategyType.AUTHORIZENET_GOOGLE_PAY,\n () =>\n new GooglePayPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayAuthorizeNetInitializer()),\n ),\n );\n\n registry.register(\n PaymentStrategyType.BARCLAYS,\n () =>\n new BarclaysPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n new CardinalThreeDSecureFlowV2(\n store,\n paymentActionCreator,\n new CardinalClient(new CardinalScriptLoader(scriptLoader)),\n ),\n ),\n );\n\n registry.register(\n PaymentStrategyType.BLUESNAPV2,\n () => new BlueSnapV2PaymentStrategy(store, orderActionCreator, paymentActionCreator),\n );\n\n registry.register(\n PaymentStrategyType.BRAINTREE,\n () =>\n new BraintreeCreditCardPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n paymentMethodActionCreator,\n braintreePaymentProcessor,\n ),\n );\n\n registry.register(\n PaymentStrategyType.BRAINTREE_GOOGLE_PAY,\n () =>\n new GooglePayPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createGooglePayPaymentProcessor(\n store,\n new GooglePayBraintreeInitializer(\n new BraintreeSDKCreator(new BraintreeScriptLoader(scriptLoader)),\n ),\n ),\n undefined,\n new BraintreeSDKCreator(new BraintreeScriptLoader(scriptLoader)),\n ),\n );\n\n registry.register(\n PaymentStrategyType.BRAINTREE_PAYPAL,\n () =>\n new BraintreePaypalPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n paymentMethodActionCreator,\n braintreePaymentProcessor,\n ),\n );\n\n registry.register(\n PaymentStrategyType.BRAINTREE_VENMO,\n () =>\n new BraintreeVenmoPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n paymentMethodActionCreator,\n braintreePaymentProcessor,\n ),\n );\n\n registry.register(\n PaymentStrategyType.BRAINTREE_PAYPAL_CREDIT,\n () =>\n new BraintreePaypalPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n paymentMethodActionCreator,\n braintreePaymentProcessor,\n true,\n ),\n );\n\n registry.register(\n PaymentStrategyType.BRAINTREE_VISA_CHECKOUT,\n () =>\n new BraintreeVisaCheckoutPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createBraintreeVisaCheckoutPaymentProcessor(scriptLoader, requestSender),\n new VisaCheckoutScriptLoader(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.CBA_MPGS,\n () =>\n new CBAMPGSPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n paymentMethodActionCreator,\n new CBAMPGSScriptLoader(scriptLoader),\n locale,\n ),\n );\n\n registry.register(\n PaymentStrategyType.CONVERGE,\n () =>\n new ConvergePaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n formPoster,\n ),\n );\n\n registry.register(\n PaymentStrategyType.CLEARPAY,\n () =>\n new ClearpayPaymentStrategy(\n store,\n checkoutValidator,\n orderActionCreator,\n paymentActionCreator,\n paymentMethodActionCreator,\n remoteCheckoutRequestSender,\n storeCreditActionCreator,\n new ClearpayScriptLoader(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.CYBERSOURCE,\n () =>\n new CyberSourcePaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n new CardinalThreeDSecureFlow(\n store,\n paymentActionCreator,\n paymentMethodActionCreator,\n new CardinalClient(new CardinalScriptLoader(scriptLoader)),\n ),\n ),\n );\n\n registry.register(\n PaymentStrategyType.CYBERSOURCEV2,\n () =>\n new CyberSourceV2PaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n new CardinalThreeDSecureFlowV2(\n store,\n paymentActionCreator,\n new CardinalClient(new CardinalScriptLoader(scriptLoader)),\n ),\n ),\n );\n\n registry.register(\n PaymentStrategyType.BNZ,\n () =>\n new BNZPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n new CardinalThreeDSecureFlowV2(\n store,\n paymentActionCreator,\n new CardinalClient(new CardinalScriptLoader(scriptLoader)),\n ),\n ),\n );\n\n registry.register(\n PaymentStrategyType.CYBERSOURCEV2_GOOGLE_PAY,\n () =>\n new GooglePayPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayCybersourceV2Initializer()),\n ),\n );\n\n registry.register(\n PaymentStrategyType.BNZ_GOOGLEPAY,\n () =>\n new GooglePayPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayBNZInitializer()),\n ),\n );\n\n registry.register(\n PaymentStrategyType.CHECKOUTCOM,\n () =>\n new CreditCardRedirectPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n formPoster,\n ),\n );\n\n registry.register(\n PaymentStrategyType.CHECKOUTCOM_APM,\n () =>\n new CheckoutcomAPMPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n ),\n );\n\n registry.register(\n PaymentStrategyType.CHECKOUTCOM_FAWRY,\n () =>\n new CheckoutcomFawryPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n ),\n );\n\n registry.register(\n PaymentStrategyType.CHECKOUTCOM_GOOGLE_PAY,\n () =>\n new GooglePayPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createGooglePayPaymentProcessor(\n store,\n new GooglePayCheckoutcomInitializer(requestSender),\n ),\n new GooglePayCheckoutcomPaymentProcessor(),\n ),\n );\n\n registry.register(\n PaymentStrategyType.CHECKOUTCOM_IDEAL,\n () =>\n new CheckoutcomiDealPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n ),\n );\n\n registry.register(\n PaymentStrategyType.CHECKOUTCOM_SEPA,\n () =>\n new CheckoutcomSEPAPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n ),\n );\n\n registry.register(\n PaymentStrategyType.CHASE_PAY,\n () =>\n new ChasePayPaymentStrategy(\n store,\n checkoutActionCreator,\n orderActionCreator,\n paymentActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n requestSender,\n new ChasePayScriptLoader(scriptLoader),\n new WepayRiskClient(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.DIGITALRIVER,\n () =>\n new DigitalRiverPaymentStrategy(\n store,\n paymentMethodActionCreator,\n orderActionCreator,\n paymentActionCreator,\n storeCreditActionCreator,\n new DigitalRiverScriptLoader(scriptLoader, getStylesheetLoader()),\n billingAddressActionCreator,\n ),\n );\n\n registry.register(\n PaymentStrategyType.KLARNA,\n () =>\n new KlarnaPaymentStrategy(\n store,\n orderActionCreator,\n paymentMethodActionCreator,\n remoteCheckoutActionCreator,\n new KlarnaScriptLoader(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.KLARNAV2,\n () =>\n new KlarnaV2PaymentStrategy(\n store,\n orderActionCreator,\n remoteCheckoutActionCreator,\n new KlarnaV2ScriptLoader(scriptLoader),\n new KlarnaV2TokenUpdater(requestSender),\n ),\n );\n\n registry.register(\n PaymentStrategyType.HUMM,\n () =>\n new HummPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n formPoster,\n paymentMethodActionCreator,\n ),\n );\n\n registry.register(\n PaymentStrategyType.MASTERPASS,\n () =>\n new MasterpassPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n new MasterpassScriptLoader(scriptLoader),\n locale,\n ),\n );\n\n registry.register(\n PaymentStrategyType.MOLLIE,\n () =>\n new MolliePaymentStrategy(\n hostedFormFactory,\n store,\n new MollieScriptLoader(scriptLoader),\n orderActionCreator,\n paymentActionCreator,\n ),\n );\n\n registry.register(\n PaymentStrategyType.MONERIS,\n () =>\n new MonerisPaymentStrategy(\n hostedFormFactory,\n store,\n orderActionCreator,\n paymentActionCreator,\n storeCreditActionCreator,\n ),\n );\n\n registry.register(\n PaymentStrategyType.OPY,\n () =>\n new OpyPaymentStrategy(\n store,\n orderActionCreator,\n paymentMethodActionCreator,\n storefrontPaymentRequestSender,\n paymentActionCreator,\n new OpyScriptLoader(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.ORBITAL_GOOGLE_PAY,\n () =>\n new GooglePayPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayOrbitalInitializer()),\n ),\n );\n\n registry.register(\n PaymentStrategyType.PAYPAL,\n () =>\n new PaypalProPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n new CardinalThreeDSecureFlow(\n store,\n paymentActionCreator,\n paymentMethodActionCreator,\n new CardinalClient(new CardinalScriptLoader(scriptLoader)),\n ),\n ),\n );\n\n registry.register(\n PaymentStrategyType.PAYPAL_EXPRESS,\n () =>\n new PaypalExpressPaymentStrategy(\n store,\n orderActionCreator,\n new PaypalScriptLoader(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.PAYPAL_EXPRESS_CREDIT,\n () =>\n new PaypalExpressPaymentStrategy(\n store,\n orderActionCreator,\n new PaypalScriptLoader(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.PPSDK,\n () =>\n new PPSDKStrategy(\n store,\n orderActionCreator,\n createSubStrategyRegistry(\n store,\n orderActionCreator,\n requestSender,\n stepHandler,\n hostedFormFactory,\n ),\n new PaymentResumer(requestSender, stepHandler),\n new BrowserStorage('PPSDK'),\n ),\n );\n\n registry.register(\n PaymentStrategyType.QUADPAY,\n () =>\n new QuadpayPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n paymentMethodActionCreator,\n storeCreditActionCreator,\n remoteCheckoutActionCreator,\n storefrontPaymentRequestSender,\n ),\n );\n\n registry.register(\n PaymentStrategyType.SAGE_PAY,\n () =>\n new SagePayPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n formPoster,\n ),\n );\n\n registry.register(\n PaymentStrategyType.SQUARE,\n () =>\n new SquarePaymentStrategy(\n store,\n checkoutActionCreator,\n orderActionCreator,\n paymentActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n requestSender,\n new SquareScriptLoader(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.STRIPE_GOOGLE_PAY,\n () =>\n new GooglePayPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayStripeInitializer()),\n ),\n );\n\n registry.register(\n PaymentStrategyType.STRIPE_UPE_GOOGLE_PAY,\n () =>\n new GooglePayPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayStripeUPEInitializer()),\n ),\n );\n\n registry.register(\n PaymentStrategyType.STRIPEV3,\n () =>\n new StripeV3PaymentStrategy(\n store,\n paymentMethodActionCreator,\n paymentActionCreator,\n orderActionCreator,\n new StripeV3ScriptLoader(scriptLoader),\n storeCreditActionCreator,\n hostedFormFactory,\n locale,\n ),\n );\n\n registry.register(\n PaymentStrategyType.STRIPE_UPE,\n () =>\n new StripeUPEPaymentStrategy(\n store,\n paymentMethodActionCreator,\n paymentActionCreator,\n orderActionCreator,\n new StripeUPEScriptLoader(scriptLoader),\n storeCreditActionCreator,\n billingAddressActionCreator,\n ),\n );\n\n registry.register(\n PaymentStrategyType.WE_PAY,\n () =>\n new WepayPaymentStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n new WepayRiskClient(scriptLoader),\n ),\n );\n\n registry.register(\n PaymentStrategyType.WORLDPAYACCESS,\n () =>\n new WorldpayaccessPaymetStrategy(\n store,\n orderActionCreator,\n paymentActionCreator,\n hostedFormFactory,\n ),\n );\n\n registry.register(\n PaymentStrategyType.WORLDPAYACCESS_GOOGLE_PAY,\n () =>\n new GooglePayPaymentStrategy(\n store,\n checkoutActionCreator,\n paymentMethodActionCreator,\n paymentStrategyActionCreator,\n paymentActionCreator,\n orderActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayWorldpayAccessInitializer()),\n ),\n );\n\n registry.register(\n PaymentStrategyType.ZIP,\n () =>\n new ZipPaymentStrategy(\n store,\n paymentMethodActionCreator,\n storeCreditActionCreator,\n remoteCheckoutActionCreator,\n orderActionCreator,\n storefrontPaymentRequestSender,\n paymentActionCreator,\n ),\n );\n\n return registry;\n}\n","import { ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { Overlay } from '@bigcommerce/checkout-sdk/ui';\n\nimport BraintreeHostedForm from './braintree-hosted-form';\nimport BraintreePaymentProcessor from './braintree-payment-processor';\nimport BraintreeScriptLoader from './braintree-script-loader';\nimport BraintreeSDKCreator from './braintree-sdk-creator';\n\nexport default function createBraintreePaymentProcessor(scriptLoader: ScriptLoader) {\n const braintreeScriptLoader = new BraintreeScriptLoader(scriptLoader);\n const braintreeSDKCreator = new BraintreeSDKCreator(braintreeScriptLoader);\n const braintreeHostedForm = new BraintreeHostedForm(braintreeSDKCreator);\n const overlay = new Overlay();\n\n return new BraintreePaymentProcessor(braintreeSDKCreator, braintreeHostedForm, overlay);\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { CheckoutRequestSender, CheckoutStore } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { PaymentMethodActionCreator, PaymentMethodRequestSender } from '../payment';\nimport { createAmazonPayV2PaymentProcessor } from '../payment/strategies/amazon-pay-v2';\nimport { StripeScriptLoader } from '../payment/strategies/stripe-upe';\n\nimport ConsignmentActionCreator from './consignment-action-creator';\nimport ConsignmentRequestSender from './consignment-request-sender';\nimport ShippingStrategyActionCreator from './shipping-strategy-action-creator';\nimport { ShippingStrategy } from './strategies';\nimport { AmazonPayV2ShippingStrategy } from './strategies/amazon-pay-v2';\nimport { DefaultShippingStrategy } from './strategies/default';\nimport { StripeUPEShippingStrategy } from './strategies/stripe-upe';\n\nexport default function createShippingStrategyRegistry(\n store: CheckoutStore,\n requestSender: RequestSender,\n): Registry {\n const registry = new Registry();\n const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n const consignmentRequestSender = new ConsignmentRequestSender(requestSender);\n const consignmentActionCreator = new ConsignmentActionCreator(\n consignmentRequestSender,\n checkoutRequestSender,\n );\n const paymentMethodActionCreator = new PaymentMethodActionCreator(\n new PaymentMethodRequestSender(requestSender),\n );\n const scriptLoader = getScriptLoader();\n\n registry.register(\n 'amazonpay',\n () =>\n new AmazonPayV2ShippingStrategy(\n store,\n consignmentActionCreator,\n new PaymentMethodActionCreator(new PaymentMethodRequestSender(requestSender)),\n createAmazonPayV2PaymentProcessor(),\n new ShippingStrategyActionCreator(registry),\n ),\n );\n\n registry.register(\n 'stripeupe',\n () =>\n new StripeUPEShippingStrategy(\n store,\n new StripeScriptLoader(scriptLoader),\n consignmentActionCreator,\n paymentMethodActionCreator,\n ),\n );\n\n registry.register(\n 'default',\n () => new DefaultShippingStrategy(store, consignmentActionCreator),\n );\n\n return registry;\n}\n","export interface RootCacheKeyMap {\n maps: ChildCacheKeyMap[];\n}\n\nexport interface IntermediateCacheKeyMap {\n maps: ChildCacheKeyMap[];\n parentMap: RootCacheKeyMap | IntermediateCacheKeyMap;\n usedCount: number;\n value: any;\n}\n\nexport interface TerminalCacheKeyMap extends IntermediateCacheKeyMap {\n cacheKey: string;\n}\n\nexport type ChildCacheKeyMap = IntermediateCacheKeyMap | TerminalCacheKeyMap;\n\nexport function isTerminalCacheKeyMap(map: ChildCacheKeyMap): map is TerminalCacheKeyMap {\n return Object.prototype.hasOwnProperty.call(map, 'cacheKey');\n}\n\nexport function isRootCacheKeyMap(map: RootCacheKeyMap | ChildCacheKeyMap): map is RootCacheKeyMap {\n return Object.prototype.hasOwnProperty.call(map, 'parentMap');\n}\n","import { noop } from 'lodash';\nimport shallowEqual from 'shallowequal';\n\nimport {\n ChildCacheKeyMap,\n IntermediateCacheKeyMap,\n isRootCacheKeyMap,\n isTerminalCacheKeyMap,\n RootCacheKeyMap,\n TerminalCacheKeyMap,\n} from './cache-key-maps';\n\nexport interface CacheKeyResolverOptions {\n maxSize?: number;\n onExpire?(key: string): void;\n isEqual?(valueA: any, valueB: any): boolean;\n}\n\ninterface ResolveResult {\n index: number;\n parentMap: RootCacheKeyMap | IntermediateCacheKeyMap;\n map?: TerminalCacheKeyMap;\n}\n\nexport default class CacheKeyResolver {\n private _lastId = 0;\n private _map: RootCacheKeyMap = { maps: [] };\n private _usedMaps: TerminalCacheKeyMap[] = [];\n private _options: Required;\n\n constructor(options?: CacheKeyResolverOptions) {\n this._options = {\n maxSize: 0,\n isEqual: shallowEqual,\n onExpire: noop,\n ...options,\n };\n }\n\n getKey(...args: any[]): string {\n const result = this._resolveMap(...args);\n const { index, parentMap } = result;\n let { map } = result;\n\n if (map && map.cacheKey) {\n map.usedCount++;\n } else {\n map = this._generateMap(parentMap, args.slice(index));\n }\n\n // Keep track of the least used map so we can remove it if the size of\n // the stack exceeds the maximum size.\n this._removeLeastUsedMap(map);\n\n return map.cacheKey;\n }\n\n getUsedCount(...args: any[]): number {\n const { map } = this._resolveMap(...args);\n\n return map ? map.usedCount : 0;\n }\n\n private _resolveMap(...args: any[]): ResolveResult {\n let index = 0;\n let parentMap = this._map;\n\n // Traverse the tree to find the linked list of maps that match the\n // arguments of the call. Each intermediate or terminal map contains a\n // value that could be used to match with the arguments. The last map in\n // the list (the terminal) should contain a cache key. If it can does\n // not exist, we will return a falsy value so that the caller could\n // handle and generate a new cache key.\n while (parentMap.maps.length) {\n let isMatched = false;\n\n for (let mapIndex = 0; mapIndex < parentMap.maps.length; mapIndex++) {\n const map = parentMap.maps[mapIndex];\n\n if (!this._options.isEqual(map.value, args[index])) {\n continue;\n }\n\n // Move the most recently used map to the top of the stack for\n // quicker access\n parentMap.maps.unshift(...parentMap.maps.splice(mapIndex, 1));\n\n if (\n (args.length === 0 || index === args.length - 1) &&\n isTerminalCacheKeyMap(map)\n ) {\n return { index, map, parentMap };\n }\n\n isMatched = true;\n parentMap = map;\n index++;\n\n break;\n }\n\n if (!isMatched) {\n break;\n }\n }\n\n return { index, parentMap };\n }\n\n private _generateMap(\n parent: RootCacheKeyMap | IntermediateCacheKeyMap,\n args: any[],\n ): TerminalCacheKeyMap {\n let index = 0;\n let parentMap = parent;\n let map: IntermediateCacheKeyMap;\n\n do {\n map = {\n maps: [],\n parentMap,\n usedCount: 1,\n value: args[index],\n };\n\n // Continue to build the tree of maps so that it could be resolved\n // next time when the function is called with the same set of\n // arguments.\n parentMap.maps.unshift(map);\n\n parentMap = map;\n index++;\n } while (index < args.length);\n\n const terminalMap = map as TerminalCacheKeyMap;\n\n terminalMap.cacheKey = `${++this._lastId}`;\n\n return terminalMap;\n }\n\n private _removeLeastUsedMap(recentlyUsedMap: TerminalCacheKeyMap): void {\n if (!this._options.maxSize) {\n return;\n }\n\n const index = this._usedMaps.indexOf(recentlyUsedMap);\n\n this._usedMaps.splice(index === -1 ? 0 : index, index === -1 ? 0 : 1, recentlyUsedMap);\n\n if (this._usedMaps.length <= this._options.maxSize) {\n return;\n }\n\n const map = this._usedMaps.pop();\n\n if (!map) {\n return;\n }\n\n this._removeMap(map);\n this._options.onExpire(map.cacheKey);\n }\n\n private _removeMap(map: ChildCacheKeyMap): void {\n if (!map.parentMap) {\n return;\n }\n\n map.parentMap.maps.splice(map.parentMap.maps.indexOf(map), 1);\n\n if (isRootCacheKeyMap(map.parentMap)) {\n return;\n }\n\n this._removeMap(map.parentMap);\n }\n}\n","import { memoize } from '@bigcommerce/memoize';\n\nimport { bindDecorator, CacheKeyResolver, isEqual, isPrivate } from '../utility';\n\n/**\n * Decorates a class by patching all of its methods to cache their return values\n * and return them if they are called again with the same set of parameters. The\n * decorator also binds all the methods to the calling instance so it can be\n * destructed.\n */\nexport default function selectorDecorator>(target: T): T {\n const decoratedTarget = class extends target {};\n\n Object.getOwnPropertyNames(target.prototype).forEach((key) => {\n const descriptor = Object.getOwnPropertyDescriptor(target.prototype, key);\n\n if (!descriptor || key === 'constructor') {\n return;\n }\n\n Object.defineProperty(\n decoratedTarget.prototype,\n key,\n selectorMethodDecorator(target.prototype, key, descriptor),\n );\n });\n\n return decoratedTarget;\n}\n\nfunction selectorMethodDecorator(\n target: object,\n key: string,\n descriptor: TypedPropertyDescriptor,\n): TypedPropertyDescriptor {\n if (typeof descriptor.value !== 'function') {\n return descriptor;\n }\n\n let resolver = new CacheKeyResolver();\n let method = descriptor.value;\n let memoizedMethod = memoize(method);\n\n return bindDecorator(target, key, {\n get() {\n const value = ((...args: any[]) => {\n const cachedValue = memoizedMethod.call(this, ...args);\n\n if (resolver.getUsedCount(...args) === 1) {\n return cachedValue;\n }\n\n const newValue = method.call(this, ...args);\n\n if (isEqual(newValue, cachedValue, { keyFilter: (key) => !isPrivate(key) })) {\n return cachedValue;\n }\n\n memoizedMethod.cache.set(resolver.getKey(...args), newValue);\n\n return newValue;\n }) as T;\n\n Object.defineProperty(this, key, { ...descriptor, value });\n\n return value;\n },\n set(value) {\n resolver = new CacheKeyResolver();\n method = value;\n memoizedMethod = memoize(method);\n },\n });\n}\n\nexport type Constructor = new (...args: any[]) => T;\ntype Method = (...args: any[]) => any;\n","export default function isPrivate(key: string): boolean {\n return `${key}`.indexOf('$$') === 0 || `${key}`.indexOf('_') === 0;\n}\n","import { InternalCheckoutSelectors } from '../checkout';\nimport { selector } from '../common/selector';\n\nimport CheckoutButtonSelector from './checkout-button-selector';\nimport { CheckoutButtonMethodType } from './strategies';\n\n@selector\nexport default class CheckoutButtonErrorSelector {\n private _checkoutButton: CheckoutButtonSelector;\n\n /**\n * @internal\n */\n constructor(selectors: InternalCheckoutSelectors) {\n this._checkoutButton = selectors.checkoutButton;\n }\n\n getInitializeButtonError(methodId?: CheckoutButtonMethodType): Error | undefined {\n return this._checkoutButton.getInitializeError(methodId);\n }\n\n getDeinitializeButtonError(methodId?: CheckoutButtonMethodType): Error | undefined {\n return this._checkoutButton.getDeinitializeError(methodId);\n }\n}\n","import { InternalCheckoutSelectors } from '../checkout';\nimport { selector } from '../common/selector';\n\nimport CheckoutButtonSelector from './checkout-button-selector';\nimport { CheckoutButtonMethodType } from './strategies';\n\n@selector\nexport default class CheckoutButtonStatusSelector {\n private _checkoutButton: CheckoutButtonSelector;\n\n /**\n * @internal\n */\n constructor(selectors: InternalCheckoutSelectors) {\n this._checkoutButton = selectors.checkoutButton;\n }\n\n isInitializingButton(methodId?: CheckoutButtonMethodType): boolean {\n return this._checkoutButton.isInitializing(methodId);\n }\n\n isDeinitializingButton(methodId?: CheckoutButtonMethodType): boolean {\n return this._checkoutButton.isDeinitializing(methodId);\n }\n}\n","import { InternalCheckoutSelectors } from '../checkout';\n\nimport CheckoutButtonErrorSelector from './checkout-button-error-selector';\nimport CheckoutButtonSelectors from './checkout-button-selectors';\nimport CheckoutButtonStatusSelector from './checkout-button-status-selector';\n\nexport default function createCheckoutButtonSelectors(\n selectors: InternalCheckoutSelectors,\n): CheckoutButtonSelectors {\n const errors = new CheckoutButtonErrorSelector(selectors);\n const statuses = new CheckoutButtonStatusSelector(selectors);\n\n return {\n errors,\n statuses,\n };\n}\n","import { CheckoutStore, InternalCheckoutSelectors } from '../checkout';\nimport { isElementId, setUniqueElementId } from '../common/dom';\nimport { bindDecorator as bind } from '../common/utility';\n\nimport { CheckoutButtonInitializeOptions, CheckoutButtonOptions } from './checkout-button-options';\nimport CheckoutButtonSelectors from './checkout-button-selectors';\nimport CheckoutButtonStrategyActionCreator from './checkout-button-strategy-action-creator';\nimport createCheckoutButtonSelectors from './create-checkout-button-selectors';\n\n@bind\nexport default class CheckoutButtonInitializer {\n private _state: CheckoutButtonSelectors;\n\n /**\n * @internal\n */\n constructor(\n private _store: CheckoutStore,\n private _buttonStrategyActionCreator: CheckoutButtonStrategyActionCreator,\n ) {\n this._state = createCheckoutButtonSelectors(this._store.getState());\n\n this._store.subscribe((state) => {\n this._state = createCheckoutButtonSelectors(state);\n });\n }\n\n /**\n * Returns a snapshot of the current state.\n *\n * The method returns a new instance every time there is a change in the\n * state. You can query the state by calling any of its getter methods.\n *\n * ```js\n * const state = service.getState();\n *\n * console.log(state.errors.getInitializeButtonError());\n * console.log(state.statuses.isInitializingButton());\n * ```\n *\n * @returns The current customer's checkout state\n */\n getState(): CheckoutButtonSelectors {\n return this._state;\n }\n\n /**\n * Subscribes to any changes to the current state.\n *\n * The method registers a callback function and executes it every time there\n * is a change in the current state.\n *\n * ```js\n * service.subscribe(state => {\n * console.log(state.statuses.isInitializingButton());\n * });\n * ```\n *\n * The method can be configured to notify subscribers only regarding\n * relevant changes, by providing a filter function.\n *\n * ```js\n * const filter = state => state.errors.getInitializeButtonError();\n *\n * // Only trigger the subscriber when the cart changes.\n * service.subscribe(state => {\n * console.log(state.errors.getInitializeButtonError())\n * }, filter);\n * ```\n *\n * @param subscriber - The function to subscribe to state changes.\n * @param filters - One or more functions to filter out irrelevant state\n * changes. If more than one function is provided, the subscriber will only\n * be triggered if all conditions are met.\n * @returns A function, if called, will unsubscribe the subscriber.\n */\n subscribe(\n subscriber: (state: CheckoutButtonSelectors) => void,\n ...filters: Array<(state: CheckoutButtonSelectors) => any>\n ): () => void {\n return this._store.subscribe(\n () => subscriber(this.getState()),\n (state) => state.checkoutButton.getState(),\n ...filters.map(\n (filter) => (state: InternalCheckoutSelectors) =>\n filter(createCheckoutButtonSelectors(state)),\n ),\n );\n }\n\n /**\n * Initializes the checkout button of a payment method.\n *\n * When the checkout button is initialized, it will be inserted into the DOM,\n * ready to be interacted with by the customer.\n *\n * ```js\n * initializer.initializeButton({\n * methodId: 'braintreepaypal',\n * containerId: 'checkoutButton',\n * braintreepaypal: {\n * },\n * });\n * ```\n *\n * @param options - Options for initializing the checkout button.\n * @returns A promise that resolves to the current state.\n */\n initializeButton(options: CheckoutButtonInitializeOptions): Promise {\n const containerIds = isElementId(options.containerId)\n ? [options.containerId]\n : setUniqueElementId(options.containerId, `${options.methodId}-container`);\n\n return Promise.all(\n containerIds.map((containerId) => {\n const action = this._buttonStrategyActionCreator.initialize({\n ...options,\n containerId,\n });\n const queueId = `checkoutButtonStrategy:${options.methodId}:${containerId}`;\n\n return this._store.dispatch(action, { queueId });\n }),\n ).then(() => this.getState());\n }\n\n /**\n * De-initializes the checkout button by performing any necessary clean-ups.\n *\n * ```js\n * await service.deinitializeButton({\n * methodId: 'braintreepaypal',\n * });\n * ```\n *\n * @param options - Options for deinitializing the checkout button.\n * @returns A promise that resolves to the current state.\n */\n deinitializeButton(options: CheckoutButtonOptions): Promise {\n const action = this._buttonStrategyActionCreator.deinitialize(options);\n const queueId = `checkoutButtonStrategy:${options.methodId}`;\n\n return this._store.dispatch(action, { queueId }).then(() => this.getState());\n }\n}\n","/* eslint-disable no-useless-escape */\nexport default function isElementId(id: string): boolean {\n return /^\\w[\\w\\-\\:\\.]*$/.test(id);\n}\n","import { uniqueId } from 'lodash';\n\nimport { InvalidArgumentError } from '../error/errors';\n\nexport default function setUniqueElementId(selector: string, idPrefix: string): string[] {\n const containers = document.querySelectorAll(selector);\n\n if (!containers.length) {\n throw new InvalidArgumentError(\n `Unable to find any element with the specified selector: ${selector}`,\n );\n }\n\n return Array.prototype.slice.call(containers).map((container: HTMLElement) => {\n if (!container.id) {\n container.id = uniqueId(idPrefix);\n }\n\n return container.id;\n });\n}\n","import { createAction, ThunkAction } from '@bigcommerce/data-store';\nimport { concat, defer, empty, of } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { CheckoutButtonStrategy as CheckoutButtonStrategyV2 } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { InternalCheckoutSelectors } from '../checkout';\nimport { throwErrorAction } from '../common/error';\nimport { Registry } from '../common/registry';\nimport { PaymentMethodActionCreator } from '../payment';\n\nimport {\n CheckoutButtonActionType,\n DeinitializeButtonAction,\n InitializeButtonAction,\n} from './checkout-button-actions';\nimport { CheckoutButtonInitializeOptions, CheckoutButtonOptions } from './checkout-button-options';\nimport CheckoutButtonRegistryV2 from './checkout-button-strategy-registry-v2';\nimport { CheckoutButtonMethodType, CheckoutButtonStrategy } from './strategies';\n\nexport default class CheckoutButtonStrategyActionCreator {\n constructor(\n private _registry: Registry,\n private _registryV2: CheckoutButtonRegistryV2,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n ) {}\n\n initialize(\n options: CheckoutButtonInitializeOptions,\n ): ThunkAction {\n return (store) => {\n const meta = {\n methodId: options.methodId,\n containerId: options.containerId,\n };\n\n if (\n store.getState().checkoutButton.isInitialized(options.methodId, options.containerId)\n ) {\n return empty();\n }\n\n const paymentMethodRequestParams = options.currencyCode\n ? { params: { currencyCode: options.currencyCode } }\n : {};\n\n const paymentMethodRequestOptions = {\n ...paymentMethodRequestParams,\n timeout: options.timeout,\n useCache: true,\n };\n\n return concat(\n of(\n createAction(\n CheckoutButtonActionType.InitializeButtonRequested,\n undefined,\n meta,\n ),\n ),\n this._paymentMethodActionCreator.loadPaymentMethod(\n options.methodId,\n paymentMethodRequestOptions,\n )(store),\n defer(() =>\n this._getStrategy(options.methodId)\n .initialize(options)\n .then(() =>\n createAction(\n CheckoutButtonActionType.InitializeButtonSucceeded,\n undefined,\n meta,\n ),\n ),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(CheckoutButtonActionType.InitializeButtonFailed, error, meta),\n ),\n );\n };\n }\n\n deinitialize(\n options: CheckoutButtonOptions,\n ): ThunkAction {\n return (store) => {\n const meta = { methodId: options.methodId };\n\n if (!store.getState().checkoutButton.isInitialized(options.methodId)) {\n return empty();\n }\n\n return concat(\n of(\n createAction(\n CheckoutButtonActionType.DeinitializeButtonRequested,\n undefined,\n meta,\n ),\n ),\n defer(() =>\n this._getStrategy(options.methodId)\n .deinitialize()\n .then(() =>\n createAction(\n CheckoutButtonActionType.DeinitializeButtonSucceeded,\n undefined,\n meta,\n ),\n ),\n ),\n ).pipe(\n catchError((error) =>\n throwErrorAction(\n CheckoutButtonActionType.DeinitializeButtonFailed,\n error,\n meta,\n ),\n ),\n );\n };\n }\n\n private _getStrategy(\n methodId: CheckoutButtonMethodType,\n ): CheckoutButtonStrategy | CheckoutButtonStrategyV2 {\n let strategy: CheckoutButtonStrategy | CheckoutButtonStrategyV2;\n\n try {\n strategy = this._registryV2.get({ id: methodId });\n } catch {\n strategy = this._registry.get(methodId);\n }\n\n return strategy;\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\n/**\n * This error should be thrown when a shopper tries to sign in as a guest but\n * they are already signed in as a registered customer.\n */\nexport default class BuyNowCartCreationError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'An unexpected error has occurred during buy now cart creation process. Please try again later.',\n );\n\n this.name = 'BuyNowCartCreationError';\n this.type = 'buy_now_cart_creation_error';\n }\n}\n","import { BuyNowCartRequestBody } from '../../../cart';\nimport {\n AmazonPayV2ButtonConfig,\n AmazonPayV2ButtonParameters,\n} from '../../../payment/strategies/amazon-pay-v2';\n\nexport function isWithBuyNowFeatures(options: unknown): options is WithBuyNowFeature {\n if (!(options instanceof Object)) {\n return false;\n }\n\n return 'buyNowInitializeOptions' in options;\n}\n\nexport interface WithBuyNowFeature extends AmazonPayV2ButtonConfig {\n /**\n * The options that are required to initialize Buy Now functionality.\n */\n buyNowInitializeOptions?: {\n getBuyNowCartRequestBody?(): BuyNowCartRequestBody | void;\n };\n}\n\n/**\n * The required config to render the AmazonPayV2 button.\n */\nexport type AmazonPayV2ButtonInitializeOptions = AmazonPayV2ButtonParameters | WithBuyNowFeature;\n","import { StandardError } from '../../../../common/error/errors';\n\nexport default class AmazonPayV2ConfigCreationError extends StandardError {\n constructor(message?: string) {\n super(\n message ||\n 'An unexpected error has occurred during config creation process. Please try again later.',\n );\n\n this.name = 'AmazonPayV2ConfigCreationError';\n this.type = 'amazon_pay_v2_config_creation_error';\n }\n}\n","import { CartRequestSender } from '../../../cart';\nimport BuyNowCartRequestBody from '../../../cart/buy-now-cart-request-body';\nimport { BuyNowCartCreationError } from '../../../cart/errors';\nimport { CheckoutActionCreator, CheckoutStore } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n} from '../../../common/error/errors';\nimport {\n AmazonPayV2CheckoutSessionConfig,\n AmazonPayV2PaymentProcessor,\n AmazonPayV2PayOptions,\n AmazonPayV2Placement,\n} from '../../../payment/strategies/amazon-pay-v2';\nimport { getShippableItemsCount } from '../../../shipping';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nimport { isWithBuyNowFeatures } from './amazon-pay-v2-button-options';\nimport AmazonPayV2RequestSender from './amazon-pay-v2-request-sender';\nimport AmazonPayV2ConfigCreationError from './errors/amazon-pay-v2-config-creation-error';\n\nexport default class AmazonPayV2ButtonStrategy implements CheckoutButtonStrategy {\n private _buyNowCartRequestBody?: BuyNowCartRequestBody | void;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _amazonPayV2PaymentProcessor: AmazonPayV2PaymentProcessor,\n private _cartRequestSender: CartRequestSender,\n private _amazonPayV2ConfigRequestSender: AmazonPayV2RequestSender,\n ) {}\n\n async initialize(options: CheckoutButtonInitializeOptions): Promise {\n const { methodId, containerId, amazonpay } = options;\n const { buttonColor } = amazonpay || {};\n\n if (!methodId || !containerId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"methodId\" or \"containerId\" argument is not provided.',\n );\n }\n\n const {\n paymentMethods: { getPaymentMethodOrThrow },\n } = this._store.getState();\n\n await this._amazonPayV2PaymentProcessor.initialize(getPaymentMethodOrThrow(methodId));\n\n if (!amazonpay) {\n await this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout());\n }\n\n const initializeAmazonButtonOptions = isWithBuyNowFeatures(amazonpay)\n ? undefined\n : amazonpay;\n\n if (\n isWithBuyNowFeatures(amazonpay) &&\n typeof amazonpay?.buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function'\n ) {\n this._buyNowCartRequestBody =\n amazonpay.buyNowInitializeOptions.getBuyNowCartRequestBody();\n\n if (this._buyNowCartRequestBody) {\n this._amazonPayV2PaymentProcessor.setCartRequestBody(this._buyNowCartRequestBody);\n }\n }\n\n this._amazonPayV2PaymentProcessor.renderAmazonPayButton({\n checkoutState: this._store.getState(),\n containerId,\n methodId,\n options: initializeAmazonButtonOptions,\n placement: AmazonPayV2Placement.Cart,\n buttonColor,\n });\n\n if (this._buyNowCartRequestBody) {\n this._amazonPayV2PaymentProcessor.prepareCheckoutWithCreationRequestConfig(\n this._getCheckoutCreationRequestConfig.bind(this),\n );\n }\n }\n\n deinitialize(): Promise {\n return this._amazonPayV2PaymentProcessor.deinitialize();\n }\n\n private async _createBuyNowCart() {\n if (!this._buyNowCartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n const { body: buyNowCart } = await this._cartRequestSender.createBuyNowCart(\n this._buyNowCartRequestBody,\n );\n\n return buyNowCart;\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n\n private async _createCheckoutConfig(\n id: string,\n ): Promise> {\n try {\n const {\n body: { payload, public_key, ...rest },\n } = await this._amazonPayV2ConfigRequestSender.createCheckoutConfig(id);\n\n return {\n payloadJSON: payload,\n publicKeyId: public_key,\n ...rest,\n };\n } catch (error) {\n throw new AmazonPayV2ConfigCreationError();\n }\n }\n\n private async _getCheckoutCreationRequestConfig() {\n const buyNowCart = await this._createBuyNowCart();\n\n const estimatedOrderAmount = {\n amount: String(buyNowCart.baseAmount),\n currencyCode: buyNowCart.currency.code,\n };\n\n const createCheckoutSessionConfig = await this._createCheckoutConfig(buyNowCart.id);\n\n return {\n createCheckoutSessionConfig,\n estimatedOrderAmount,\n productType:\n getShippableItemsCount(buyNowCart) === 0\n ? AmazonPayV2PayOptions.PayOnly\n : AmazonPayV2PayOptions.PayAndShip,\n };\n }\n}\n","import { RequestSender, Response } from '@bigcommerce/request-sender';\n\nimport { ContentType, INTERNAL_USE_ONLY, SDK_VERSION_HEADERS } from '../../../common/http-request';\n\nexport interface CheckoutConfig {\n payload: string;\n signature: string;\n public_key: string;\n}\n\nexport default class AmazonPayV2RequestSender {\n constructor(private _requestSender: RequestSender) {}\n\n createCheckoutConfig(cartId: string | number): Promise> {\n const body = { cartId };\n const headers = {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n 'Content-Type': ContentType.Json,\n ...SDK_VERSION_HEADERS,\n };\n\n return this._requestSender.post('/api/storefront/payment/amazonpay', { headers, body });\n }\n}\n","import { isNil, omitBy } from 'lodash';\n\nimport { PaypalStyleOptions } from '../../../payment/strategies/paypal';\n\nexport default function getValidButtonStyle(style: PaypalStyleOptions): PaypalStyleOptions {\n const { color, fundingicons, height, layout, shape, size, tagline } = style;\n\n const validStyles = {\n color,\n fundingicons,\n height: getValidHeight(height),\n layout,\n shape: shape || 'rect',\n size,\n tagline,\n };\n\n return omitBy(validStyles, isNil);\n}\n\nfunction getValidHeight(height?: number): number {\n const minHeight = 25;\n const maxHeight = 55;\n\n if (typeof height !== 'number' || height > maxHeight) {\n return maxHeight;\n }\n\n if (height < minHeight) {\n return minHeight;\n }\n\n return height;\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { Cart, CartRequestSender } from '../../../cart';\nimport { BuyNowCartCreationError } from '../../../cart/errors';\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n StandardError,\n} from '../../../common/error/errors';\nimport PaymentMethod from '../../../payment/payment-method';\nimport {\n BraintreeError,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeSDKCreator,\n BraintreeTokenizePayload,\n mapToBraintreeShippingAddressOverride,\n} from '../../../payment/strategies/braintree';\nimport { PaypalAuthorizeData, PaypalHostWindow } from '../../../payment/strategies/paypal';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nimport { BraintreePaypalButtonInitializeOptions } from './braintree-paypal-button-options';\nimport getValidButtonStyle from './get-valid-button-style';\nimport mapToLegacyBillingAddress from './map-to-legacy-billing-address';\nimport mapToLegacyShippingAddress from './map-to-legacy-shipping-address';\n\ntype BuyNowInitializeOptions = Pick<\n BraintreePaypalButtonInitializeOptions,\n 'buyNowInitializeOptions'\n>;\n\nexport default class BraintreePaypalButtonStrategy implements CheckoutButtonStrategy {\n private _buyNowCart?: Cart;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _cartRequestSender: CartRequestSender,\n private _braintreeSDKCreator: BraintreeSDKCreator,\n private _formPoster: FormPoster,\n private _window: PaypalHostWindow,\n ) {}\n\n async initialize(options: CheckoutButtonInitializeOptions): Promise {\n const { braintreepaypal, containerId, methodId } = options;\n const { messagingContainerId, onError } = braintreepaypal || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!braintreepaypal) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypal\" argument is not provided.`,\n );\n }\n\n let state: InternalCheckoutSelectors;\n let paymentMethod: PaymentMethod;\n let currencyCode: string;\n\n if (braintreepaypal.buyNowInitializeOptions) {\n state = this._store.getState();\n paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n if (!braintreepaypal.currencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypal.currencyCode\" argument is not provided.`,\n );\n }\n\n currencyCode = braintreepaypal.currencyCode;\n } else {\n state = await this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout());\n paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n currencyCode = state.cart.getCartOrThrow().currency.code;\n }\n\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const paypalCheckoutOptions: Partial = {\n currency: currencyCode,\n intent: paymentMethod.initializationData?.intent,\n isCreditEnabled: paymentMethod.initializationData?.isCreditEnabled,\n };\n\n const paypalCheckoutSuccessCallback = (\n braintreePaypalCheckout: BraintreePaypalCheckout,\n ) => {\n this._renderPayPalComponents(\n braintreePaypalCheckout,\n braintreepaypal,\n containerId,\n methodId,\n Boolean(paymentMethod.config.testMode),\n );\n };\n const paypalCheckoutErrorCallback = (error: BraintreeError) =>\n this._handleError(error, containerId, messagingContainerId, onError);\n\n this._braintreeSDKCreator.initialize(paymentMethod.clientToken);\n await this._braintreeSDKCreator.getPaypalCheckout(\n paypalCheckoutOptions,\n paypalCheckoutSuccessCallback,\n paypalCheckoutErrorCallback,\n );\n }\n\n deinitialize(): Promise {\n this._braintreeSDKCreator.teardown();\n\n return Promise.resolve();\n }\n\n private _renderPayPalComponents(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypal: BraintreePaypalButtonInitializeOptions,\n containerId: string,\n methodId: string,\n testMode: boolean,\n ): void {\n const { messagingContainerId } = braintreepaypal;\n\n this._renderPayPalMessages(messagingContainerId);\n this._renderPayPalButton(\n braintreePaypalCheckout,\n braintreepaypal,\n containerId,\n methodId,\n testMode,\n );\n }\n\n private _renderPayPalButton(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypal: BraintreePaypalButtonInitializeOptions,\n containerId: string,\n methodId: string,\n testMode: boolean,\n ): void {\n const { style, shouldProcessPayment, onAuthorizeError } = braintreepaypal;\n\n const { paypal } = this._window;\n const fundingSource = paypal?.FUNDING.PAYPAL;\n\n if (paypal && fundingSource) {\n const validButtonStyle = style ? getValidButtonStyle(style) : {};\n\n const paypalButtonRender = paypal.Buttons({\n env: testMode ? 'sandbox' : 'production',\n commit: false,\n fundingSource,\n style: validButtonStyle,\n createOrder: () =>\n this._setupPayment(braintreePaypalCheckout, braintreepaypal, methodId),\n onApprove: (authorizeData: PaypalAuthorizeData) =>\n this._tokenizePayment(\n authorizeData,\n braintreePaypalCheckout,\n methodId,\n shouldProcessPayment,\n onAuthorizeError,\n ),\n });\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${containerId}`);\n }\n } else {\n this._removeElement(containerId);\n }\n }\n\n private _renderPayPalMessages(messagingContainerId?: string): void {\n const isMessageContainerAvailable =\n messagingContainerId && Boolean(document.getElementById(messagingContainerId));\n const { paypal } = this._window;\n\n if (paypal && isMessageContainerAvailable) {\n const state = this._store.getState();\n const cart = state.cart.getCartOrThrow();\n\n const paypalMessagesRender = paypal.Messages({\n amount: cart.cartAmount,\n placement: 'cart',\n });\n\n paypalMessagesRender.render(`#${messagingContainerId}`);\n } else {\n this._removeElement(messagingContainerId);\n }\n }\n\n private async _setupPayment(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypal: BraintreePaypalButtonInitializeOptions,\n methodId: string,\n ): Promise {\n const { buyNowInitializeOptions, shippingAddress, onPaymentError } = braintreepaypal;\n let state: InternalCheckoutSelectors;\n\n try {\n this._buyNowCart = await this._createBuyNowCart({ buyNowInitializeOptions });\n\n if (this._buyNowCart) {\n state = this._store.getState();\n } else {\n state = await this._store.dispatch(\n this._checkoutActionCreator.loadDefaultCheckout(),\n );\n }\n\n const customer = state.customer.getCustomer();\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n const amount = this._buyNowCart\n ? this._buyNowCart.cartAmount\n : state.checkout.getCheckoutOrThrow().outstandingBalance;\n const currencyCode =\n braintreepaypal.currencyCode ?? state.config.getStoreConfigOrThrow().currency.code;\n\n const address = shippingAddress || customer?.addresses[0];\n const shippingAddressOverride = address\n ? mapToBraintreeShippingAddressOverride(address)\n : undefined;\n\n return await braintreePaypalCheckout.createPayment({\n flow: 'checkout',\n enableShippingAddress: true,\n shippingAddressEditable: false,\n shippingAddressOverride,\n amount,\n currency: currencyCode,\n offerCredit: false,\n intent: paymentMethod.initializationData?.intent,\n });\n } catch (error) {\n if (onPaymentError) {\n onPaymentError(error);\n }\n\n throw error;\n }\n }\n\n private async _createBuyNowCart({ buyNowInitializeOptions }: BuyNowInitializeOptions) {\n if (typeof buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function') {\n const cartRequestBody = buyNowInitializeOptions.getBuyNowCartRequestBody();\n\n if (!cartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n const { body: cart } = await this._cartRequestSender.createBuyNowCart(\n cartRequestBody,\n );\n\n return cart;\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n }\n\n private async _tokenizePayment(\n authorizeData: PaypalAuthorizeData,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n methodId: string,\n shouldProcessPayment?: boolean,\n onError?: (error: BraintreeError | StandardError) => void,\n ): Promise {\n try {\n const { deviceData } = await this._braintreeSDKCreator.getDataCollector({\n paypal: true,\n });\n const tokenizePayload = await braintreePaypalCheckout.tokenizePayment(authorizeData);\n const { details, nonce } = tokenizePayload;\n const buyNowCartId = this._buyNowCart?.id;\n\n this._formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n provider: methodId,\n action: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n nonce,\n device_data: deviceData,\n billing_address: JSON.stringify(mapToLegacyBillingAddress(details)),\n shipping_address: JSON.stringify(mapToLegacyShippingAddress(details)),\n ...(buyNowCartId && { cart_id: buyNowCartId }),\n });\n\n return tokenizePayload;\n } catch (error) {\n if (onError) {\n onError(error);\n }\n\n throw error;\n }\n }\n\n private _handleError(\n error: BraintreeError,\n buttonContainerId: string,\n messagingContainerId?: string,\n onErrorCallback?: (error: BraintreeError) => void,\n ): void {\n this._removeElement(buttonContainerId);\n this._removeElement(messagingContainerId);\n\n if (onErrorCallback) {\n onErrorCallback(error);\n }\n }\n\n private _removeElement(elementId?: string): void {\n const element = elementId && document.getElementById(elementId);\n\n if (element) {\n element.remove();\n }\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport { Cart, CartRequestSender } from '../../../cart';\nimport { BuyNowCartCreationError } from '../../../cart/errors';\nimport { CheckoutActionCreator, CheckoutStore, InternalCheckoutSelectors } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n StandardError,\n} from '../../../common/error/errors';\nimport PaymentMethod from '../../../payment/payment-method';\nimport {\n BraintreeError,\n BraintreePaypalCheckout,\n BraintreePaypalSdkCreatorConfig,\n BraintreeSDKCreator,\n BraintreeTokenizePayload,\n mapToBraintreeShippingAddressOverride,\n} from '../../../payment/strategies/braintree';\nimport {\n PaypalAuthorizeData,\n PaypalButtonStyleLabelOption,\n PaypalHostWindow,\n} from '../../../payment/strategies/paypal';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nimport { BraintreePaypalCreditButtonInitializeOptions } from './braintree-paypal-credit-button-options';\nimport getValidButtonStyle from './get-valid-button-style';\nimport mapToLegacyBillingAddress from './map-to-legacy-billing-address';\nimport mapToLegacyShippingAddress from './map-to-legacy-shipping-address';\n\ntype BuyNowInitializeOptions = Pick<\n BraintreePaypalCreditButtonInitializeOptions,\n 'buyNowInitializeOptions'\n>;\n\nexport default class BraintreePaypalCreditButtonStrategy implements CheckoutButtonStrategy {\n private _buyNowCart?: Cart;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _cartRequestSender: CartRequestSender,\n private _braintreeSDKCreator: BraintreeSDKCreator,\n private _formPoster: FormPoster,\n private _window: PaypalHostWindow,\n ) {}\n\n async initialize(options: CheckoutButtonInitializeOptions): Promise {\n const { braintreepaypalcredit, containerId, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!braintreepaypalcredit) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypalcredit\" argument is not provided.`,\n );\n }\n\n let state: InternalCheckoutSelectors;\n let paymentMethod: PaymentMethod;\n let currencyCode: string;\n\n if (braintreepaypalcredit.buyNowInitializeOptions) {\n state = this._store.getState();\n paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n if (!braintreepaypalcredit.currencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.braintreepaypalcredit.currencyCode\" argument is not provided.`,\n );\n }\n\n currencyCode = braintreepaypalcredit.currencyCode;\n } else {\n state = await this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout());\n paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n currencyCode = state.cart.getCartOrThrow().currency.code;\n }\n\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const paypalCheckoutOptions: Partial = {\n currency: currencyCode,\n intent: paymentMethod.initializationData?.intent,\n isCreditEnabled: paymentMethod.initializationData?.isCreditEnabled,\n };\n\n const paypalCheckoutCallback = (braintreePaypalCheckout: BraintreePaypalCheckout) =>\n this._renderPayPalButton(\n braintreePaypalCheckout,\n braintreepaypalcredit,\n containerId,\n methodId,\n Boolean(paymentMethod.config.testMode),\n );\n const paypalCheckoutErrorCallback = (error: BraintreeError) =>\n this._handleError(error, containerId, braintreepaypalcredit.onError);\n\n this._braintreeSDKCreator.initialize(paymentMethod.clientToken);\n await this._braintreeSDKCreator.getPaypalCheckout(\n paypalCheckoutOptions,\n paypalCheckoutCallback,\n paypalCheckoutErrorCallback,\n );\n }\n\n deinitialize(): Promise {\n this._braintreeSDKCreator.teardown();\n\n return Promise.resolve();\n }\n\n private _renderPayPalButton(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypalcredit: BraintreePaypalCreditButtonInitializeOptions,\n containerId: string,\n methodId: string,\n testMode: boolean,\n ): void {\n const { style, shouldProcessPayment, onAuthorizeError } = braintreepaypalcredit;\n const { paypal } = this._window;\n\n let hasRenderedSmartButton = false;\n\n if (paypal) {\n const fundingSources = [paypal.FUNDING.PAYLATER, paypal.FUNDING.CREDIT];\n const commonButtonStyle = style ? getValidButtonStyle(style) : {};\n\n fundingSources.forEach((fundingSource) => {\n const buttonStyle =\n fundingSource === paypal.FUNDING.CREDIT\n ? { label: PaypalButtonStyleLabelOption.CREDIT, ...commonButtonStyle }\n : commonButtonStyle;\n\n if (!hasRenderedSmartButton) {\n const paypalButtonRender = paypal.Buttons({\n env: testMode ? 'sandbox' : 'production',\n commit: false,\n fundingSource,\n style: buttonStyle,\n createOrder: () =>\n this._setupPayment(\n braintreePaypalCheckout,\n braintreepaypalcredit,\n methodId,\n ),\n onApprove: (authorizeData: PaypalAuthorizeData) =>\n this._tokenizePayment(\n authorizeData,\n braintreePaypalCheckout,\n methodId,\n shouldProcessPayment,\n onAuthorizeError,\n ),\n });\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${containerId}`);\n hasRenderedSmartButton = true;\n }\n }\n });\n }\n\n if (!paypal || !hasRenderedSmartButton) {\n this._removeElement(containerId);\n }\n }\n\n private async _setupPayment(\n braintreePaypalCheckout: BraintreePaypalCheckout,\n braintreepaypalcredit: BraintreePaypalCreditButtonInitializeOptions,\n methodId: string,\n ): Promise {\n const { onPaymentError, shippingAddress, buyNowInitializeOptions } = braintreepaypalcredit;\n let state: InternalCheckoutSelectors;\n\n try {\n this._buyNowCart = await this._createBuyNowCart({ buyNowInitializeOptions });\n\n if (this._buyNowCart) {\n state = this._store.getState();\n } else {\n state = await this._store.dispatch(\n this._checkoutActionCreator.loadDefaultCheckout(),\n );\n }\n\n const customer = state.customer.getCustomer();\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n const amount = this._buyNowCart\n ? this._buyNowCart.cartAmount\n : state.checkout.getCheckoutOrThrow().outstandingBalance;\n const currencyCode =\n braintreepaypalcredit.currencyCode ??\n state.config.getStoreConfigOrThrow().currency.code;\n\n const address = shippingAddress || customer?.addresses[0];\n const shippingAddressOverride = address\n ? mapToBraintreeShippingAddressOverride(address)\n : undefined;\n\n return await braintreePaypalCheckout.createPayment({\n flow: 'checkout',\n enableShippingAddress: true,\n shippingAddressEditable: false,\n shippingAddressOverride,\n amount,\n currency: currencyCode,\n offerCredit: true,\n intent: paymentMethod.initializationData?.intent,\n });\n } catch (error) {\n if (onPaymentError) {\n onPaymentError(error);\n }\n\n throw error;\n }\n }\n\n private async _createBuyNowCart({ buyNowInitializeOptions }: BuyNowInitializeOptions) {\n if (typeof buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function') {\n const cartRequestBody = buyNowInitializeOptions.getBuyNowCartRequestBody();\n\n if (!cartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n const { body: buyNowCart } = await this._cartRequestSender.createBuyNowCart(\n cartRequestBody,\n );\n\n return buyNowCart;\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n }\n\n private async _tokenizePayment(\n authorizeData: PaypalAuthorizeData,\n braintreePaypalCheckout: BraintreePaypalCheckout,\n methodId: string,\n shouldProcessPayment?: boolean,\n onError?: (error: BraintreeError | StandardError) => void,\n ): Promise {\n try {\n const { deviceData } = await this._braintreeSDKCreator.getDataCollector({\n paypal: true,\n });\n const tokenizePayload = await braintreePaypalCheckout.tokenizePayment(authorizeData);\n const { details, nonce } = tokenizePayload;\n const buyNowCartId = this._buyNowCart?.id;\n\n this._formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n provider: methodId,\n action: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n nonce,\n device_data: deviceData,\n billing_address: JSON.stringify(mapToLegacyBillingAddress(details)),\n shipping_address: JSON.stringify(mapToLegacyShippingAddress(details)),\n ...(buyNowCartId && { cart_id: buyNowCartId }),\n });\n\n return tokenizePayload;\n } catch (error) {\n if (onError) {\n onError(error);\n }\n\n throw error;\n }\n }\n\n private _handleError(\n error: BraintreeError,\n containerId: string,\n onErrorCallback?: (error: BraintreeError) => void,\n ): void {\n this._removeElement(containerId);\n\n if (onErrorCallback) {\n onErrorCallback(error);\n }\n }\n\n private _removeElement(elementId?: string): void {\n const element = elementId && document.getElementById(elementId);\n\n if (element) {\n element.remove();\n }\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { noop } from 'lodash';\n\nimport { BuyNowCartRequestBody, CartRequestSender } from '../../../cart';\nimport { BuyNowCartCreationError } from '../../../cart/errors';\nimport { CheckoutStore } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n UnsupportedBrowserError,\n} from '../../../common/error/errors';\nimport { PaymentMethodActionCreator } from '../../../payment';\nimport {\n BraintreeError,\n BraintreeSDKCreator,\n BraintreeTokenizePayload,\n BraintreeVenmoCheckout,\n} from '../../../payment/strategies/braintree';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\nimport { CheckoutButtonMethodType } from '../index';\n\nimport mapToLegacyBillingAddress from './map-to-legacy-billing-address';\nimport mapToLegacyShippingAddress from './map-to-legacy-shipping-address';\n\nconst venmoButtonStyle = {\n backgroundColor: '#3D95CE',\n backgroundPosition: '50% 50%',\n backgroundSize: '80px auto',\n backgroundImage: 'url(\"/app/assets/img/payment-providers/venmo-logo-white.svg\")',\n backgroundRepeat: 'no-repeat',\n borderRadius: '4px',\n cursor: 'pointer',\n transition: '0.2s ease',\n minHeight: '40px',\n minWidth: '150px',\n height: '100%',\n width: '100%',\n};\n\nconst venmoButtonStyleHover = {\n backgroundColor: '#0a7fc2',\n};\n\ninterface BuyNowInitializeOptions {\n getBuyNowCartRequestBody?(): BuyNowCartRequestBody | void;\n}\n\nexport default class BraintreeVenmoButtonStrategy implements CheckoutButtonStrategy {\n private _onError = noop;\n\n constructor(\n private _store: CheckoutStore,\n private _paymentMethodActionCreator: PaymentMethodActionCreator,\n private _cartRequestSender: CartRequestSender,\n private _braintreeSDKCreator: BraintreeSDKCreator,\n private _formPoster: FormPoster,\n ) {}\n\n async initialize(options: CheckoutButtonInitializeOptions): Promise {\n const { braintreevenmo, containerId, methodId } = options;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n const state = await this._store.dispatch(\n this._paymentMethodActionCreator.loadPaymentMethod(methodId),\n );\n const paymentMethod = state.paymentMethods.getPaymentMethodOrThrow(methodId);\n\n if (!paymentMethod.clientToken) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n this._onError = braintreevenmo?.onError || this._handleError;\n\n this._braintreeSDKCreator.initialize(paymentMethod.clientToken);\n await this._braintreeSDKCreator.getVenmoCheckout(\n (braintreeVenmoCheckout) =>\n this._handleInitializationVenmoSuccess(\n braintreeVenmoCheckout,\n containerId,\n braintreevenmo?.buyNowInitializeOptions,\n ),\n (error) => this._handleInitializationVenmoError(error, containerId),\n );\n }\n\n deinitialize(): Promise {\n this._braintreeSDKCreator.teardown();\n\n return Promise.resolve();\n }\n\n private _handleError(error: BraintreeError) {\n throw new Error(error.message);\n }\n\n private _handleInitializationVenmoSuccess(\n braintreeVenmoCheckout: BraintreeVenmoCheckout,\n parentContainerId: string,\n buyNowInitializeOptions?: BuyNowInitializeOptions,\n ): void {\n return this._renderVenmoButton(\n braintreeVenmoCheckout,\n parentContainerId,\n buyNowInitializeOptions,\n );\n }\n\n private _handleInitializationVenmoError(\n error: BraintreeError | UnsupportedBrowserError,\n containerId: string,\n ): void {\n this._removeVenmoContainer(containerId);\n\n return this._onError(error);\n }\n\n private _removeVenmoContainer(containerId: string): void {\n const buttonContainer = document.getElementById(containerId);\n\n if (buttonContainer) {\n buttonContainer.remove();\n }\n }\n\n private _renderVenmoButton(\n braintreeVenmoCheckout: BraintreeVenmoCheckout,\n containerId: string,\n buyNowInitializeOptions?: BuyNowInitializeOptions,\n ): void {\n const venmoButton = document.getElementById(containerId);\n\n if (!venmoButton) {\n throw new InvalidArgumentError(\n 'Unable to create wallet button without valid container ID.',\n );\n }\n\n venmoButton.setAttribute('aria-label', 'Venmo');\n Object.assign(venmoButton.style, venmoButtonStyle);\n\n venmoButton.addEventListener('click', async () => {\n venmoButton.setAttribute('disabled', 'true');\n\n const buyBowCart = await this._createBuyNowCart(buyNowInitializeOptions);\n\n if (braintreeVenmoCheckout.tokenize) {\n braintreeVenmoCheckout.tokenize(\n async (error: BraintreeError, payload: BraintreeTokenizePayload) => {\n venmoButton.removeAttribute('disabled');\n\n if (error) {\n return this._onError(error);\n }\n\n await this._handlePostForm(payload, buyBowCart?.id);\n },\n );\n }\n });\n\n venmoButton.addEventListener('mouseenter', () => {\n venmoButton.style.backgroundColor = venmoButtonStyleHover.backgroundColor;\n });\n\n venmoButton.addEventListener('mouseleave', () => {\n venmoButton.style.backgroundColor = venmoButtonStyle.backgroundColor;\n });\n }\n\n private async _createBuyNowCart(buyNowInitializeOptions?: BuyNowInitializeOptions) {\n if (typeof buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function') {\n const cartRequestBody = buyNowInitializeOptions.getBuyNowCartRequestBody();\n\n if (!cartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n const { body: buyNowCart } = await this._cartRequestSender.createBuyNowCart(\n cartRequestBody,\n );\n\n return buyNowCart;\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n }\n\n private async _handlePostForm(\n payload: BraintreeTokenizePayload,\n buyNowCartId?: string,\n ): Promise {\n const { deviceData } = await this._braintreeSDKCreator.getDataCollector();\n const { nonce, details } = payload;\n\n this._formPoster.postForm('/checkout.php', {\n nonce,\n provider: CheckoutButtonMethodType.BRAINTREE_VENMO,\n payment_type: 'paypal',\n device_data: deviceData,\n action: 'set_external_checkout',\n billing_address: JSON.stringify(mapToLegacyBillingAddress(details)),\n shipping_address: JSON.stringify(mapToLegacyShippingAddress(details)),\n ...(buyNowCartId && { cart_id: buyNowCartId }),\n });\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { CheckoutButtonMethodType } from '../';\nimport { Cart, CartRequestSender } from '../../../cart';\nimport { BuyNowCartCreationError } from '../../../cart/errors';\nimport { CheckoutActionCreator, CheckoutStore } from '../../../checkout';\nimport { SDK_VERSION_HEADERS } from '../../../common/http-request';\nimport { bindDecorator as bind } from '../../../common/utility';\nimport {\n CallbackIntentsType,\n CallbackTriggerType,\n EnvironmentType,\n GooglePayPaymentOptions,\n GooglePayPaymentProcessor,\n IntermediatePaymentData,\n NewTransactionInfo,\n TotalPriceStatusType,\n} from '../../../payment/strategies/googlepay';\nimport { GooglePayBuyNowInitializeOptions } from './googlepay-button-types';\nimport { getShippableItemsCount } from '../../../shipping';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nimport { GooglePayButtonInitializeOptions } from './googlepay-button-options';\n\nexport default class GooglePayButtonStrategy implements CheckoutButtonStrategy {\n private _methodId?: string;\n private _walletButton?: HTMLElement;\n private _buyNowCart?: Cart;\n private _isBuyNowFlow?: boolean;\n\n constructor(\n private _store: CheckoutStore,\n private _formPoster: FormPoster,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _googlePayPaymentProcessor: GooglePayPaymentProcessor,\n private _cartRequestSender: CartRequestSender,\n ) {}\n\n async initialize(options: CheckoutButtonInitializeOptions): Promise {\n const { containerId, methodId, currencyCode } = options;\n\n const googlePayOptions = this._getGooglePayOptions(options);\n const { buyNowInitializeOptions } = googlePayOptions;\n\n if (!containerId || !methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"containerId\" argument is not provided.',\n );\n }\n\n const state = this._store.getState();\n const paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n const { testMode } = paymentMethod?.config || {};\n\n this._methodId = methodId;\n\n this._isBuyNowFlow = !!buyNowInitializeOptions;\n\n if (this._isBuyNowFlow) {\n if (!currencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.currencyCode\" argument is not provided.`,\n );\n }\n\n const { buyNowInitializeOptions } = googlePayOptions;\n this._googlePayPaymentProcessor.updateBuyNowFlowFlag(this._isBuyNowFlow);\n\n await this._googlePayPaymentProcessor.initialize(\n this._getMethodId(),\n this._getGooglePayClientOptions(currencyCode, testMode, buyNowInitializeOptions),\n );\n } else {\n await this._store.dispatch(this._checkoutActionCreator.loadDefaultCheckout());\n await this._googlePayPaymentProcessor.initialize(this._getMethodId());\n }\n\n this._walletButton = this._createSignInButton(containerId, googlePayOptions, currencyCode);\n }\n\n deinitialize(): Promise {\n if (this._walletButton && this._walletButton.parentNode) {\n this._walletButton.parentNode.removeChild(this._walletButton);\n this._walletButton = undefined;\n }\n\n return this._googlePayPaymentProcessor.deinitialize();\n }\n\n private _getGooglePayClientOptions(\n currencyCode: string,\n testMode?: boolean,\n buyNowInitializeOptions?: GooglePayBuyNowInitializeOptions,\n ): GooglePayPaymentOptions {\n const environment: EnvironmentType = testMode ? 'TEST' : 'PRODUCTION';\n\n return {\n environment,\n paymentDataCallbacks: {\n onPaymentDataChanged: async ({\n callbackTrigger,\n }: IntermediatePaymentData): Promise => {\n if (callbackTrigger !== CallbackTriggerType.INITIALIZE) {\n return;\n }\n\n try {\n this._buyNowCart = await this._createBuyNowCart(buyNowInitializeOptions);\n\n if (this._buyNowCart) {\n const { id, cartAmount } = this._buyNowCart;\n\n await this._store.dispatch(\n this._checkoutActionCreator.loadCheckout(id),\n );\n\n return {\n newTransactionInfo: {\n currencyCode,\n totalPrice: String(cartAmount),\n totalPriceStatus: TotalPriceStatusType.FINAL,\n },\n };\n }\n } catch (error) {\n throw new BuyNowCartCreationError(error);\n }\n },\n },\n };\n }\n\n private _createSignInButton(\n containerId: string,\n buttonOptions: GooglePayButtonInitializeOptions,\n currencyCode?: string,\n ): HTMLElement {\n const container = document.getElementById(containerId);\n const { buttonType, buttonColor } = buttonOptions;\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to create sign-in button without valid container ID.',\n );\n }\n\n const onClick = (event: Event) => this._handleWalletButtonClick(event, currencyCode);\n\n const googlePayButton = this._googlePayPaymentProcessor.createButton(\n onClick,\n buttonType,\n buttonColor,\n );\n\n container.appendChild(googlePayButton);\n\n return googlePayButton;\n }\n\n private _getMethodId(): string {\n if (!this._methodId) {\n throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized);\n }\n\n return this._methodId;\n }\n\n private _getGooglePayOptions(\n options: CheckoutButtonInitializeOptions,\n ): GooglePayButtonInitializeOptions {\n if (\n options.methodId === CheckoutButtonMethodType.GOOGLEPAY_ADYENV2 &&\n options.googlepayadyenv2\n ) {\n return options.googlepayadyenv2;\n }\n\n if (\n options.methodId === CheckoutButtonMethodType.GOOGLEPAY_ADYENV3 &&\n options.googlepayadyenv3\n ) {\n return options.googlepayadyenv3;\n }\n\n if (\n options.methodId === CheckoutButtonMethodType.GOOGLEPAY_AUTHORIZENET &&\n options.googlepayauthorizenet\n ) {\n return options.googlepayauthorizenet;\n }\n\n if (options.methodId === CheckoutButtonMethodType.GOOGLEPAY_BNZ && options.googlepaybnz) {\n return options.googlepaybnz;\n }\n\n if (\n options.methodId === CheckoutButtonMethodType.GOOGLEPAY_BRAINTREE &&\n options.googlepaybraintree\n ) {\n return options.googlepaybraintree;\n }\n\n if (\n options.methodId === CheckoutButtonMethodType.GOOGLEPAY_CHECKOUTCOM &&\n options.googlepaycheckoutcom\n ) {\n return options.googlepaycheckoutcom;\n }\n\n if (\n options.methodId === CheckoutButtonMethodType.GOOGLEPAY_CYBERSOURCEV2 &&\n options.googlepaycybersourcev2\n ) {\n return options.googlepaycybersourcev2;\n }\n\n if (\n options.methodId === CheckoutButtonMethodType.GOOGLEPAY_ORBITAL &&\n options.googlepayorbital\n ) {\n return options.googlepayorbital;\n }\n\n if (\n options.methodId === CheckoutButtonMethodType.GOOGLEPAY_STRIPE &&\n options.googlepaystripe\n ) {\n return options.googlepaystripe;\n }\n\n if (\n options.methodId === CheckoutButtonMethodType.GOOGLEPAY_STRIPEUPE &&\n options.googlepaystripeupe\n ) {\n return options.googlepaystripeupe;\n }\n\n if (\n options.methodId === CheckoutButtonMethodType.GOOGLEPAY_WORLDPAYACCESS &&\n options.googlepayworldpayaccess\n ) {\n return options.googlepayworldpayaccess;\n }\n\n throw new InvalidArgumentError();\n }\n\n private async _createBuyNowCart(\n buyNowInitializeOptions?: GooglePayBuyNowInitializeOptions,\n ): Promise {\n if (typeof buyNowInitializeOptions?.getBuyNowCartRequestBody === 'function') {\n const cartRequestBody = buyNowInitializeOptions.getBuyNowCartRequestBody();\n\n if (!cartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n try {\n const { body: cart } = await this._cartRequestSender.createBuyNowCart(\n cartRequestBody,\n );\n\n return cart;\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n }\n\n @bind\n private async _handleWalletButtonClick(event: Event, currencyCode?: string): Promise {\n event.preventDefault();\n\n try {\n if (this._isBuyNowFlow && currencyCode) {\n this._googlePayPaymentProcessor.updatePaymentDataRequest({\n transactionInfo: {\n currencyCode,\n totalPrice: '0',\n totalPriceStatus: TotalPriceStatusType.ESTIMATED,\n },\n callbackIntents: [CallbackIntentsType.OFFER],\n });\n }\n const paymentData = await this._googlePayPaymentProcessor.displayWallet();\n\n await this._googlePayPaymentProcessor.handleSuccess(paymentData);\n\n const cart = this._store.getState().cart.getCartOrThrow();\n const hasPhysicalItems = getShippableItemsCount(cart) > 0;\n\n if (hasPhysicalItems && paymentData.shippingAddress) {\n await this._googlePayPaymentProcessor.updateShippingAddress(\n paymentData.shippingAddress,\n );\n }\n\n await this._onPaymentSelectComplete();\n } catch (error) {\n if (error && error.message !== 'CANCELED') {\n throw error;\n }\n }\n }\n\n private _onPaymentSelectComplete(): void {\n const buyNowCartId = this._buyNowCart?.id;\n\n this._formPoster.postForm('/checkout.php', {\n headers: {\n Accept: 'text/html',\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...SDK_VERSION_HEADERS,\n },\n ...(buyNowCartId && {\n action: 'set_external_checkout',\n provider: this._methodId,\n cart_id: buyNowCartId,\n }),\n });\n }\n}\n","import { CheckoutActionCreator, CheckoutStore } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n} from '../../../common/error/errors';\nimport { bindDecorator as bind } from '../../../common/utility';\nimport {\n formatLocale,\n getCallbackUrl,\n Masterpass,\n MasterpassCheckoutOptions,\n MasterpassScriptLoader,\n} from '../../../payment/strategies/masterpass';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nexport default class MasterpassButtonStrategy implements CheckoutButtonStrategy {\n private _masterpassClient?: Masterpass;\n private _methodId?: string;\n private _signInButton?: HTMLElement;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _masterpassScriptLoader: MasterpassScriptLoader,\n private _locale: string,\n ) {}\n\n initialize(options: CheckoutButtonInitializeOptions): Promise {\n const { containerId, methodId } = options;\n\n if (!containerId || !methodId) {\n throw new InvalidArgumentError(\n 'Unable to proceed because \"containerId\" argument is not provided.',\n );\n }\n\n this._methodId = methodId;\n\n return this._store\n .dispatch(this._checkoutActionCreator.loadDefaultCheckout())\n .then((state) => {\n const paymentMethod = state.paymentMethods.getPaymentMethod(methodId);\n\n if (!paymentMethod || !paymentMethod.initializationData.checkoutId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const masterpassScriptLoaderParams = {\n useMasterpassSrc: paymentMethod.initializationData.isMasterpassSrcEnabled,\n language: formatLocale(this._locale),\n testMode: paymentMethod.config.testMode,\n checkoutId: paymentMethod.initializationData.checkoutId,\n };\n\n return this._masterpassScriptLoader.load(masterpassScriptLoaderParams);\n })\n .then((masterpass) => {\n this._masterpassClient = masterpass;\n this._signInButton = this._createSignInButton(containerId);\n });\n }\n\n deinitialize(): Promise {\n if (this._signInButton && this._signInButton.parentNode) {\n this._signInButton.removeEventListener('click', this._handleWalletButtonClick);\n this._signInButton.parentNode.removeChild(this._signInButton);\n this._signInButton = undefined;\n }\n\n return Promise.resolve();\n }\n\n private _createSignInButton(containerId: string): HTMLElement {\n const buttonContainer = document.getElementById(containerId);\n const state = this._store.getState();\n const paymentMethod = this._methodId\n ? state.paymentMethods.getPaymentMethod(this._methodId)\n : null;\n const storeConfig = state.config.getStoreConfig();\n\n if (!buttonContainer) {\n throw new Error('Need a container to place the button');\n }\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (!storeConfig) {\n throw new InvalidArgumentError('Unable to retrieve store configuration');\n }\n\n const button = document.createElement('input');\n\n button.type = 'image';\n\n if (paymentMethod.initializationData.isMasterpassSrcEnabled) {\n const subdomain = paymentMethod.config.testMode ? 'sandbox.' : '';\n const { checkoutId } = paymentMethod.initializationData;\n\n const params = [\n `locale=${formatLocale(this._locale)}`,\n `paymentmethod=master,visa,amex,discover`,\n `checkoutid=${checkoutId}`,\n ];\n\n button.src = [\n `https://${subdomain}src.mastercard.com/assets/img/btn/src_chk_btn_126x030px.svg`,\n params.join('&'),\n ].join('?');\n } else {\n button.src =\n 'https://static.masterpass.com/dyn/img/btn/global/mp_chk_btn_160x037px.svg';\n }\n\n buttonContainer.appendChild(button);\n\n button.addEventListener('click', this._handleWalletButtonClick);\n\n return button;\n }\n\n private _createMasterpassPayload(): MasterpassCheckoutOptions {\n const state = this._store.getState();\n const checkout = state.checkout.getCheckout();\n const paymentMethod = this._methodId\n ? state.paymentMethods.getPaymentMethod(this._methodId)\n : null;\n\n if (!checkout) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckout);\n }\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n return {\n checkoutId: paymentMethod.initializationData.checkoutId,\n allowedCardTypes: paymentMethod.initializationData.allowedCardTypes,\n amount: checkout.cart.cartAmount.toString(),\n currency: checkout.cart.currency.code,\n cartId: checkout.cart.id,\n callbackUrl: getCallbackUrl('cart'),\n };\n }\n\n @bind\n private _handleWalletButtonClick(): void {\n if (!this._masterpassClient) {\n throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n }\n\n this._masterpassClient.checkout(this._createMasterpassPayload());\n }\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { pick } from 'lodash';\n\nimport { CheckoutActionCreator, CheckoutStore } from '../../../checkout';\nimport {\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n StandardError,\n} from '../../../common/error/errors';\nimport { INTERNAL_USE_ONLY, SDK_VERSION_HEADERS } from '../../../common/http-request';\nimport { PaymentMethod } from '../../../payment';\nimport {\n PaypalActions,\n PaypalAuthorizeData,\n PaypalButtonStyleShapeOption,\n PaypalButtonStyleSizeOption,\n PaypalClientToken,\n PaypalScriptLoader,\n} from '../../../payment/strategies/paypal';\nimport { CheckoutButtonInitializeOptions } from '../../checkout-button-options';\nimport CheckoutButtonStrategy from '../checkout-button-strategy';\n\nexport default class PaypalButtonStrategy implements CheckoutButtonStrategy {\n private _paymentMethod?: PaymentMethod;\n\n constructor(\n private _store: CheckoutStore,\n private _checkoutActionCreator: CheckoutActionCreator,\n private _paypalScriptLoader: PaypalScriptLoader,\n private _formPoster: FormPoster,\n private _host: string = '',\n ) {}\n\n initialize(options: CheckoutButtonInitializeOptions): Promise {\n const paypalOptions = options.paypal;\n const state = this._store.getState();\n const paymentMethod = (this._paymentMethod = state.paymentMethods.getPaymentMethod(\n options.methodId,\n ));\n\n if (!paypalOptions) {\n throw new InvalidArgumentError();\n }\n\n if (!paymentMethod) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n return this._paypalScriptLoader\n .loadPaypal(paymentMethod.config.merchantId)\n .then((paypal) => {\n if (!paymentMethod || !paymentMethod.config.merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const merchantId = paymentMethod.config.merchantId;\n const env = paymentMethod.config.testMode ? 'sandbox' : 'production';\n const clientToken: PaypalClientToken = { [env]: paypalOptions.clientId };\n\n const fundingCreditOption = paypal.FUNDING.CREDIT || 'credit';\n const allowedSources = paypalOptions.allowCredit ? [fundingCreditOption] : [];\n const disallowedSources = !paypalOptions.allowCredit ? [fundingCreditOption] : [];\n\n return paypal.Button.render(\n {\n env,\n client: clientToken,\n commit: paypalOptions.shouldProcessPayment,\n funding: {\n allowed: allowedSources,\n disallowed: disallowedSources,\n },\n style: {\n shape: PaypalButtonStyleShapeOption.RECT,\n ...pick(\n paypalOptions.style,\n 'layout',\n 'color',\n 'label',\n 'shape',\n 'tagline',\n 'fundingicons',\n ),\n size:\n paymentMethod.id === 'paypalexpress' &&\n paypalOptions.style?.size === 'small'\n ? PaypalButtonStyleSizeOption.RESPONSIVE\n : paypalOptions.style?.size,\n },\n payment: (_, actions) =>\n this._setupPayment(merchantId, actions, paypalOptions.onPaymentError),\n onAuthorize: (data, actions) =>\n this._tokenizePayment(\n data,\n actions,\n paypalOptions.shouldProcessPayment,\n paypalOptions.onAuthorizeError,\n ),\n },\n options.containerId,\n );\n });\n }\n\n deinitialize(): Promise {\n this._paymentMethod = undefined;\n\n return Promise.resolve();\n }\n\n private _setupPayment(\n merchantId: string,\n actions?: PaypalActions,\n onError?: (error: StandardError) => void,\n ): Promise {\n if (!actions) {\n throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n }\n\n return this._store\n .dispatch(this._checkoutActionCreator.loadDefaultCheckout())\n .then((state) => {\n const cart = state.cart.getCart();\n const cartId = cart ? cart.id : '';\n\n return actions.request.post(\n `${this._host}/api/storefront/payment/paypalexpress`,\n { merchantId, cartId },\n {\n headers: {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n },\n );\n })\n .then((res) => res.id)\n .catch((error) => {\n if (onError) {\n onError(error);\n }\n\n throw error;\n });\n }\n\n private _tokenizePayment(\n data: PaypalAuthorizeData,\n actions?: PaypalActions,\n shouldProcessPayment?: boolean,\n _onError?: (error: StandardError) => void, // FIXME: This parameter seems to be unused\n ): Promise {\n if (!this._paymentMethod) {\n throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n }\n\n if (!actions) {\n throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n }\n\n if (!data.paymentID || !data.payerID) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n const methodId = this._paymentMethod.id;\n\n return actions.payment.get(data.paymentID).then((payload) => {\n this._formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n provider: methodId,\n action: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n paymentId: data.paymentID,\n payerId: data.payerID,\n payerInfo: JSON.stringify(payload.payer.payer_info),\n });\n });\n }\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\nimport { noop } from 'lodash';\n\nimport {\n AddressRequestBody,\n BuyNowCartCreationError,\n Cart,\n Checkout,\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n Payment,\n PaymentIntegrationService,\n PaymentMethod,\n PaymentMethodCancelledError,\n ShippingOption,\n StoreConfig,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ApplePayButtonInitializeOptions, {\n WithApplePayButtonInitializeOptions,\n} from './apple-pay-button-initialize-options';\nimport ApplePaySessionFactory, { assertApplePayWindow } from './apple-pay-session-factory';\n\nconst validationEndpoint = (bigPayEndpoint: string) =>\n `${bigPayEndpoint}/api/public/v1/payments/applepay/validate_merchant`;\n\nenum DefaultLabels {\n Subtotal = 'Subtotal',\n Shipping = 'Shipping',\n}\n\nfunction isShippingOptions(options: ShippingOption[] | undefined): options is ShippingOption[] {\n return options instanceof Array;\n}\n\nexport default class ApplePayButtonStrategy implements CheckoutButtonStrategy {\n private _paymentMethod?: PaymentMethod;\n private _applePayButton?: HTMLElement;\n private _requiresShipping?: boolean;\n private _buyNowInitializeOptions?: ApplePayButtonInitializeOptions['buyNowInitializeOptions'];\n private _onAuthorizeCallback = noop;\n private _subTotalLabel: string = DefaultLabels.Subtotal;\n private _shippingLabel: string = DefaultLabels.Shipping;\n\n constructor(\n private _requestSender: RequestSender,\n private _paymentIntegrationService: PaymentIntegrationService,\n private _sessionFactory: ApplePaySessionFactory,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithApplePayButtonInitializeOptions,\n ): Promise {\n const { methodId, containerId, applepay } = options;\n\n assertApplePayWindow(window);\n\n if (!methodId || !applepay) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const { buttonClassName, onPaymentAuthorize, buyNowInitializeOptions, requiresShipping } =\n applepay;\n\n this._requiresShipping = requiresShipping;\n\n this._buyNowInitializeOptions = buyNowInitializeOptions;\n\n this._onAuthorizeCallback = onPaymentAuthorize;\n\n if (!buyNowInitializeOptions) {\n await this._paymentIntegrationService.loadDefaultCheckout();\n }\n\n await this._paymentIntegrationService.loadPaymentMethod(methodId);\n\n const state = this._paymentIntegrationService.getState();\n\n this._paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n await this._paymentIntegrationService.verifyCheckoutSpamProtection();\n\n this._applePayButton = this._createButton(containerId, buttonClassName);\n this._applePayButton.addEventListener('click', this._handleWalletButtonClick.bind(this));\n\n return Promise.resolve();\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private _createButton(\n containerId: string,\n buttonClassName = 'apple-pay-checkout-button',\n ): HTMLElement {\n const container = document.getElementById(containerId);\n\n if (!container) {\n throw new InvalidArgumentError(\n 'Unable to create wallet button without valid container ID.',\n );\n }\n\n document.body.classList.add('apple-pay-supported');\n\n const button = document.createElement('div');\n\n button.setAttribute('class', buttonClassName);\n button.setAttribute('role', 'button');\n button.setAttribute('aria-label', 'Apple Pay button');\n container.appendChild(button);\n\n return button;\n }\n\n private async _handleWalletButtonClick(event: Event) {\n event.preventDefault();\n\n if (!this._paymentMethod || !this._paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n if (\n this._buyNowInitializeOptions &&\n typeof this._buyNowInitializeOptions.getBuyNowCartRequestBody === 'function'\n ) {\n const {\n countryCode,\n currencyCode,\n merchantCapabilities,\n supportedNetworks,\n storeName,\n } = this._paymentMethod.initializationData;\n\n const request = this._getRequestWithEmptyTotal(\n countryCode,\n currencyCode,\n supportedNetworks,\n merchantCapabilities,\n );\n\n if (this._requiresShipping) {\n request.requiredShippingContactFields?.push('postalAddress');\n }\n\n const applePaySession = this._sessionFactory.create(request);\n\n this._handleApplePayEvents(applePaySession, this._paymentMethod, storeName);\n\n applePaySession.begin();\n } else {\n const state = this._paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const config = state.getStoreConfigOrThrow();\n const checkout = state.getCheckoutOrThrow();\n const request = this._getBaseRequest(cart, checkout, config, this._paymentMethod);\n const applePaySession = this._sessionFactory.create(request);\n\n this._handleApplePayEvents(\n applePaySession,\n this._paymentMethod,\n config.storeProfile.storeName,\n );\n\n applePaySession.begin();\n }\n }\n\n private _getRequestWithEmptyTotal(\n countryCode: string,\n currencyCode: string,\n supportedNetworks: string[],\n merchantCapabilities: ApplePayJS.ApplePayMerchantCapability[],\n ): ApplePayJS.ApplePayPaymentRequest {\n return {\n countryCode,\n currencyCode,\n supportedNetworks,\n merchantCapabilities,\n total: { label: '', amount: '0', type: 'pending' },\n requiredBillingContactFields: ['postalAddress'],\n requiredShippingContactFields: ['email', 'phone'],\n };\n }\n\n private _getBaseRequest(\n cart: Cart,\n checkout: Checkout,\n config: StoreConfig,\n paymentMethod: PaymentMethod,\n ): ApplePayJS.ApplePayPaymentRequest {\n const {\n storeProfile: { storeCountryCode, storeName },\n } = config;\n const {\n currency: { code, decimalPlaces },\n } = cart;\n\n const {\n initializationData: { merchantCapabilities, supportedNetworks },\n } = paymentMethod;\n\n const requiresShipping = cart.lineItems.physicalItems.length > 0;\n const total: ApplePayJS.ApplePayLineItem = requiresShipping\n ? {\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n type: 'pending',\n }\n : {\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n type: 'final',\n };\n\n const request: ApplePayJS.ApplePayPaymentRequest = {\n requiredBillingContactFields: ['postalAddress'],\n requiredShippingContactFields: ['email', 'phone'],\n countryCode: storeCountryCode,\n currencyCode: code,\n merchantCapabilities,\n supportedNetworks,\n lineItems: [],\n total,\n };\n\n if (requiresShipping) {\n request.requiredShippingContactFields?.push('postalAddress');\n } else {\n const lineItems: ApplePayJS.ApplePayLineItem[] = [\n {\n label: this._subTotalLabel,\n amount: `${checkout.subtotal.toFixed(decimalPlaces)}`,\n },\n ];\n\n checkout.taxes.forEach((tax) =>\n lineItems.push({\n label: tax.name,\n amount: `${tax.amount.toFixed(decimalPlaces)}`,\n }),\n );\n\n request.lineItems = lineItems;\n }\n\n return request;\n }\n\n private _handleApplePayEvents(\n applePaySession: ApplePaySession,\n paymentMethod: PaymentMethod,\n storeName: string,\n ) {\n applePaySession.onvalidatemerchant = async (event) => {\n try {\n const { body: merchantSession } = await this._onValidateMerchant(\n paymentMethod,\n event,\n );\n\n applePaySession.completeMerchantValidation(merchantSession);\n } catch (error) {\n throw new Error('Merchant validation failed');\n }\n };\n\n if (this._buyNowInitializeOptions && !this._requiresShipping) {\n applePaySession.onpaymentmethodselected = async () => {\n await this._createBuyNowCart();\n this._handlePaymentMethodSelected(applePaySession);\n };\n }\n\n applePaySession.onshippingcontactselected = async (event) => {\n if (this._buyNowInitializeOptions && this._requiresShipping) {\n await this._createBuyNowCart();\n }\n\n await this._handleShippingContactSelected(applePaySession, storeName, event);\n };\n\n applePaySession.onshippingmethodselected = async (event) => {\n await this._handleShippingMethodSelected(applePaySession, storeName, event);\n };\n\n applePaySession.oncancel = async () => {\n try {\n const url = `/remote-checkout/${paymentMethod.id}/signout`;\n\n await this._requestSender.get(url);\n\n return await this._paymentIntegrationService.loadCheckout();\n } catch (error) {\n throw new PaymentMethodCancelledError();\n }\n };\n\n applePaySession.onpaymentauthorized = async (event) =>\n this._onPaymentAuthorized(event, applePaySession, paymentMethod);\n }\n\n private async _createBuyNowCart() {\n try {\n const cartRequestBody = this._buyNowInitializeOptions?.getBuyNowCartRequestBody?.();\n\n if (!cartRequestBody) {\n throw new MissingDataError(MissingDataErrorType.MissingCart);\n }\n\n const buyNowCart = await this._paymentIntegrationService.createBuyNowCart(\n cartRequestBody,\n );\n\n await this._paymentIntegrationService.loadCheckout(buyNowCart.id);\n } catch (error) {\n throw new BuyNowCartCreationError();\n }\n }\n\n private _handlePaymentMethodSelected(applePaySession: ApplePaySession) {\n const state = this._paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const config = state.getStoreConfigOrThrow();\n const checkout = state.getCheckoutOrThrow();\n\n if (!this._paymentMethod || !this._paymentMethod.initializationData) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const request = this._getBaseRequest(cart, checkout, config, this._paymentMethod);\n\n delete request.total.type;\n\n applePaySession.completePaymentMethodSelection({\n newTotal: request.total,\n newLineItems: request.lineItems,\n });\n }\n\n private async _handleShippingContactSelected(\n applePaySession: ApplePaySession,\n storeName: string,\n event: ApplePayJS.ApplePayShippingContactSelectedEvent,\n ) {\n const shippingAddress = this._transformContactToAddress(event.shippingContact);\n\n try {\n await this._paymentIntegrationService.updateShippingAddress(shippingAddress);\n } catch (error) {\n applePaySession.abort();\n\n throw new Error('Shipping address update failed');\n }\n\n let state = this._paymentIntegrationService.getState();\n const {\n currency: { decimalPlaces },\n } = state.getCartOrThrow();\n let checkout = state.getCheckoutOrThrow();\n const selectionShippingOptionId = checkout.consignments[0].selectedShippingOption?.id;\n const availableOptions = checkout.consignments[0].availableShippingOptions;\n const selectedOption = availableOptions?.find(({ id }) => id === selectionShippingOptionId);\n const unselectedOptions = availableOptions?.filter(\n (option) => option.id !== selectionShippingOptionId,\n );\n const shippingOptions: ApplePayJS.ApplePayShippingMethod[] = selectedOption\n ? [\n {\n label: selectedOption.description,\n amount: `${selectedOption.cost.toFixed(decimalPlaces)}`,\n detail: selectedOption.additionalDescription,\n identifier: selectedOption.id,\n },\n ]\n : [];\n\n if (unselectedOptions) {\n [\n ...unselectedOptions.filter((option) => option.isRecommended),\n ...unselectedOptions.filter((option) => !option.isRecommended),\n ].forEach((option) =>\n shippingOptions.push({\n label: option.description,\n amount: `${option.cost.toFixed(decimalPlaces)}`,\n detail: option.additionalDescription,\n identifier: option.id,\n }),\n );\n }\n\n if (!isShippingOptions(availableOptions)) {\n throw new Error('Shipping options not available.');\n }\n\n if (availableOptions.length === 0) {\n applePaySession.completeShippingContactSelection(\n ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,\n [],\n {\n type: 'pending',\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n },\n [],\n );\n\n return;\n }\n\n const recommendedOption = availableOptions.find((option) => option.isRecommended);\n\n const optionId = recommendedOption ? recommendedOption.id : availableOptions[0].id;\n const selectedOptionId = selectedOption ? selectedOption.id : optionId;\n\n try {\n await this._updateShippingOption(selectedOptionId);\n } catch (error) {\n throw new Error('Shipping options update failed');\n }\n\n state = this._paymentIntegrationService.getState();\n checkout = state.getCheckoutOrThrow();\n\n applePaySession.completeShippingContactSelection({\n newShippingMethods: shippingOptions,\n newTotal: {\n type: 'final',\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n },\n newLineItems: this._getUpdatedLineItems(checkout, decimalPlaces),\n });\n }\n\n private async _handleShippingMethodSelected(\n applePaySession: ApplePaySession,\n storeName: string,\n event: ApplePayJS.ApplePayShippingMethodSelectedEvent,\n ) {\n const {\n shippingMethod: { identifier: optionId },\n } = event;\n\n try {\n await this._updateShippingOption(optionId);\n } catch (error) {\n applePaySession.abort();\n\n throw new Error('Shipping option selection update failed.');\n }\n\n const state = this._paymentIntegrationService.getState();\n const {\n currency: { decimalPlaces },\n } = state.getCartOrThrow();\n const checkout = state.getCheckoutOrThrow();\n\n applePaySession.completeShippingMethodSelection({\n newTotal: {\n type: 'final',\n label: storeName,\n amount: `${checkout.grandTotal.toFixed(decimalPlaces)}`,\n },\n newLineItems: this._getUpdatedLineItems(checkout, decimalPlaces),\n });\n }\n\n private _getUpdatedLineItems(\n checkout: Checkout,\n decimalPlaces: number,\n ): ApplePayJS.ApplePayLineItem[] {\n const lineItems: ApplePayJS.ApplePayLineItem[] = [\n {\n label: this._subTotalLabel,\n amount: `${checkout.subtotal.toFixed(decimalPlaces)}`,\n },\n ];\n\n checkout.taxes.forEach((tax) =>\n lineItems.push({\n label: tax.name,\n amount: `${tax.amount.toFixed(decimalPlaces)}`,\n }),\n );\n lineItems.push({\n label: this._shippingLabel,\n amount: `${checkout.shippingCostTotal.toFixed(decimalPlaces)}`,\n });\n\n return lineItems;\n }\n\n private async _updateShippingOption(optionId: string) {\n return this._paymentIntegrationService.selectShippingOption(optionId);\n }\n\n private async _onValidateMerchant(\n paymentData: PaymentMethod,\n event: ApplePayJS.ApplePayValidateMerchantEvent,\n ) {\n const body = [\n `validationUrl=${event.validationURL}`,\n `merchantIdentifier=${paymentData.initializationData.merchantId}`,\n `displayName=${paymentData.initializationData.storeName}`,\n `domainName=${window.location.hostname}`,\n ].join('&');\n\n return this._requestSender.post(\n validationEndpoint(paymentData.initializationData.paymentsUrl),\n {\n credentials: false,\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'X-XSRF-TOKEN': null,\n },\n body,\n },\n );\n }\n\n private async _onPaymentAuthorized(\n event: ApplePayJS.ApplePayPaymentAuthorizedEvent,\n applePaySession: ApplePaySession,\n paymentMethod: PaymentMethod,\n ) {\n const { token, billingContact, shippingContact } = event.payment;\n const state = this._paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const requiresShipping = cart.lineItems.physicalItems.length > 0;\n\n const payment: Payment = {\n methodId: paymentMethod.id,\n paymentData: {\n formattedPayload: {\n apple_pay_token: {\n payment_data: token.paymentData,\n payment_method: token.paymentMethod,\n transaction_id: token.transactionIdentifier,\n },\n },\n },\n };\n\n const transformedBillingAddress = this._transformContactToAddress(billingContact);\n const transformedShippingAddress = this._transformContactToAddress(shippingContact);\n const emailAddress = shippingContact?.emailAddress;\n const phone = shippingContact?.phoneNumber || '';\n\n try {\n await this._paymentIntegrationService.updateBillingAddress({\n ...transformedBillingAddress,\n email: emailAddress,\n phone,\n });\n\n if (requiresShipping) {\n await this._paymentIntegrationService.updateShippingAddress(\n transformedShippingAddress,\n );\n }\n\n await this._paymentIntegrationService.submitOrder({\n useStoreCredit: false,\n });\n\n await this._paymentIntegrationService.submitPayment(payment);\n applePaySession.completePayment(ApplePaySession.STATUS_SUCCESS);\n\n return this._onAuthorizeCallback();\n } catch (error) {\n applePaySession.completePayment(ApplePaySession.STATUS_FAILURE);\n\n throw new Error('Payment cannot complete');\n }\n }\n\n private _transformContactToAddress(\n contact?: ApplePayJS.ApplePayPaymentContact,\n ): AddressRequestBody {\n return {\n firstName: contact?.givenName || '',\n lastName: contact?.familyName || '',\n city: contact?.locality || '',\n company: '',\n address1: (contact?.addressLines && contact.addressLines[0]) || '',\n address2: (contact?.addressLines && contact.addressLines[1]) || '',\n postalCode: contact?.postalCode || '',\n countryCode: contact?.countryCode || '',\n phone: contact?.phoneNumber || '',\n stateOrProvince: contact?.administrativeArea || '',\n stateOrProvinceCode: contact?.administrativeArea || '',\n customFields: [],\n };\n }\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport ApplePayButtonStrategy from './apple-pay-button-strategy';\nimport ApplePaySessionFactory from './apple-pay-session-factory';\n\nconst createApplePayButtonStrategy: CheckoutButtonStrategyFactory = (\n paymentIntegrationService,\n) => {\n const { getHost } = paymentIntegrationService.getState();\n\n return new ApplePayButtonStrategy(\n createRequestSender({ host: getHost() }),\n paymentIntegrationService,\n new ApplePaySessionFactory(),\n );\n};\n\nexport default toResolvableModule(createApplePayButtonStrategy, [{ id: 'applepay' }]);\n","import { stringifyUrl } from 'query-string';\n\nimport {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n NotImplementedError,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport {\n BoltButtonStyleOptions,\n BoltHostWindow,\n BoltPaymentMethod,\n StyleButtonShape,\n StyleButtonSize,\n} from './bolt';\nimport { WithBoltButtonInitializeOptions } from './bolt-button-initialize-options';\nimport BoltScriptLoader from './bolt-script-loader';\n\nexport default class BoltButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private boltScriptLoader: BoltScriptLoader,\n public boltHostWindow: BoltHostWindow = window,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithBoltButtonInitializeOptions,\n ): Promise {\n const { bolt, containerId, methodId } = options;\n const { buyNowInitializeOptions, style } = bolt || {};\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!bolt) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.bolt\" argument is not provided.`,\n );\n }\n\n const isBuyNowFlow = Boolean(buyNowInitializeOptions);\n\n if (!isBuyNowFlow) {\n throw new NotImplementedError('Only buy now flow is implemented for Bolt button');\n }\n\n if (\n !buyNowInitializeOptions?.storefrontApiToken ||\n typeof buyNowInitializeOptions.storefrontApiToken !== 'string'\n ) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.storefrontApiToken\" argument is not provided.`,\n );\n }\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod: BoltPaymentMethod = state.getPaymentMethodOrThrow(methodId);\n const { initializationData, config } = paymentMethod;\n const { publishableKey, developerConfig } = initializationData || {};\n\n await this.boltScriptLoader.loadBoltClient(\n publishableKey,\n config.testMode,\n developerConfig,\n 'BigCommerce',\n buyNowInitializeOptions.storefrontApiToken,\n );\n\n this.renderButton(containerId, paymentMethod, style);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n paymentMethod: BoltPaymentMethod,\n style?: BoltButtonStyleOptions,\n ): void {\n if (typeof this.boltHostWindow.BoltConnect?.setupProductPageCheckout !== 'function') {\n return;\n }\n\n this.addButtonContainer(containerId, paymentMethod, style);\n this.boltHostWindow.BoltConnect.setupProductPageCheckout();\n }\n\n private addButtonContainer(\n containerId: string,\n paymentMethod: BoltPaymentMethod,\n style?: BoltButtonStyleOptions,\n ): void {\n const container = document.getElementById(containerId);\n\n if (!container) {\n return;\n }\n\n const boltButtonContainer = document.createElement('div');\n const boltButtonObject = document.createElement('object');\n\n boltButtonContainer.setAttribute('id', 'product-page-checkout-wrapper');\n boltButtonContainer.setAttribute('class', 'bolt-button-wrapper');\n boltButtonContainer.setAttribute('style', 'display:none');\n boltButtonContainer.setAttribute('data-tid', 'product-page-checkout-wrapper');\n\n boltButtonObject.setAttribute('data', this.getBoltObjectData(paymentMethod, style));\n boltButtonObject.setAttribute('class', 'bolt-product-checkout-button');\n\n boltButtonContainer.append(boltButtonObject);\n container.innerHTML = '';\n container.append(boltButtonContainer);\n }\n\n private getBoltObjectData(\n paymentMethod: BoltPaymentMethod,\n style?: BoltButtonStyleOptions,\n ): string {\n const { initializationData, config } = paymentMethod;\n const { publishableKey, developerConfig } = initializationData || {};\n\n const domainUrl = this.boltScriptLoader.getDomainURL(!!config.testMode, developerConfig);\n const buttonHeight = this.getButtonHeight(style?.size);\n const buttonBorderRadius = this.getButtonBorderRadius(style?.shape, buttonHeight);\n\n return stringifyUrl({\n url: `https://${domainUrl}/v1/checkout_button`,\n query: {\n publishable_key: publishableKey,\n variant: 'ppc',\n height: buttonHeight,\n border_radius: buttonBorderRadius,\n },\n });\n }\n\n private getButtonHeight(buttonSize?: StyleButtonSize): number | undefined {\n if (!buttonSize) {\n return;\n }\n\n switch (buttonSize) {\n case StyleButtonSize.Small:\n return 25;\n\n case StyleButtonSize.Large:\n return 45;\n\n case StyleButtonSize.Medium:\n default:\n return 40;\n }\n }\n\n private getButtonBorderRadius(\n buttonShape?: StyleButtonShape,\n buttonHeight?: number,\n ): number | undefined {\n if (!buttonShape) {\n return;\n }\n\n switch (buttonShape) {\n case StyleButtonShape.Pill:\n return buttonHeight ? Math.round(buttonHeight / 2) : undefined;\n\n case StyleButtonShape.Rect:\n default:\n return 4;\n }\n }\n}\n","import { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport BoltButtonStrategy from './bolt-button-strategy';\nimport BoltScriptLoader from './bolt-script-loader';\n\nconst createBoltButtonStrategy: CheckoutButtonStrategyFactory = (\n paymentIntegrationService,\n) => {\n return new BoltButtonStrategy(\n paymentIntegrationService,\n new BoltScriptLoader(getScriptLoader()),\n );\n};\n\nexport default toResolvableModule(createBoltButtonStrategy, [{ id: 'bolt' }]);\n","import {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n PayPalBuyNowInitializeOptions,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceButtonInitializeOptions, {\n WithPayPalCommerceButtonInitializeOptions,\n} from './paypal-commerce-button-initialize-options';\n\nexport default class PayPalCommerceButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithPayPalCommerceButtonInitializeOptions,\n ): Promise {\n const { paypalcommerce, containerId, methodId } = options;\n\n const isBuyNowFlow = Boolean(paypalcommerce?.buyNowInitializeOptions);\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!paypalcommerce) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerce\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !paypalcommerce.currencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerce.currencyCode\" argument is not provided.`,\n );\n }\n\n if (\n isBuyNowFlow &&\n typeof paypalcommerce.buyNowInitializeOptions?.getBuyNowCartRequestBody !== 'function'\n ) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommerce.buyNowInitializeOptions.getBuyNowCartRequestBody\" argument is not provided or it is not a function.`,\n );\n }\n\n if (!isBuyNowFlow) {\n // Info: default checkout should not be loaded for BuyNow flow,\n // since there is no checkout session available for that.\n await this.paymentIntegrationService.loadDefaultCheckout();\n }\n\n // Info: we are using provided currency code for buy now cart,\n // because checkout session is not available before buy now cart creation,\n // hence application will throw an error on getCartOrThrow method call\n const currencyCode = isBuyNowFlow\n ? paypalcommerce.currencyCode\n : this.paymentIntegrationService.getState().getCartOrThrow().currency.code;\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId, currencyCode, false);\n\n this.renderButton(containerId, methodId, paypalcommerce);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n paypalcommerce: PayPalCommerceButtonInitializeOptions,\n ): void {\n const { buyNowInitializeOptions, style, onComplete } = paypalcommerce;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled } = paymentMethod.initializationData || {};\n\n const defaultCallbacks = {\n createOrder: () => this.paypalCommerceIntegrationService.createOrder('paypalcommerce'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const hostedCheckoutCallbacks = {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(data, actions, methodId, onComplete),\n };\n\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource: paypalSdk.FUNDING.PAYPAL,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(style),\n ...defaultCallbacks,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n };\n\n const paypalButton = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButton.isEligible()) {\n paypalButton.render(`#${containerId}`);\n } else {\n this.paypalCommerceIntegrationService.removeElement(containerId);\n }\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart = await this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(\n buyNowInitializeOptions,\n );\n\n await this.paymentIntegrationService.loadCheckout(buyNowCart.id);\n }\n }\n\n private async onHostedCheckoutApprove(\n data: ApproveCallbackPayload,\n actions: ApproveCallbackActions,\n methodId: string,\n onComplete?: () => void,\n ): Promise {\n if (!data.orderID) {\n throw new MissingDataError(MissingDataErrorType.MissingOrderId);\n }\n\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const orderDetails = await actions.order.get();\n\n try {\n const billingAddress =\n this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.paypalCommerceIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.paypalCommerceIntegrationService.submitPayment(methodId, data.orderID);\n\n if (onComplete && typeof onComplete === 'function') {\n onComplete();\n }\n\n return true; // FIXME: Do we really need to return true here?\n } catch (error) {\n throw new Error(error);\n }\n }\n\n private async onShippingAddressChange(\n data: ShippingAddressChangeCallbackPayload,\n ): Promise {\n const address = this.paypalCommerceIntegrationService.getAddress({\n city: data.shippingAddress.city,\n countryCode: data.shippingAddress.country_code,\n postalCode: data.shippingAddress.postal_code,\n stateOrProvinceCode: data.shippingAddress.state,\n });\n\n try {\n // Info: we use the same address to fill billing and shipping addresses to have valid quota on BE for order updating process\n // on this stage we don't have access to valid customer's address accept shipping data\n await this.paymentIntegrationService.updateBillingAddress(address);\n await this.paymentIntegrationService.updateShippingAddress(address);\n\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n throw new Error(error);\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n ): Promise {\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n throw new Error(error);\n }\n }\n}\n","import {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceButtonStrategy from './paypal-commerce-button-strategy';\n\nconst createPayPalCommerceButtonStrategy: CheckoutButtonStrategyFactory<\n PayPalCommerceButtonStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceButtonStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceButtonStrategy, [{ id: 'paypalcommerce' }]);\n","import {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackActions,\n ApproveCallbackPayload,\n PayPalBuyNowInitializeOptions,\n PayPalCommerceButtonsOptions,\n PayPalCommerceInitializationData,\n ShippingAddressChangeCallbackPayload,\n ShippingOptionChangeCallbackPayload,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceCreditButtonInitializeOptions, {\n WithPayPalCommerceCreditButtonInitializeOptions,\n} from './paypal-commerce-credit-button-initialize-options';\n\nexport default class PayPalCommerceCreditButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithPayPalCommerceCreditButtonInitializeOptions,\n ): Promise {\n const { paypalcommercecredit, containerId, methodId } = options;\n const {\n buyNowInitializeOptions,\n currencyCode: providedCurrencyCode,\n messagingContainerId,\n } = paypalcommercecredit || {};\n\n const isBuyNowFlow = !!buyNowInitializeOptions;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!paypalcommercecredit) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercecredit\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !providedCurrencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercecredit.currencyCode\" argument is not provided.`,\n );\n }\n\n if (\n isBuyNowFlow &&\n typeof buyNowInitializeOptions?.getBuyNowCartRequestBody !== 'function'\n ) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercecredit.buyNowInitializeOptions.getBuyNowCartRequestBody\" argument is not provided or it is not a function.`,\n );\n }\n\n if (!isBuyNowFlow) {\n // Info: default checkout should not be loaded for BuyNow flow,\n // since there is no checkout session available for that.\n await this.paymentIntegrationService.loadDefaultCheckout();\n }\n\n // Info: we are using provided currency code for buy now cart,\n // because checkout session is not available before buy now cart creation,\n // hence application will throw an error on getCartOrThrow method call\n const currencyCode = isBuyNowFlow\n ? providedCurrencyCode\n : this.paymentIntegrationService.getState().getCartOrThrow().currency.code;\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId, currencyCode, false);\n\n this.renderButton(containerId, methodId, paypalcommercecredit);\n this.renderMessages(messagingContainerId);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n paypalcommercecredit: PayPalCommerceCreditButtonInitializeOptions,\n ): void {\n const { buyNowInitializeOptions, style, onComplete } = paypalcommercecredit;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const state = this.paymentIntegrationService.getState();\n const paymentMethod =\n state.getPaymentMethodOrThrow(methodId);\n const { isHostedCheckoutEnabled } = paymentMethod.initializationData || {};\n\n const defaultCallbacks = {\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder('paypalcommercecredit'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const hostedCheckoutCallbacks = {\n onShippingAddressChange: (data: ShippingAddressChangeCallbackPayload) =>\n this.onShippingAddressChange(data),\n onShippingOptionsChange: (data: ShippingOptionChangeCallbackPayload) =>\n this.onShippingOptionsChange(data),\n onApprove: (data: ApproveCallbackPayload, actions: ApproveCallbackActions) =>\n this.onHostedCheckoutApprove(data, actions, methodId, onComplete),\n };\n\n const fundingSources = [paypalSdk.FUNDING.PAYLATER, paypalSdk.FUNDING.CREDIT];\n let hasRenderedSmartButton = false;\n\n fundingSources.forEach((fundingSource) => {\n if (!hasRenderedSmartButton) {\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(style),\n ...defaultCallbacks,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n ...(isHostedCheckoutEnabled && hostedCheckoutCallbacks),\n };\n\n const paypalButton = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButton.isEligible()) {\n paypalButton.render(`#${containerId}`);\n hasRenderedSmartButton = true;\n }\n }\n });\n\n if (!hasRenderedSmartButton) {\n this.paypalCommerceIntegrationService.removeElement(containerId);\n }\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart = await this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(\n buyNowInitializeOptions,\n );\n\n await this.paymentIntegrationService.loadCheckout(buyNowCart.id);\n }\n }\n\n private async onHostedCheckoutApprove(\n data: ApproveCallbackPayload,\n actions: ApproveCallbackActions,\n methodId: string,\n onComplete?: () => void,\n ): Promise {\n if (!data.orderID) {\n throw new MissingDataError(MissingDataErrorType.MissingOrderId);\n }\n\n const state = this.paymentIntegrationService.getState();\n const cart = state.getCartOrThrow();\n const orderDetails = await actions.order.get();\n\n try {\n const billingAddress =\n this.paypalCommerceIntegrationService.getBillingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateBillingAddress(billingAddress);\n\n if (cart.lineItems.physicalItems.length > 0) {\n const shippingAddress =\n this.paypalCommerceIntegrationService.getShippingAddressFromOrderDetails(\n orderDetails,\n );\n\n await this.paymentIntegrationService.updateShippingAddress(shippingAddress);\n await this.paypalCommerceIntegrationService.updateOrder();\n }\n\n await this.paymentIntegrationService.submitOrder({}, { params: { methodId } });\n await this.paypalCommerceIntegrationService.submitPayment(methodId, data.orderID);\n\n if (onComplete && typeof onComplete === 'function') {\n onComplete();\n }\n\n return true; // FIXME: Do we really need to return true here?\n } catch (error) {\n throw new Error(error);\n }\n }\n\n private async onShippingAddressChange(\n data: ShippingAddressChangeCallbackPayload,\n ): Promise {\n const address = this.paypalCommerceIntegrationService.getAddress({\n city: data.shippingAddress.city,\n countryCode: data.shippingAddress.country_code,\n postalCode: data.shippingAddress.postal_code,\n stateOrProvinceCode: data.shippingAddress.state,\n });\n\n try {\n // Info: we use the same address to fill billing and shipping addresses to have valid quota on BE for order updating process\n // on this stage we don't have access to valid customer's address accept shipping data\n await this.paymentIntegrationService.updateBillingAddress(address);\n await this.paymentIntegrationService.updateShippingAddress(address);\n\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow();\n\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n throw new Error(error);\n }\n }\n\n private async onShippingOptionsChange(\n data: ShippingOptionChangeCallbackPayload,\n ): Promise {\n const shippingOption = this.paypalCommerceIntegrationService.getShippingOptionOrThrow(\n data.selectedShippingOption.id,\n );\n\n try {\n await this.paymentIntegrationService.selectShippingOption(shippingOption.id);\n await this.paypalCommerceIntegrationService.updateOrder();\n } catch (error) {\n throw new Error(error);\n }\n }\n\n private renderMessages(messagingContainerId?: string): void {\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n\n if (messagingContainerId && document.getElementById(messagingContainerId)) {\n const cart = this.paymentIntegrationService.getState().getCartOrThrow();\n\n const paypalMessagesOptions = {\n amount: cart.cartAmount,\n placement: 'cart',\n style: {\n layout: 'text',\n },\n };\n\n const paypalMessages = paypalSdk.Messages(paypalMessagesOptions);\n\n paypalMessages.render(`#${messagingContainerId}`);\n }\n }\n}\n","import {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceCreditButtonStrategy from './paypal-commerce-credit-button-strategy';\n\nconst createPayPalCommerceCreditButtonStrategy: CheckoutButtonStrategyFactory<\n PayPalCommerceCreditButtonStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceCreditButtonStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceCreditButtonStrategy, [\n { id: 'paypalcommercecredit' },\n]);\n","import {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n PayPalButtonStyleOptions,\n PayPalBuyNowInitializeOptions,\n PayPalCommerceButtonsOptions,\n StyleButtonColor,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceVenmoButtonInitializeOptions, {\n WithPayPalCommerceVenmoButtonInitializeOptions,\n} from './paypal-commerce-venmo-button-initialize-options';\n\nexport default class PayPalCommerceVenmoButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithPayPalCommerceVenmoButtonInitializeOptions,\n ): Promise {\n const { paypalcommercevenmo, containerId, methodId } = options;\n const { buyNowInitializeOptions, currencyCode: providedCurrencyCode } =\n paypalcommercevenmo || {};\n\n const isBuyNowFlow = !!buyNowInitializeOptions;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!paypalcommercevenmo) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercevenmo\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !providedCurrencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercevenmo.currencyCode\" argument is not provided.`,\n );\n }\n\n if (\n isBuyNowFlow &&\n typeof buyNowInitializeOptions?.getBuyNowCartRequestBody !== 'function'\n ) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercevenmo.buyNowInitializeOptions.getBuyNowCartRequestBody\" argument is not provided or it is not a function.`,\n );\n }\n\n if (!isBuyNowFlow) {\n // Info: default checkout should not be loaded for BuyNow flow,\n // since there is no checkout session available for that.\n await this.paymentIntegrationService.loadDefaultCheckout();\n }\n\n // Info: we are using provided currency code for buy now cart,\n // because checkout session is not available before buy now cart creation,\n // hence application will throw an error on getCartOrThrow method call\n const currencyCode = isBuyNowFlow\n ? providedCurrencyCode\n : this.paymentIntegrationService.getState().getCartOrThrow().currency.code;\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId, currencyCode, false);\n\n this.renderButton(containerId, methodId, paypalcommercevenmo);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n paypalcommercevenmo: PayPalCommerceVenmoButtonInitializeOptions,\n ): void {\n const { buyNowInitializeOptions, style } = paypalcommercevenmo;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const fundingSource = paypalSdk.FUNDING.VENMO;\n\n const defaultCallbacks = {\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder('paypalcommercevenmo'),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource,\n style: this.getValidVenmoButtonStyles(style),\n ...defaultCallbacks,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n };\n\n const paypalButtonRender = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${containerId}`);\n } else {\n this.paypalCommerceIntegrationService.removeElement(containerId);\n }\n }\n\n private getValidVenmoButtonStyles(style: PayPalButtonStyleOptions | undefined) {\n const validButtonStyle = this.paypalCommerceIntegrationService.getValidButtonStyle(style);\n\n if (validButtonStyle.color === StyleButtonColor.gold) {\n return {\n ...validButtonStyle,\n color: undefined,\n };\n }\n\n return validButtonStyle;\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart = await this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(\n buyNowInitializeOptions,\n );\n\n await this.paymentIntegrationService.loadCheckout(buyNowCart.id);\n }\n }\n}\n","import {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceVenmoButtonStrategy from './paypal-commerce-venmo-button-strategy';\n\nconst createPayPalCommerceVenmoButtonStrategy: CheckoutButtonStrategyFactory<\n PayPalCommerceVenmoButtonStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceVenmoButtonStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceVenmoButtonStrategy, [\n { id: 'paypalcommercevenmo' },\n]);\n","import {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n InvalidArgumentError,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport PayPalCommerceIntegrationService from '../paypal-commerce-integration-service';\nimport {\n ApproveCallbackPayload,\n PayPalBuyNowInitializeOptions,\n PayPalCommerceButtonsOptions,\n} from '../paypal-commerce-types';\n\nimport PayPalCommerceAlternativeMethodsButtonOptions, {\n WithPayPalCommerceAlternativeMethodsButtonInitializeOptions,\n} from './paypal-commerce-alternative-methods-button-initialize-options';\n\nexport default class PayPalCommerceAlternativeMethodsButtonStrategy\n implements CheckoutButtonStrategy\n{\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalCommerceIntegrationService: PayPalCommerceIntegrationService,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions &\n WithPayPalCommerceAlternativeMethodsButtonInitializeOptions,\n ): Promise {\n const { paypalcommercealternativemethods, containerId, methodId } = options;\n const {\n apm,\n buyNowInitializeOptions,\n currencyCode: providedCurrencyCode,\n } = paypalcommercealternativemethods || {};\n\n const isBuyNowFlow = !!buyNowInitializeOptions;\n\n if (!methodId) {\n throw new InvalidArgumentError(\n 'Unable to initialize payment because \"options.methodId\" argument is not provided.',\n );\n }\n\n if (!containerId) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.containerId\" argument is not provided.`,\n );\n }\n\n if (!paypalcommercealternativemethods) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercealternativemethods\" argument is not provided.`,\n );\n }\n\n if (!apm) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercealternativemethods.apm\" argument is not provided.`,\n );\n }\n\n if (isBuyNowFlow && !providedCurrencyCode) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercealternativemethods.currencyCode\" argument is not provided.`,\n );\n }\n\n if (\n isBuyNowFlow &&\n typeof buyNowInitializeOptions?.getBuyNowCartRequestBody !== 'function'\n ) {\n throw new InvalidArgumentError(\n `Unable to initialize payment because \"options.paypalcommercealternativemethods.buyNowInitializeOptions.getBuyNowCartRequestBody\" argument is not provided or it is not a function.`,\n );\n }\n\n if (!isBuyNowFlow) {\n // Info: default checkout should not be loaded for BuyNow flow,\n // since there is no checkout session available for that.\n await this.paymentIntegrationService.loadDefaultCheckout();\n }\n\n // Info: we are using provided currency code for buy now cart,\n // because checkout session is not available before buy now cart creation,\n // hence application will throw an error on getCartOrThrow method call\n const currencyCode = isBuyNowFlow\n ? providedCurrencyCode\n : this.paymentIntegrationService.getState().getCartOrThrow().currency.code;\n\n await this.paypalCommerceIntegrationService.loadPayPalSdk(methodId, currencyCode, false);\n\n this.renderButton(containerId, methodId, paypalcommercealternativemethods);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n containerId: string,\n methodId: string,\n paypalcommercealternativemethods: PayPalCommerceAlternativeMethodsButtonOptions,\n ): void {\n const { apm, buyNowInitializeOptions, style } = paypalcommercealternativemethods;\n\n const paypalSdk = this.paypalCommerceIntegrationService.getPayPalSdkOrThrow();\n const isAvailableFundingSource = Object.values(paypalSdk.FUNDING).includes(apm);\n\n if (!isAvailableFundingSource) {\n throw new InvalidArgumentError(\n `Unable to initialize PayPal button because \"options.paypalcommercealternativemethods.apm\" argument is not valid funding source.`,\n );\n }\n\n const defaultCallbacks = {\n createOrder: () =>\n this.paypalCommerceIntegrationService.createOrder(\n 'paypalcommercealternativemethod',\n ),\n onApprove: ({ orderID }: ApproveCallbackPayload) =>\n this.paypalCommerceIntegrationService.tokenizePayment(methodId, orderID),\n };\n\n const buyNowFlowCallbacks = {\n onClick: () => this.handleClick(buyNowInitializeOptions),\n onCancel: () => this.paymentIntegrationService.loadDefaultCheckout(),\n };\n\n const buttonRenderOptions: PayPalCommerceButtonsOptions = {\n fundingSource: apm,\n style: this.paypalCommerceIntegrationService.getValidButtonStyle(style),\n ...defaultCallbacks,\n ...(buyNowInitializeOptions && buyNowFlowCallbacks),\n };\n\n const paypalButtonRender = paypalSdk.Buttons(buttonRenderOptions);\n\n if (paypalButtonRender.isEligible()) {\n paypalButtonRender.render(`#${containerId}`);\n } else {\n this.paypalCommerceIntegrationService.removeElement(containerId);\n }\n }\n\n private async handleClick(\n buyNowInitializeOptions?: PayPalBuyNowInitializeOptions,\n ): Promise {\n if (buyNowInitializeOptions) {\n const buyNowCart = await this.paypalCommerceIntegrationService.createBuyNowCartOrThrow(\n buyNowInitializeOptions,\n );\n\n await this.paymentIntegrationService.loadCheckout(buyNowCart.id);\n }\n }\n}\n","import {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport createPayPalCommerceIntegrationService from '../create-paypal-commerce-integration-service';\n\nimport PayPalCommerceAlternativeMethodsButtonStrategy from './paypal-commerce-alternative-methods-button-strategy';\n\nconst createPayPalCommerceAlternativeMethodsButtonStrategy: CheckoutButtonStrategyFactory<\n PayPalCommerceAlternativeMethodsButtonStrategy\n> = (paymentIntegrationService) =>\n new PayPalCommerceAlternativeMethodsButtonStrategy(\n paymentIntegrationService,\n createPayPalCommerceIntegrationService(paymentIntegrationService),\n );\n\nexport default toResolvableModule(createPayPalCommerceAlternativeMethodsButtonStrategy, [\n { id: 'paypalcommercealternativemethods' },\n]);\n","export interface PaypalFundingTypeList {\n CARD?: string;\n CREDIT?: string;\n PAYPAL?: string;\n PAYLATER?: string;\n}\n\nexport interface PaypalButton {\n render(options: PaypalButtonOptions, container: string): void;\n}\n\nexport interface PaypalButtonRender {\n render(container: string): void;\n isEligible(): boolean;\n}\n\nexport interface MessagingRender {\n render(container: string): void;\n}\n\nexport interface MessagingOptions {\n amount: number;\n placement: string;\n}\n\nexport interface PaypalButtonOptions {\n env?: string;\n commit?: boolean;\n style?: PaypalStyleOptions;\n funding?: PaypalFundingType;\n fundingSource?: string;\n client?: PaypalClientToken;\n payment?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onAuthorize?(data: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n createOrder?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n onApprove?(data?: PaypalAuthorizeData, actions?: PaypalActions): Promise;\n}\n\nexport interface PaypalClientToken {\n production?: string;\n sandbox?: string;\n}\n\nexport interface PaypalFundingType {\n allowed?: string[];\n disallowed?: string[];\n}\n\nexport enum PaypalButtonStyleLayoutOption {\n HORIZONTAL = 'horizontal',\n VERTICAL = 'vertical',\n}\n\nexport enum PaypalButtonStyleSizeOption {\n SMALL = 'small',\n MEDIUM = 'medium',\n LARGE = 'large',\n RESPONSIVE = 'responsive',\n}\n\nexport enum PaypalButtonStyleColorOption {\n GOLD = 'gold',\n BLUE = 'blue',\n SIlVER = 'silver',\n BLACK = 'black',\n}\n\nexport enum PaypalButtonStyleLabelOption {\n CHECKOUT = 'checkout',\n PAY = 'pay',\n BUYNOW = 'buynow',\n PAYPAL = 'paypal',\n CREDIT = 'credit',\n}\n\nexport enum PaypalButtonStyleShapeOption {\n PILL = 'pill',\n RECT = 'rect',\n}\n\nexport interface PaypalStyleOptions {\n layout?: PaypalButtonStyleLayoutOption;\n size?: PaypalButtonStyleSizeOption;\n color?: PaypalButtonStyleColorOption;\n label?: PaypalButtonStyleLabelOption;\n shape?: PaypalButtonStyleShapeOption;\n tagline?: boolean;\n fundingicons?: boolean;\n height?: number;\n}\n\nexport interface PaypalActions {\n payment: PaypalPaymentActions;\n request: PaypalRequestActions;\n}\n\nexport interface PaypalPaymentActions {\n get(id: string): Promise;\n}\n\nexport interface PaypalRequestActions {\n post(url: string, payload?: object, options?: object): Promise<{ id: string }>;\n}\n\nexport interface PaypalTransaction {\n amount?: PaypalAmount;\n payee?: PaypalPayee;\n description?: string;\n note_to_payee?: string;\n item_list?: PaypalItemList;\n}\n\nexport interface PaypalItemList {\n items?: PaypalItem[];\n shipping_address?: PaypalAddress;\n}\n\nexport interface PaypalItem {\n sku?: string;\n name?: string;\n description?: string;\n quantity: string;\n price: string;\n currency: string;\n tax?: string;\n}\n\nexport interface PaypalAmount {\n currency: string;\n total: string;\n}\n\nexport interface PaypalPayer {\n payer_info: object;\n}\n\nexport interface PaypalPayee {\n email?: string;\n merchant_id?: string;\n}\n\nexport interface PaypalAddress {\n line1: string;\n line2?: string;\n city?: string;\n country_code: string;\n postal_code?: string;\n state?: string;\n phone?: string;\n type?: string;\n}\n\nexport interface PaypalPaymentPayload {\n payment: PaypalPaymentPayload;\n payer: PaypalPayer;\n transactions?: PaypalTransaction[];\n}\n\nexport interface PaypalAuthorizeData {\n payerId: string;\n paymentId?: string;\n billingToken?: string;\n // the PayPal side of things uses uppercase ID instead of camel case Id\n payerID?: string;\n paymentID?: string;\n}\n\nexport interface PaypalExpressCheckout {\n initXO(): void;\n startFlow(url: string): void;\n closeFlow(): void;\n setup(merchantId: string, options: PaypalExpressCheckoutOptions): void;\n}\n\nexport interface PaypalExpressCheckoutOptions {\n button: string;\n environment: string;\n}\n\nexport interface PaypalHostWindow extends Window {\n paypal?: PaypalSDK;\n}\n\nexport interface PaypalSDK {\n Button: PaypalButton;\n checkout: PaypalExpressCheckout;\n FUNDING: PaypalFundingTypeList;\n Messages(options: MessagingOptions): MessagingRender;\n Buttons(options: PaypalButtonOptions): PaypalButtonRender;\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\n\nimport {\n CheckoutButtonInitializeOptions,\n CheckoutButtonStrategy,\n INTERNAL_USE_ONLY,\n InvalidArgumentError,\n MissingDataError,\n MissingDataErrorType,\n NotInitializedError,\n NotInitializedErrorType,\n PaymentIntegrationService,\n SDK_VERSION_HEADERS,\n StandardError,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { WithPaypalExpressButtonInitializeOptions } from './paypal-express-button-initialize-options';\nimport PaypalScriptLoader from './paypal-express-script-loader';\nimport {\n PaypalActions,\n PaypalAuthorizeData,\n PaypalButtonStyleShapeOption,\n PaypalButtonStyleSizeOption,\n PaypalClientToken,\n PaypalSDK,\n PaypalStyleOptions,\n} from './paypal-express-types';\n\nexport default class PaypalButtonStrategy implements CheckoutButtonStrategy {\n constructor(\n private paymentIntegrationService: PaymentIntegrationService,\n private paypalExpressScriptLoader: PaypalScriptLoader,\n private formPoster: FormPoster,\n ) {}\n\n async initialize(\n options: CheckoutButtonInitializeOptions & WithPaypalExpressButtonInitializeOptions,\n ): Promise {\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(options.methodId);\n\n if (!options.paypal) {\n throw new InvalidArgumentError();\n }\n\n if (!paymentMethod.config.merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const paypalSDK = await this.paypalExpressScriptLoader.loadPaypalSDK(\n paymentMethod.config.merchantId,\n );\n\n this.renderButton(options, paypalSDK);\n }\n\n deinitialize(): Promise {\n return Promise.resolve();\n }\n\n private renderButton(\n options: CheckoutButtonInitializeOptions & WithPaypalExpressButtonInitializeOptions,\n paypalSDK: PaypalSDK,\n ) {\n const { containerId, methodId, paypal } = options;\n const { allowCredit, clientId, onPaymentError, shouldProcessPayment, style } = paypal;\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(options.methodId);\n\n if (!paymentMethod.config.merchantId) {\n throw new MissingDataError(MissingDataErrorType.MissingPaymentMethod);\n }\n\n const merchantId = paymentMethod.config.merchantId;\n const env = paymentMethod.config.testMode ? 'sandbox' : 'production';\n const clientToken: PaypalClientToken = { [env]: clientId };\n const fundingCreditOption = paypalSDK.FUNDING.CREDIT || 'credit';\n const allowedSources = allowCredit ? [fundingCreditOption] : [];\n const disallowedSources = !allowCredit ? [fundingCreditOption] : [];\n\n return paypalSDK.Button.render(\n {\n env,\n client: clientToken,\n commit: shouldProcessPayment,\n funding: {\n allowed: allowedSources,\n disallowed: disallowedSources,\n },\n style: this.getStyle(style),\n payment: (_, actions) => this.setupPayment(merchantId, actions, onPaymentError),\n onAuthorize: (data, actions) =>\n this.tokenizePayment(data, methodId, actions, shouldProcessPayment),\n },\n containerId,\n );\n }\n\n private getStyle(style?: Omit): PaypalStyleOptions {\n const { color, fundingicons, label, layout, shape, size, tagline } = style || {};\n\n return {\n color,\n fundingicons,\n label,\n layout,\n shape: shape || PaypalButtonStyleShapeOption.RECT,\n size: size === 'small' ? PaypalButtonStyleSizeOption.RESPONSIVE : size,\n tagline,\n };\n }\n\n private async setupPayment(\n merchantId: string,\n actions?: PaypalActions,\n onError?: (error: StandardError) => void,\n ): Promise {\n if (!actions) {\n throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n }\n\n try {\n const state = await this.paymentIntegrationService.loadDefaultCheckout();\n const { id: cartId } = state.getCartOrThrow();\n const host = state.getHost() || '';\n\n const paymentRequest = await actions.request.post(\n `${host}/api/storefront/payment/paypalexpress`,\n { merchantId, cartId },\n {\n headers: {\n 'X-API-INTERNAL': INTERNAL_USE_ONLY,\n ...SDK_VERSION_HEADERS,\n },\n },\n );\n\n return paymentRequest.id;\n } catch (error) {\n if (onError) {\n onError(error);\n }\n\n throw error;\n }\n }\n\n private async tokenizePayment(\n data: PaypalAuthorizeData,\n methodId: string,\n actions?: PaypalActions,\n shouldProcessPayment?: boolean,\n ): Promise {\n if (!actions) {\n throw new NotInitializedError(NotInitializedErrorType.CheckoutButtonNotInitialized);\n }\n\n if (!data.paymentID || !data.payerID) {\n throw new MissingDataError(MissingDataErrorType.MissingPayment);\n }\n\n const state = this.paymentIntegrationService.getState();\n const paymentMethod = state.getPaymentMethodOrThrow(methodId);\n\n const getPaymentData = await actions.payment.get(data.paymentID);\n\n return this.formPoster.postForm('/checkout.php', {\n payment_type: 'paypal',\n provider: paymentMethod.id,\n action: shouldProcessPayment ? 'process_payment' : 'set_external_checkout',\n paymentId: data.paymentID,\n payerId: data.payerID,\n payerInfo: JSON.stringify(getPaymentData.payer.payer_info),\n });\n }\n}\n","import { LoadScriptOptions, ScriptLoader } from '@bigcommerce/script-loader';\n\nimport { PaymentMethodClientUnavailableError } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { PaypalHostWindow, PaypalSDK } from './paypal-express-types';\n\nexport default class PaypalScriptLoader {\n private window: PaypalHostWindow;\n\n constructor(private scriptLoader: ScriptLoader) {\n this.window = window;\n }\n\n async loadPaypalSDK(merchantId = ''): Promise {\n const scriptSrc = '//www.paypalobjects.com/api/checkout.min.js';\n const options: LoadScriptOptions = {\n async: true,\n attributes: { 'data-merchant-id': merchantId },\n ...(merchantId && {\n attributes: { 'data-merchant-id': merchantId },\n }),\n };\n\n await this.scriptLoader.loadScript(scriptSrc, options);\n\n if (!this.window.paypal) {\n throw new PaymentMethodClientUnavailableError();\n }\n\n return this.window.paypal;\n }\n}\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport {\n CheckoutButtonStrategyFactory,\n toResolvableModule,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { PaypalExpressButtonStrategy, PaypalExpressScriptLoader } from './index';\n\nconst createPaypalExpressButtonStrategy: CheckoutButtonStrategyFactory<\n PaypalExpressButtonStrategy\n> = (paymentIntegrationService) => {\n return new PaypalExpressButtonStrategy(\n paymentIntegrationService,\n new PaypalExpressScriptLoader(getScriptLoader()),\n createFormPoster(),\n );\n};\n\nexport default toResolvableModule(createPaypalExpressButtonStrategy, [{ id: 'paypalexpress' }]);\n","import { createFormPoster } from '@bigcommerce/form-poster';\nimport { createRequestSender } from '@bigcommerce/request-sender';\n\nimport { createCheckoutStore } from '../checkout';\nimport { PaymentMethodActionCreator, PaymentMethodRequestSender } from '../payment';\nimport { createPaymentIntegrationService } from '../payment-integration';\n\nimport CheckoutButtonInitializer from './checkout-button-initializer';\nimport CheckoutButtonInitializerOptions from './checkout-button-initializer-options';\nimport CheckoutButtonStrategyActionCreator from './checkout-button-strategy-action-creator';\nimport createCheckoutButtonRegistry from './create-checkout-button-registry';\nimport createCheckoutButtonRegistryV2 from './create-checkout-button-registry-v2';\n\n/**\n * Creates an instance of `CheckoutButtonInitializer`.\n *\n * @remarks\n * ```js\n * const initializer = createCheckoutButtonInitializer();\n *\n * initializer.initializeButton({\n * methodId: 'braintreepaypal',\n * braintreepaypal: {\n * container: '#checkoutButton',\n * },\n * });\n * ```\n *\n * @alpha\n * Please note that `CheckoutButtonInitializer` is currently in an early stage\n * of development. Therefore the API is unstable and not ready for public\n * consumption.\n *\n * @param options - A set of construction options.\n * @returns an instance of `CheckoutButtonInitializer`.\n */\nexport default function createCheckoutButtonInitializer(\n options?: CheckoutButtonInitializerOptions,\n): CheckoutButtonInitializer {\n const { host, locale = 'en' } = options ?? {};\n const store = createCheckoutStore();\n const requestSender = createRequestSender({ host });\n const formPoster = createFormPoster({ host });\n const paymentIntegrationService = createPaymentIntegrationService(store);\n const registryV2 = createCheckoutButtonRegistryV2(paymentIntegrationService);\n\n return new CheckoutButtonInitializer(\n store,\n new CheckoutButtonStrategyActionCreator(\n createCheckoutButtonRegistry(store, requestSender, formPoster, locale, host),\n registryV2,\n new PaymentMethodActionCreator(new PaymentMethodRequestSender(requestSender)),\n ),\n );\n}\n","import {\n CheckoutButtonStrategy,\n CheckoutButtonStrategyFactory,\n CheckoutButtonStrategyResolveId,\n isResolvableModule,\n PaymentIntegrationService,\n} from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { ResolveIdRegistry } from '../common/registry';\nimport * as defaultCheckoutButtonStrategyFactories from '../generated/checkout-button-strategies';\n\nexport interface CheckoutButtonStrategyFactories {\n [key: string]: CheckoutButtonStrategyFactory;\n}\n\nexport default function createCheckoutButtonStrategyRegistry(\n paymentIntegrationService: PaymentIntegrationService,\n checkoutButtonStrategyFactories: CheckoutButtonStrategyFactories = defaultCheckoutButtonStrategyFactories,\n): ResolveIdRegistry {\n const registry = new ResolveIdRegistry<\n CheckoutButtonStrategy,\n CheckoutButtonStrategyResolveId\n >();\n\n for (const [, createCheckoutButtonStrategy] of Object.entries(\n checkoutButtonStrategyFactories,\n )) {\n if (\n !isResolvableModule<\n CheckoutButtonStrategyFactory,\n CheckoutButtonStrategyResolveId\n >(createCheckoutButtonStrategy)\n ) {\n continue;\n }\n\n for (const resolverId of createCheckoutButtonStrategy.resolveIds) {\n registry.register(resolverId, () =>\n createCheckoutButtonStrategy(paymentIntegrationService),\n );\n }\n }\n\n return registry;\n}\n","import { FormPoster } from '@bigcommerce/form-poster';\nimport { RequestSender } from '@bigcommerce/request-sender';\nimport { getScriptLoader } from '@bigcommerce/script-loader';\n\nimport { CartRequestSender } from '../cart';\nimport { CheckoutActionCreator, CheckoutRequestSender, CheckoutStore } from '../checkout';\nimport { Registry } from '../common/registry';\nimport { ConfigActionCreator, ConfigRequestSender } from '../config';\nimport { FormFieldsActionCreator, FormFieldsRequestSender } from '../form';\nimport { PaymentMethodActionCreator, PaymentMethodRequestSender } from '../payment';\nimport { createAmazonPayV2PaymentProcessor } from '../payment/strategies/amazon-pay-v2';\nimport { BraintreeScriptLoader, BraintreeSDKCreator } from '../payment/strategies/braintree';\nimport {\n createGooglePayPaymentProcessor,\n GooglePayAdyenV2Initializer,\n GooglePayAdyenV3Initializer,\n GooglePayAuthorizeNetInitializer,\n GooglePayBNZInitializer,\n GooglePayBraintreeInitializer,\n GooglePayCheckoutcomInitializer,\n GooglePayCybersourceV2Initializer,\n GooglePayOrbitalInitializer,\n GooglePayStripeInitializer,\n GooglePayStripeUPEInitializer,\n GooglePayWorldpayAccessInitializer,\n} from '../payment/strategies/googlepay';\nimport { MasterpassScriptLoader } from '../payment/strategies/masterpass';\nimport { PaypalScriptLoader } from '../payment/strategies/paypal';\n\nimport { CheckoutButtonMethodType, CheckoutButtonStrategy } from './strategies';\nimport { AmazonPayV2ButtonStrategy } from './strategies/amazon-pay-v2';\nimport AmazonPayV2RequestSender from './strategies/amazon-pay-v2/amazon-pay-v2-request-sender';\nimport {\n BraintreePaypalButtonStrategy,\n BraintreePaypalCreditButtonStrategy,\n BraintreeVenmoButtonStrategy,\n} from './strategies/braintree';\nimport { GooglePayButtonStrategy } from './strategies/googlepay';\nimport { MasterpassButtonStrategy } from './strategies/masterpass';\nimport { PaypalButtonStrategy } from './strategies/paypal';\n\nexport default function createCheckoutButtonRegistry(\n store: CheckoutStore,\n requestSender: RequestSender,\n formPoster: FormPoster,\n locale: string,\n host?: string,\n): Registry {\n const registry = new Registry();\n const scriptLoader = getScriptLoader();\n const checkoutRequestSender = new CheckoutRequestSender(requestSender);\n const checkoutActionCreator = new CheckoutActionCreator(\n checkoutRequestSender,\n new ConfigActionCreator(new ConfigRequestSender(requestSender)),\n new FormFieldsActionCreator(new FormFieldsRequestSender(requestSender)),\n );\n const paymentMethodActionCreator = new PaymentMethodActionCreator(\n new PaymentMethodRequestSender(requestSender),\n );\n\n const braintreeSdkCreator = new BraintreeSDKCreator(new BraintreeScriptLoader(scriptLoader));\n const cartRequestSender = new CartRequestSender(requestSender);\n const amazonPayV2RequestSender = new AmazonPayV2RequestSender(requestSender);\n\n registry.register(\n CheckoutButtonMethodType.AMAZON_PAY_V2,\n () =>\n new AmazonPayV2ButtonStrategy(\n store,\n checkoutActionCreator,\n createAmazonPayV2PaymentProcessor(),\n cartRequestSender,\n amazonPayV2RequestSender,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.BRAINTREE_PAYPAL,\n () =>\n new BraintreePaypalButtonStrategy(\n store,\n checkoutActionCreator,\n cartRequestSender,\n braintreeSdkCreator,\n formPoster,\n window,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.BRAINTREE_PAYPAL_CREDIT,\n () =>\n new BraintreePaypalCreditButtonStrategy(\n store,\n checkoutActionCreator,\n cartRequestSender,\n braintreeSdkCreator,\n formPoster,\n window,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.BRAINTREE_VENMO,\n () =>\n new BraintreeVenmoButtonStrategy(\n store,\n paymentMethodActionCreator,\n cartRequestSender,\n braintreeSdkCreator,\n formPoster,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.GOOGLEPAY_ADYENV2,\n () =>\n new GooglePayButtonStrategy(\n store,\n formPoster,\n checkoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayAdyenV2Initializer()),\n cartRequestSender,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.GOOGLEPAY_ADYENV3,\n () =>\n new GooglePayButtonStrategy(\n store,\n formPoster,\n checkoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayAdyenV3Initializer()),\n cartRequestSender,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.GOOGLEPAY_AUTHORIZENET,\n () =>\n new GooglePayButtonStrategy(\n store,\n formPoster,\n checkoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayAuthorizeNetInitializer()),\n cartRequestSender,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.GOOGLEPAY_BNZ,\n () =>\n new GooglePayButtonStrategy(\n store,\n formPoster,\n checkoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayBNZInitializer()),\n cartRequestSender,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.GOOGLEPAY_BRAINTREE,\n () =>\n new GooglePayButtonStrategy(\n store,\n formPoster,\n checkoutActionCreator,\n createGooglePayPaymentProcessor(\n store,\n new GooglePayBraintreeInitializer(braintreeSdkCreator),\n ),\n cartRequestSender,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.GOOGLEPAY_CHECKOUTCOM,\n () =>\n new GooglePayButtonStrategy(\n store,\n formPoster,\n checkoutActionCreator,\n createGooglePayPaymentProcessor(\n store,\n new GooglePayCheckoutcomInitializer(requestSender),\n ),\n cartRequestSender,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.GOOGLEPAY_CYBERSOURCEV2,\n () =>\n new GooglePayButtonStrategy(\n store,\n formPoster,\n checkoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayCybersourceV2Initializer()),\n cartRequestSender,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.GOOGLEPAY_ORBITAL,\n () =>\n new GooglePayButtonStrategy(\n store,\n formPoster,\n checkoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayOrbitalInitializer()),\n cartRequestSender,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.GOOGLEPAY_STRIPE,\n () =>\n new GooglePayButtonStrategy(\n store,\n formPoster,\n checkoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayStripeInitializer()),\n cartRequestSender,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.GOOGLEPAY_STRIPEUPE,\n () =>\n new GooglePayButtonStrategy(\n store,\n formPoster,\n checkoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayStripeUPEInitializer()),\n cartRequestSender,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.MASTERPASS,\n () =>\n new MasterpassButtonStrategy(\n store,\n checkoutActionCreator,\n new MasterpassScriptLoader(scriptLoader),\n locale,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.PAYPALEXPRESS,\n () =>\n new PaypalButtonStrategy(\n store,\n checkoutActionCreator,\n new PaypalScriptLoader(scriptLoader),\n formPoster,\n host,\n ),\n );\n\n registry.register(\n CheckoutButtonMethodType.GOOGLEPAY_WORLDPAYACCESS,\n () =>\n new GooglePayButtonStrategy(\n store,\n formPoster,\n checkoutActionCreator,\n createGooglePayPaymentProcessor(store, new GooglePayWorldpayAccessInitializer()),\n cartRequestSender,\n ),\n );\n\n return registry;\n}\n","import EmbeddedCheckoutError from './embedded-checkout-error';\nimport { EmbeddedContentOptions } from './iframe-content';\n\nexport enum EmbeddedCheckoutEventType {\n CheckoutComplete = 'CHECKOUT_COMPLETE',\n CheckoutError = 'CHECKOUT_ERROR',\n CheckoutLoaded = 'CHECKOUT_LOADED',\n FrameError = 'FRAME_ERROR',\n FrameLoaded = 'FRAME_LOADED',\n SignedOut = 'SIGNED_OUT',\n}\n\nexport interface EmbeddedCheckoutEventMap {\n [EmbeddedCheckoutEventType.CheckoutComplete]: EmbeddedCheckoutCompleteEvent;\n [EmbeddedCheckoutEventType.CheckoutError]: EmbeddedCheckoutErrorEvent;\n [EmbeddedCheckoutEventType.CheckoutLoaded]: EmbeddedCheckoutLoadedEvent;\n [EmbeddedCheckoutEventType.FrameError]: EmbeddedCheckoutFrameErrorEvent;\n [EmbeddedCheckoutEventType.FrameLoaded]: EmbeddedCheckoutFrameLoadedEvent;\n [EmbeddedCheckoutEventType.SignedOut]: EmbeddedCheckoutSignedOutEvent;\n}\n\nexport type EmbeddedCheckoutEvent =\n | EmbeddedCheckoutCompleteEvent\n | EmbeddedCheckoutErrorEvent\n | EmbeddedCheckoutFrameErrorEvent\n | EmbeddedCheckoutFrameLoadedEvent\n | EmbeddedCheckoutLoadedEvent\n | EmbeddedCheckoutSignedOutEvent;\n\nexport interface EmbeddedCheckoutCompleteEvent {\n type: EmbeddedCheckoutEventType.CheckoutComplete;\n}\n\nexport interface EmbeddedCheckoutErrorEvent {\n type: EmbeddedCheckoutEventType.CheckoutError;\n payload: EmbeddedCheckoutError;\n}\n\nexport interface EmbeddedCheckoutLoadedEvent {\n type: EmbeddedCheckoutEventType.CheckoutLoaded;\n}\n\nexport interface EmbeddedCheckoutFrameErrorEvent {\n type: EmbeddedCheckoutEventType.FrameError;\n payload: EmbeddedCheckoutError;\n}\n\nexport interface EmbeddedCheckoutFrameLoadedEvent {\n type: EmbeddedCheckoutEventType.FrameLoaded;\n payload?: EmbeddedContentOptions;\n}\n\nexport interface EmbeddedCheckoutSignedOutEvent {\n type: EmbeddedCheckoutEventType.SignedOut;\n}\n","import { Response } from '@bigcommerce/request-sender';\n\nimport { InternalErrorResponseBody } from '@bigcommerce/checkout-sdk/payment-integration-api';\n\nimport { RequestError } from '../../common/error/errors';\n\n/**\n * Throw this error we are not able to sign in a shopper because the provided\n * login token is invalid.\n */\nexport default class InvalidLoginTokenError extends RequestError {\n constructor(response: Response) {\n super(response, { message: response.body.title });\n\n this.name = 'InvalidLoginTokenError';\n this.type = 'invalid_login_token';\n }\n}\n","import { StandardError } from '../../common/error/errors';\n\nexport enum NotEmbeddableErrorType {\n MissingContainer = 'missing_container',\n MissingContent = 'missing_content',\n UnknownError = 'unknown_error',\n}\n\n/**\n * Throw this error if we are not able to embed the checkout form as an iframe.\n * This can be due to the fact that the provided container ID is invalid, or the\n * checkout form fails to load inside the iframe. It can also be due to an\n * unknown reason.\n */\nexport default class NotEmbeddableError extends StandardError {\n constructor(\n message?: string,\n public subtype: NotEmbeddableErrorType = NotEmbeddableErrorType.UnknownError,\n ) {\n super(message || 'Unable to embed the checkout form.');\n\n this.name = 'NotEmbeddableError';\n this.type = 'not_embeddable';\n }\n}\n","import EmbeddedCheckoutStyles from '../embedded-checkout-styles';\n\nexport enum EmbeddedContentEventType {\n StyleConfigured = 'STYLE_CONFIGURED',\n}\n\nexport interface EmbeddedContentEventMap {\n [EmbeddedContentEventType.StyleConfigured]: EmbeddedContentStyleConfiguredEvent;\n}\n\nexport type EmbeddedContentEvent = EmbeddedContentStyleConfiguredEvent;\n\nexport interface EmbeddedContentStyleConfiguredEvent {\n type: EmbeddedContentEventType.StyleConfigured;\n payload: EmbeddedCheckoutStyles;\n}\n","import { RequestSender } from '@bigcommerce/request-sender';\n\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport { IFrameComponent, IframeEventListener, IframeEventPoster } from '../common/iframe';\nimport { BrowserStorage } from '../common/storage';\nimport { parseUrl } from '../common/url';\nimport { bindDecorator as bind } from '../common/utility';\n\nimport EmbeddedCheckoutError from './embedded-checkout-error';\nimport { EmbeddedCheckoutEventMap, EmbeddedCheckoutEventType } from './embedded-checkout-events';\nimport EmbeddedCheckoutOptions from './embedded-checkout-options';\nimport { InvalidLoginTokenError, NotEmbeddableError, NotEmbeddableErrorType } from './errors';\nimport { EmbeddedContentEvent, EmbeddedContentEventType } from './iframe-content';\nimport ResizableIframeCreator from './resizable-iframe-creator';\n\nexport const ALLOW_COOKIE_ATTEMPT_INTERVAL = 10 * 60 * 1000;\nexport const IS_COOKIE_ALLOWED_KEY = 'isCookieAllowed';\nexport const LAST_ALLOW_COOKIE_ATTEMPT_KEY = 'lastAllowCookieAttempt';\n\n@bind\nexport default class EmbeddedCheckout {\n private _iframe?: IFrameComponent;\n private _isAttached: boolean;\n\n /**\n * @internal\n */\n constructor(\n private _iframeCreator: ResizableIframeCreator,\n private _messageListener: IframeEventListener,\n private _messagePoster: IframeEventPoster,\n private _loadingIndicator: LoadingIndicator,\n private _requestSender: RequestSender,\n private _storage: BrowserStorage,\n private _location: Location,\n private _options: EmbeddedCheckoutOptions,\n ) {\n this._isAttached = false;\n\n if (this._options.onComplete) {\n this._messageListener.addListener(\n EmbeddedCheckoutEventType.CheckoutComplete,\n this._options.onComplete,\n );\n }\n\n if (this._options.onError) {\n this._messageListener.addListener(\n EmbeddedCheckoutEventType.CheckoutError,\n this._options.onError,\n );\n }\n\n if (this._options.onLoad) {\n this._messageListener.addListener(\n EmbeddedCheckoutEventType.CheckoutLoaded,\n this._options.onLoad,\n );\n }\n\n if (this._options.onFrameLoad) {\n this._messageListener.addListener(\n EmbeddedCheckoutEventType.FrameLoaded,\n this._options.onFrameLoad,\n );\n }\n\n if (this._options.onSignOut) {\n this._messageListener.addListener(\n EmbeddedCheckoutEventType.SignedOut,\n this._options.onSignOut,\n );\n }\n\n this._messageListener.addListener(EmbeddedCheckoutEventType.FrameLoaded, () =>\n this._configureStyles(),\n );\n }\n\n attach(): Promise {\n if (this._isAttached) {\n return Promise.resolve(this);\n }\n\n this._isAttached = true;\n this._messageListener.listen();\n this._loadingIndicator.show(this._options.containerId);\n\n return this._allowCookie()\n .then(() => this._attemptLogin())\n .then((url) => this._iframeCreator.createFrame(url, this._options.containerId))\n .then((iframe) => {\n this._iframe = iframe;\n\n this._configureStyles();\n this._loadingIndicator.hide();\n })\n .catch((error) => {\n this._isAttached = false;\n\n return this._retryAllowCookie(error).catch(() => {\n this._messageListener.trigger({\n type: EmbeddedCheckoutEventType.FrameError,\n payload: error,\n });\n\n this._loadingIndicator.hide();\n\n throw error;\n });\n })\n .then(() => this);\n }\n\n detach(): void {\n if (!this._isAttached) {\n return;\n }\n\n this._isAttached = false;\n this._messageListener.stopListen();\n\n if (this._iframe && this._iframe.parentNode) {\n this._iframe.parentNode.removeChild(this._iframe);\n this._iframe.iFrameResizer.close();\n }\n }\n\n private _configureStyles(): void {\n if (!this._iframe || !this._iframe.contentWindow || !this._options.styles) {\n return;\n }\n\n this._messagePoster.setTarget(this._iframe.contentWindow);\n\n this._messagePoster.post({\n type: EmbeddedContentEventType.StyleConfigured,\n payload: this._options.styles,\n });\n }\n\n private _attemptLogin(): Promise {\n if (!/^\\/login\\/token/.test(parseUrl(this._options.url).pathname)) {\n return Promise.resolve(this._options.url);\n }\n\n return this._requestSender\n .post<{ redirectUrl: string }>(this._options.url)\n .then(({ body: { redirectUrl } }) => redirectUrl)\n .catch((response) => Promise.reject(new InvalidLoginTokenError(response)));\n }\n\n /**\n * This workaround is required for certain browsers (namely Safari) that\n * prevent session cookies to be set for a third party website unless the\n * user has recently visited such website. Therefore, before we attempt to\n * login or set an active cart in the session, we need to first redirect the\n * user to the domain of Embedded Checkout.\n */\n private _allowCookie(): Promise {\n if (this._storage.getItem(IS_COOKIE_ALLOWED_KEY)) {\n return Promise.resolve();\n }\n\n this._storage.setItem(IS_COOKIE_ALLOWED_KEY, true);\n\n // It could be possible that the flag is set to true but the browser has\n // already removed the permission to store third-party cookies. In that\n // case, we should try to redirect the user again. But we only want to\n // do it once within a fixed interval. This is to avoid getting into a\n // redirect loop if the shopper actually doesn't have a valid card\n // session.\n this._storage.setItem(LAST_ALLOW_COOKIE_ATTEMPT_KEY, Date.now());\n\n const { origin } = parseUrl(this._options.url);\n const redirectUrl = `${origin}/embedded-checkout/allow-cookie?returnUrl=${encodeURIComponent(\n this._location.href,\n )}`;\n\n document.body.style.visibility = 'hidden';\n this._location.replace(redirectUrl);\n\n return new Promise(() => {});\n }\n\n private _retryAllowCookie(error: EmbeddedCheckoutError): Promise {\n const lastAttempt = Number(this._storage.getItem(LAST_ALLOW_COOKIE_ATTEMPT_KEY));\n const canRetry =\n (!lastAttempt || Date.now() - lastAttempt > ALLOW_COOKIE_ATTEMPT_INTERVAL) &&\n error instanceof NotEmbeddableError &&\n error.subtype === NotEmbeddableErrorType.MissingContent;\n\n if (!canRetry) {\n return Promise.reject();\n }\n\n this._storage.removeItem(LAST_ALLOW_COOKIE_ATTEMPT_KEY);\n this._storage.removeItem(IS_COOKIE_ALLOWED_KEY);\n\n return this._allowCookie();\n }\n}\n","import { IFrameComponent, iframeResizer, isIframeEvent } from '../common/iframe';\nimport { parseUrl } from '../common/url';\n\nimport { EmbeddedCheckoutEventType } from './embedded-checkout-events';\nimport { NotEmbeddableError, NotEmbeddableErrorType } from './errors';\n\nexport default class ResizableIframeCreator {\n constructor(private _options?: { timeout: number }) {}\n\n createFrame(src: string, containerId: string): Promise {\n const container = document.getElementById(containerId);\n const { timeout = 60000 } = this._options || {};\n\n if (!container) {\n throw new NotEmbeddableError(\n 'Unable to embed the iframe because the container element could not be found.',\n NotEmbeddableErrorType.MissingContainer,\n );\n }\n\n const iframe = document.createElement('iframe');\n\n iframe.src = src;\n iframe.style.border = 'none';\n iframe.style.display = 'none';\n iframe.style.width = '100%';\n iframe.allowPaymentRequest = true;\n\n container.appendChild(iframe);\n\n return this._toResizableFrame(iframe, timeout).catch((error) => {\n container.removeChild(iframe);\n\n throw error;\n });\n }\n\n private _toResizableFrame(\n iframe: HTMLIFrameElement,\n timeoutInterval: number,\n ): Promise {\n // Can't simply listen to `load` event because it always gets triggered even if there's an error.\n // Instead, listen to the `load` inside the iframe and let the parent frame know when it happens.\n return new Promise((resolve, reject) => {\n const timeout = window.setTimeout(() => {\n reject(\n new NotEmbeddableError(\n 'Unable to embed the iframe because the content could not be loaded.',\n ),\n );\n }, timeoutInterval);\n\n const handleMessage = (event: MessageEvent) => {\n if (event.origin !== parseUrl(iframe.src).origin) {\n return;\n }\n\n if (isIframeEvent(event.data, EmbeddedCheckoutEventType.FrameError)) {\n teardown();\n reject(\n new NotEmbeddableError(\n event.data.payload.message,\n NotEmbeddableErrorType.MissingContent,\n ),\n );\n }\n\n if (isIframeEvent(event.data, EmbeddedCheckoutEventType.FrameLoaded)) {\n iframe.style.display = '';\n\n const contentId = event.data.payload && event.data.payload.contentId;\n const iframes = iframeResizer(\n {\n scrolling: false,\n sizeWidth: false,\n heightCalculationMethod: contentId ? 'taggedElement' : 'lowestElement',\n },\n iframe,\n );\n\n teardown();\n resolve(iframes[iframes.length - 1]);\n }\n };\n\n const teardown = () => {\n window.removeEventListener('message', handleMessage);\n window.clearTimeout(timeout);\n };\n\n window.addEventListener('message', handleMessage);\n });\n }\n}\n","import { IFrameComponent, IFrameOptions } from 'iframe-resizer';\n\nexport {\n HeightCalculationMethod,\n IFrameComponent,\n IFrameMessageData,\n IFrameObject,\n IFrameOptions,\n IFramePage,\n IFramePageOptions,\n IFrameResizedData,\n IFrameScrollData,\n PageInfo,\n WidthCalculationMethod,\n} from 'iframe-resizer';\n\n// The reason why we are wrapping the original `iframeResizer` function imported\n// from the package is because the package sets up event listeners (window\n// resize etc...) as soon as the package is imported. Therefore, to defer the\n// side effect from happening until the function is actually being used, we are\n// importing the package inside this function. To minimise the chance of\n// importing the original package inadvertently, we are also re-exporting all of\n// its public interfaces. The re-exports do not cause any side effect because\n// they are plain TypeScript interfaces; meaning they are only used for type\n// checks rather than for code output.\nexport function iframeResizer(\n options: IFrameOptions,\n target: string | HTMLElement,\n): IFrameComponent[] {\n /* eslint-disable @typescript-eslint/no-var-requires */\n const { iframeResizer: originalIframeResizer } = require('iframe-resizer');\n\n return originalIframeResizer(options, target);\n}\n\n// We also need to wrap the original `iframeResizer.contentWindow` because\n// similarly the package sets up event listeners as soon as the package gets\n// imported. Another reason is that if it is imported at the top level using a\n// regular import statement, it will be stripped out by Webpack as it is\n// considered as \"unused\", unless we explicitly mark it as a package that\n// produces side effects.\nexport function setupContentWindowForIframeResizer(): void {\n require('iframe-resizer/js/iframeResizer.contentWindow');\n}\n","import { createRequestSender } from '@bigcommerce/request-sender';\n\nimport { LoadingIndicator } from '@bigcommerce/checkout-sdk/ui';\n\nimport { IframeEventListener, IframeEventPoster } from '../common/iframe';\nimport { BrowserStorage } from '../common/storage';\nimport { parseUrl } from '../common/url';\n\nimport EmbeddedCheckout from './embedded-checkout';\nimport { EmbeddedCheckoutEventMap } from './embedded-checkout-events';\nimport EmbeddedCheckoutOptions from './embedded-checkout-options';\nimport { EmbeddedContentEvent } from './iframe-content';\nimport ResizableIframeCreator from './resizable-iframe-creator';\n\nconst STORAGE_PREFIX = 'BigCommerce.EmbeddedCheckout';\n\n/**\n * Embed the checkout form in an iframe.\n *\n * @remarks\n * Once the iframe is embedded, it will automatically resize according to the\n * size of the checkout form. It will also notify the parent window when certain\n * events have occurred. i.e.: when the form is loaded and ready to be used.\n *\n * ```js\n * embedCheckout({\n * url: 'https://checkout/url',\n * containerId: 'container-id',\n * });\n * ```\n *\n * @param options - Options for embedding the checkout form.\n * @returns A promise that resolves to an instance of `EmbeddedCheckout`.\n */\nexport default function embedCheckout(options: EmbeddedCheckoutOptions): Promise {\n const origin = parseUrl(options.url).origin;\n const embeddedCheckout = new EmbeddedCheckout(\n new ResizableIframeCreator(),\n new IframeEventListener(origin),\n new IframeEventPoster(origin),\n new LoadingIndicator({ styles: options.styles && options.styles.loadingIndicator }),\n createRequestSender(),\n new BrowserStorage(STORAGE_PREFIX),\n window.location,\n options,\n );\n\n return embeddedCheckout.attach();\n}\n","import { EmbeddedCheckoutFrameLoadedEvent } from '../embedded-checkout-events';\n\nexport default function handleFrameLoadedEvent(message: EmbeddedCheckoutFrameLoadedEvent): void {\n if (!message.payload || !message.payload.contentId) {\n return;\n }\n\n const body = document.getElementById(message.payload.contentId);\n\n if (!body || body.hasAttribute('data-iframe-height')) {\n return;\n }\n\n body.setAttribute('data-iframe-height', '');\n}\n","export default interface CustomError extends Error {\n message: string;\n type: string;\n subtype?: string;\n}\n\nexport function isCustomError(error: unknown): error is CustomError {\n return typeof error === 'object' && error !== null && 'message' in error && 'type' in error;\n}\n","import { CustomError, isCustomError } from '../../common/error/errors';\nimport { IframeEventListener, IframeEventPoster } from '../../common/iframe';\nimport { bindDecorator as bind } from '../../common/utility';\nimport EmbeddedCheckoutError from '../embedded-checkout-error';\nimport {\n EmbeddedCheckoutCompleteEvent,\n EmbeddedCheckoutErrorEvent,\n EmbeddedCheckoutEvent,\n EmbeddedCheckoutEventMap,\n EmbeddedCheckoutEventType,\n EmbeddedCheckoutFrameErrorEvent,\n EmbeddedCheckoutFrameLoadedEvent,\n EmbeddedCheckoutLoadedEvent,\n EmbeddedCheckoutSignedOutEvent,\n} from '../embedded-checkout-events';\nimport EmbeddedCheckoutStyles from '../embedded-checkout-styles';\n\nimport EmbeddedCheckoutMessenger from './embedded-checkout-messenger';\nimport { EmbeddedContentEventMap, EmbeddedContentEventType } from './embedded-content-events';\nimport EmbeddedContentOptions from './embedded-content-options';\n\n@bind\nexport default class IframeEmbeddedCheckoutMessenger implements EmbeddedCheckoutMessenger {\n /**\n * @internal\n */\n constructor(\n private _messageListener: IframeEventListener,\n private _messagePoster: IframeEventPoster,\n private _untargetedMessagePoster: IframeEventPoster,\n private _messageHandlers: EventCallbacks = {},\n ) {\n this._messageListener.listen();\n }\n\n postComplete(): void {\n const message: EmbeddedCheckoutCompleteEvent = {\n type: EmbeddedCheckoutEventType.CheckoutComplete,\n };\n\n this._postMessage(message);\n }\n\n postError(payload: Error | CustomError): void {\n const message: EmbeddedCheckoutErrorEvent = {\n type: EmbeddedCheckoutEventType.CheckoutError,\n payload: this._transformError(payload),\n };\n\n this._postMessage(message);\n }\n\n postFrameError(payload: Error | CustomError): void {\n const message: EmbeddedCheckoutFrameErrorEvent = {\n type: EmbeddedCheckoutEventType.FrameError,\n payload: this._transformError(payload),\n };\n\n // Ideally, all messages should be targeted at a specific origin.\n // However, for `FrameError` message, we have to post it in an\n // untargeted fashion. This is because the error could be caused by a\n // missing cart. That makes it not possible to determine of site origin\n // of the parent window. Nevertheless, we still want to notify the\n // parent window about the error.\n this._postMessage(message, { untargeted: true });\n }\n\n postFrameLoaded(payload?: EmbeddedContentOptions): void {\n const message: EmbeddedCheckoutFrameLoadedEvent = {\n type: EmbeddedCheckoutEventType.FrameLoaded,\n payload,\n };\n\n this._postMessage(message);\n }\n\n postLoaded(): void {\n const message: EmbeddedCheckoutLoadedEvent = {\n type: EmbeddedCheckoutEventType.CheckoutLoaded,\n };\n\n this._postMessage(message);\n }\n\n postSignedOut(): void {\n const message: EmbeddedCheckoutSignedOutEvent = {\n type: EmbeddedCheckoutEventType.SignedOut,\n };\n\n this._postMessage(message);\n }\n\n receiveStyles(handler: (styles: EmbeddedCheckoutStyles) => void): void {\n this._messageListener.addListener(\n EmbeddedContentEventType.StyleConfigured,\n ({ payload }) => {\n handler(payload);\n },\n );\n }\n\n private _postMessage(message: EmbeddedCheckoutEvent, options?: { untargeted?: boolean }): void {\n this._notifyMessageHandlers(message);\n\n if (options && options.untargeted) {\n return this._untargetedMessagePoster.post(message);\n }\n\n this._messagePoster.post(message);\n }\n\n private _notifyMessageHandlers(message: EmbeddedCheckoutEvent): void {\n Object.keys(this._messageHandlers).forEach((key) => {\n if (message.type !== key) {\n return;\n }\n\n const handler = this._messageHandlers[key];\n\n if (handler) {\n (handler as (event: EmbeddedCheckoutEvent) => void).call(null, message);\n }\n });\n }\n\n private _transformError(error: Error | CustomError): EmbeddedCheckoutError {\n return {\n message: error.message,\n type: isCustomError(error) ? error.type : undefined,\n subtype: isCustomError(error) ? error.subtype : undefined,\n };\n }\n}\n\nexport type EventCallbacks = {\n [key in keyof TEventMap]?: (event: TEventMap[key]) => void;\n};\n","import { bindDecorator as bind } from '../../common/utility';\n\nimport EmbeddedCheckoutMessenger from './embedded-checkout-messenger';\n\n@bind\nexport default class NoopEmbeddedCheckoutMessenger implements EmbeddedCheckoutMessenger {\n postComplete(): void {}\n\n postError(): void {}\n\n postFrameError(): void {}\n\n postFrameLoaded(): void {}\n\n postLoaded(): void {}\n\n postSignedOut(): void {}\n\n receiveStyles(): void {}\n}\n","import {\n IframeEventListener,\n IframeEventPoster,\n setupContentWindowForIframeResizer,\n} from '../../common/iframe';\nimport { EmbeddedCheckoutEvent, EmbeddedCheckoutEventType } from '../embedded-checkout-events';\n\nimport EmbeddedCheckoutMessenger from './embedded-checkout-messenger';\nimport EmbeddedCheckoutMessengerOptions from './embedded-checkout-messenger-options';\nimport { EmbeddedContentEventMap } from './embedded-content-events';\nimport handleFrameLoadedEvent from './handle-frame-loaded-event';\nimport IframeEmbeddedCheckoutMessenger from './iframe-embedded-checkout-messenger';\nimport NoopEmbeddedCheckoutMessenger from './noop-embedded-checkout-messenger';\n\n/**\n * Create an instance of `EmbeddedCheckoutMessenger`.\n *\n * @remarks\n * The object is responsible for posting messages to the parent window from the\n * iframe when certain events have occurred. For example, when the checkout\n * form is first loaded, you should notify the parent window about it.\n *\n * The iframe can only be embedded in domains that are allowed by the store.\n *\n * ```ts\n * const messenger = createEmbeddedCheckoutMessenger({\n * parentOrigin: 'https://some/website',\n * });\n *\n * messenger.postFrameLoaded();\n * ```\n *\n * @alpha\n * Please note that this feature is currently in an early stage of development.\n * Therefore the API is unstable and not ready for public consumption.\n *\n * @param options - Options for creating `EmbeddedCheckoutMessenger`\n * @returns - An instance of `EmbeddedCheckoutMessenger`\n */\nexport default function createEmbeddedCheckoutMessenger(\n options: EmbeddedCheckoutMessengerOptions,\n): EmbeddedCheckoutMessenger {\n setupContentWindowForIframeResizer();\n\n const parentWindow = options.parentWindow || window.parent;\n\n // Return a No-op messenger if it is not called inside an iframe\n if (window === parentWindow) {\n return new NoopEmbeddedCheckoutMessenger();\n }\n\n return new IframeEmbeddedCheckoutMessenger(\n new IframeEventListener(options.parentOrigin),\n new IframeEventPoster(options.parentOrigin, parentWindow),\n new IframeEventPoster('*', parentWindow),\n { [EmbeddedCheckoutEventType.FrameLoaded]: handleFrameLoadedEvent },\n );\n}\n","const __WEBPACK_NAMESPACE_OBJECT__ = require(\"messageformat\");","import { isObject, union } from 'lodash';\nimport MessageFormat from 'messageformat';\n\nimport { Logger } from '../common/log';\nimport { bindDecorator as bind } from '../common/utility';\n\nimport LanguageConfig, { Locales, Translations } from './language-config';\n\nconst DEFAULT_LOCALE = 'en';\nconst KEY_PREFIX = 'optimized_checkout';\n\n/**\n * Responsible for getting language strings.\n *\n * This object can be used to retrieve language strings that are most\n * appropriate for a given locale.\n *\n * The language strings provided to the object should follow [ICU\n * MessageFormat](http://userguide.icu-project.org/formatparse/messages) syntax.\n */\n@bind\nexport default class LanguageService {\n private _locale: string;\n private _locales: Locales;\n private _translations: Translations;\n private _formatters: { [key: string]: any };\n\n /**\n * @internal\n */\n constructor(config: Partial, private _logger: Logger) {\n const { locale, locales, translations } = this._transformConfig(config);\n\n this._locale = locale;\n this._locales = locales;\n this._translations = translations;\n this._formatters = {};\n }\n\n /**\n * Remaps a set of language strings with a different set of keys.\n *\n * ```js\n * service.mapKeys({\n * 'new_key': 'existing_key',\n * });\n *\n * console.log(service.translate('new_key'));\n * ```\n *\n * @param maps - The set of language strings.\n */\n mapKeys(maps: { [key: string]: string }): void {\n Object.keys(maps).forEach((key) => {\n const translationKey = `${KEY_PREFIX}.${maps[key]}`;\n\n this._translations[`${KEY_PREFIX}.${key}`] = this._translations[translationKey];\n });\n }\n\n /**\n * Gets the preferred locale of the current customer.\n *\n * @returns The preferred locale code.\n */\n getLocale(): string {\n return this._hasTranslations() ? this._locale : DEFAULT_LOCALE;\n }\n\n /**\n * Gets a language string by a key.\n *\n * ```js\n * service.translate('language_key');\n * ```\n *\n * If the language string contains a placeholder, you can replace it by\n * providing a second argument.\n *\n * ```js\n * service.translate('language_key', { placeholder: 'Hello' });\n * ```\n *\n * @param key - The language key.\n * @param data - Data for replacing placeholders in the language string.\n * @returns The translated language string.\n */\n translate(key: string, data: TranslationData = {}): string {\n const prefixedKey = `${KEY_PREFIX}.${key}`;\n\n if (typeof this._translations[prefixedKey] !== 'string') {\n this._logger.warn(`Translation key \"${prefixedKey}\" is missing`);\n\n return prefixedKey;\n }\n\n if (!this._formatters[prefixedKey]) {\n const messageFormat = new MessageFormat(this._locales[prefixedKey]);\n\n this._formatters[prefixedKey] = messageFormat.compile(\n this._translations[prefixedKey] || '',\n );\n }\n\n return this._formatters[prefixedKey](this._transformData(data));\n }\n\n private _transformConfig(config: Partial = {}): LanguageConfig {\n const output: LanguageConfig = {\n defaultLocale: '',\n defaultTranslations: {},\n translations: {},\n locales: {},\n locale: config.locale || DEFAULT_LOCALE,\n };\n\n const locales = config.locales || {};\n const translations = this._flattenObject(config.translations || {});\n const defaultTranslations = this._flattenObject(config.defaultTranslations || {});\n const fallbackTranslations = this._flattenObject(config.fallbackTranslations || {});\n const translationKeys = union(\n Object.keys(fallbackTranslations),\n Object.keys(defaultTranslations),\n Object.keys(translations),\n );\n\n translationKeys.forEach((key) => {\n if (translations && translations[key]) {\n output.translations[key] = translations[key];\n output.locales[key] = locales[key] || output.locale;\n } else if (defaultTranslations[key]) {\n output.translations[key] = defaultTranslations[key];\n output.locales[key] = config.defaultLocale ?? DEFAULT_LOCALE;\n } else {\n output.translations[key] = fallbackTranslations[key];\n output.locales[key] = config.fallbackLocale ?? DEFAULT_LOCALE;\n }\n });\n\n return output;\n }\n\n private _flattenObject(\n object: Translations,\n result: Translations = {},\n parentKey = '',\n ): Translations {\n try {\n Object.keys(object).forEach((key) => {\n const value = object[key];\n const resultKey = parentKey ? `${parentKey}.${key}` : key;\n\n if (isObject(value)) {\n return this._flattenObject(value, result, resultKey);\n }\n\n result[resultKey] = value;\n });\n } catch (err) {\n this._logger.warn(`Unable to parse object: ${err}`);\n }\n\n return result;\n }\n\n private _transformData(data: TranslationData): TranslationData {\n return Object.keys(data).reduce((result, key) => {\n const value = data[key];\n\n result[key] = value === null || value === undefined ? '' : value;\n\n return result;\n }, {} as TranslationData);\n }\n\n private _hasTranslations(): boolean {\n return (\n Object.keys(this._locales)\n .map((key) => this._locales[key])\n .filter((code) => code.split('-')[0] === this._locale.split('-')[0]).length > 0\n );\n }\n}\n\nexport interface TranslationData {\n [key: string]: string | number;\n}\n","import { getDefaultLogger } from '../common/log';\n\nimport LanguageConfig from './language-config';\nimport LanguageService from './language-service';\n\n/**\n * Creates an instance of `LanguageService`.\n *\n * @remarks\n * ```js\n * const language = {{{langJson 'optimized_checkout'}}}; // `langJson` is a Handlebars helper provided by BigCommerce's Stencil template engine.\n * const service = createLanguageService(language);\n *\n * console.log(service.translate('address.city_label'));\n * ```\n *\n * @param config - A configuration object.\n * @returns An instance of `LanguageService`.\n */\nexport default function createLanguageService(\n config: Partial = {},\n): LanguageService {\n return new LanguageService(config, getDefaultLogger());\n}\n","import { InvalidArgumentError } from '../common/error/errors';\n\nimport { CurrencyConfig } from './currency';\n\nexport default class CurrencyFormatter {\n private _decimalPlaces: number;\n private _symbolLocation: string;\n private _symbol: string;\n private _thousandsSeparator: string;\n private _decimalSeparator: string;\n\n constructor(currencySettings: CurrencyConfig) {\n if (!currencySettings) {\n throw new Error('Currency settings missing');\n }\n\n const { decimalPlaces, symbolLocation, symbol, thousandsSeparator, decimalSeparator } =\n currencySettings;\n\n if (\n typeof symbolLocation !== 'string' ||\n typeof symbol !== 'string' ||\n typeof thousandsSeparator !== 'string' ||\n typeof decimalSeparator !== 'string' ||\n typeof decimalPlaces !== 'string'\n ) {\n throw new InvalidArgumentError('Invalid currency settings provided');\n }\n\n this._decimalPlaces = parseInt(decimalPlaces, 10);\n this._symbolLocation = symbolLocation;\n this._symbol = symbol;\n this._thousandsSeparator = thousandsSeparator;\n this._decimalSeparator = decimalSeparator;\n }\n\n format(amount?: number): string {\n if (typeof amount !== 'number') {\n throw new InvalidArgumentError('Invalid amount provided');\n }\n\n const formattedNumber = this._formatNumber(amount);\n\n const formattedCurrency = this._formatCurrency(formattedNumber);\n\n return amount < 0 ? `-${formattedCurrency}` : formattedCurrency;\n }\n\n private _formatNumber(amount: number): string {\n const positiveAmount = Math.abs(amount);\n const [integerAmount, decimalAmount = ''] = this._toFixed(\n positiveAmount,\n this._decimalPlaces,\n ).split('.');\n const parsedIntegerAmount = integerAmount.replace(\n /\\B(?=(\\d{3})+(?!\\d))/g,\n this._thousandsSeparator,\n );\n\n if (this._decimalPlaces < 1) {\n return parsedIntegerAmount;\n }\n\n return [parsedIntegerAmount, decimalAmount].join(this._decimalSeparator);\n }\n\n private _formatCurrency(formattedNumber: string): string {\n return this._symbolLocation.toLowerCase() === 'left'\n ? `${this._symbol}${formattedNumber}`\n : `${formattedNumber}${this._symbol}`;\n }\n\n private _toFixed(value: number, precision: number): string {\n return (+`${Math.round(+`${value}e${precision}`)}e${-precision}`).toFixed(precision);\n }\n}\n","import { bindDecorator as bind } from '../common/utility';\nimport { StoreConfig } from '../config';\n\nimport CurrencyFormatter from './currency-formatter';\n\n/**\n * Responsible for formatting and converting currencies.\n */\n@bind\nexport default class CurrencyService {\n private _customerFormatter: CurrencyFormatter;\n private _storeFormatter: CurrencyFormatter;\n\n /**\n * @internal\n */\n constructor(private _storeConfig: StoreConfig) {\n this._customerFormatter = new CurrencyFormatter(this._storeConfig.shopperCurrency);\n this._storeFormatter = new CurrencyFormatter(this._storeConfig.currency);\n }\n\n toCustomerCurrency(amount: number): string {\n const exchangeRate = this._storeConfig.shopperCurrency.exchangeRate;\n\n return this._customerFormatter.format(amount * exchangeRate);\n }\n\n toStoreCurrency(amount: number): string {\n return this._storeFormatter.format(amount);\n }\n}\n","import { StoreConfig } from '../config';\n\nimport CurrencyService from './currency-service';\n\n/**\n * Creates an instance of `CurrencyService`.\n *\n * @remarks\n * ```js\n * const { data } = checkoutService.getState();\n * const config = data.getConfig();\n * const checkout = data.getCheckout();\n * const currencyService = createCurrencyService(config);\n *\n * currencyService.toStoreCurrency(checkout.grandTotal);\n * currencyService.toCustomerCurrency(checkout.grandTotal);\n * ```\n *\n * @param config - The config object containing the currency configuration\n * @returns an instance of `CurrencyService`.\n */\nexport default function createCurrencyService(config: StoreConfig): CurrencyService {\n return new CurrencyService(config);\n}\n","import {\n AnalyticsTrackerWindow,\n isAnalyticsTrackerWindow,\n} from '@bigcommerce/checkout-sdk/analytics';\n\ninterface AnalyticsTrackerWindowGA extends AnalyticsTrackerWindow {\n ga(command: string, eventName: string, payload: AnalyticPayload): void;\n}\n\nfunction isAnalyticsTrackerWindowGA(\n window: Window | AnalyticsTrackerWindowGA,\n): window is AnalyticsTrackerWindowGA {\n return window && 'ga' in window && typeof window.ga === 'function';\n}\n\nexport function isGoogleAnalyticsAvailable(): boolean {\n return isAnalyticsTrackerWindow(window) && isAnalyticsTrackerWindowGA(window);\n}\n\nexport function sendGoogleAnalytics(type: string, payload: AnalyticPayload): void {\n if (isAnalyticsTrackerWindowGA(window)) {\n window.ga('send', type, {\n ...payload,\n nonInteraction: false,\n });\n }\n}\n\n/**\n * Max size of the payload for the Google Analytics module\n * if the limit will be succeeded, the GA throwing a silent error,\n * and only in debug mode you can see it\n */\nexport function isPayloadSizeLimitReached(obj: AnalyticPayload): boolean {\n const ANALYTICS_MAX_URI_LENGTH = 8096;\n\n return serializeAnalyticsEventPayload(obj).length >= ANALYTICS_MAX_URI_LENGTH;\n}\n\nfunction serializeAnalyticsEventPayload(obj: AnalyticPayload): string {\n return Object.keys(obj)\n .reduce((acc: string[], key) => {\n const type = typeof obj[key];\n\n if (type === 'string' || type === 'number') {\n return [...acc, `${key}=${obj[key]}`];\n }\n\n if (type === 'object' && obj[key] !== null) {\n return [...acc, serializeAnalyticsEventPayload(obj[key] as AnalyticPayload)];\n }\n\n return acc;\n }, [])\n .join('&');\n}\n\ninterface AnalyticPayload {\n [key: string]: unknown;\n}\n","import { keys } from 'lodash';\n\nimport {\n AnalyticsExtraItemsManager,\n AnalyticsTracker,\n ExtraItemsData,\n} from '@bigcommerce/checkout-sdk/analytics';\n\nimport { LineItemMap } from '../cart';\nimport { Checkout, CheckoutService } from '../checkout';\nimport { InvalidArgumentError } from '../common/error/errors';\nimport { ShopperCurrency, StoreProfile } from '../config';\nimport { Coupon } from '../coupon';\nimport { Order } from '../order';\nimport { ShippingOption } from '../shipping';\n\nimport {\n isGoogleAnalyticsAvailable,\n isPayloadSizeLimitReached,\n sendGoogleAnalytics,\n} from './analytics-tracker-ga';\nimport StepTracker from './step-tracker';\n\nexport interface StepTrackerConfig {\n checkoutSteps?: AnalyticStepType[];\n}\n\nexport type AnalyticStepType = 'customer' | 'shipping' | 'billing' | 'payment';\n\nexport enum AnalyticStepId {\n CUSTOMER = 1,\n SHIPPING,\n BILLING,\n PAYMENT,\n}\n\nconst ANALYTIC_STEPS: { [key: string]: AnalyticStepId } = {\n customer: AnalyticStepId.CUSTOMER,\n shipping: AnalyticStepId.SHIPPING,\n billing: AnalyticStepId.BILLING,\n payment: AnalyticStepId.PAYMENT,\n};\n\nexport default class AnalyticsStepTracker implements StepTracker {\n private _checkoutStarted = false;\n private _completedSteps: { [key: string]: boolean } = {};\n private _viewedSteps: { [key in AnalyticStepId]?: boolean } = {};\n private _analyticStepOrder: AnalyticStepType[] = ['customer', 'shipping', 'billing', 'payment'];\n\n constructor(\n private checkoutService: CheckoutService,\n private analyticsExtraItemsManager: AnalyticsExtraItemsManager,\n private analytics: AnalyticsTracker,\n { checkoutSteps }: StepTrackerConfig = {},\n ) {\n if (checkoutSteps !== undefined) {\n if (checkoutSteps.some((value) => !(value in ANALYTIC_STEPS))) {\n throw new InvalidArgumentError(\n `Invalid checkout steps provided. Valid values are: ${keys(ANALYTIC_STEPS).join(\n ', ',\n )}.`,\n );\n }\n\n this._analyticStepOrder = checkoutSteps;\n }\n }\n\n trackCheckoutStarted(): void {\n if (this._checkoutStarted) {\n return;\n }\n\n const checkout = this.getCheckout();\n\n if (!checkout) {\n return;\n }\n\n const {\n coupons,\n grandTotal,\n shippingCostTotal,\n taxTotal,\n cart: { lineItems, discountAmount, id },\n } = checkout;\n\n const extraItemsData = this.analyticsExtraItemsManager.saveExtraItemsData(id, lineItems);\n\n this.analytics.track(\n 'Checkout Started',\n this.getTrackingPayload({\n revenue: grandTotal,\n shipping: shippingCostTotal,\n tax: taxTotal,\n discount: discountAmount,\n coupons,\n lineItems,\n extraItemsData,\n }),\n );\n\n this._checkoutStarted = true;\n }\n\n trackOrderComplete(): void {\n const order = this.getOrder();\n\n if (!order) {\n return;\n }\n\n const {\n isComplete,\n orderId,\n orderAmount,\n shippingCostTotal,\n taxTotal,\n discountAmount,\n coupons,\n lineItems,\n cartId,\n } = order;\n\n if (!isComplete) {\n return;\n }\n\n const extraItemsData = this.analyticsExtraItemsManager.readExtraItemsData(cartId);\n\n if (extraItemsData === null) {\n return;\n }\n\n const isMissingOrdersExperimentEnabled = this.checkoutService.getState().data.getConfig()\n ?.checkoutSettings.features['DATA-6891.missing_orders_within_GA'];\n\n const payload = this.getTrackingPayload({\n orderId,\n revenue: orderAmount,\n shipping: shippingCostTotal,\n tax: taxTotal,\n discount: discountAmount,\n coupons,\n extraItemsData,\n lineItems,\n });\n\n if (\n isMissingOrdersExperimentEnabled &&\n isGoogleAnalyticsAvailable() &&\n isPayloadSizeLimitReached(payload)\n ) {\n sendGoogleAnalytics('transaction', {\n '&ti': payload.orderId,\n '&ta': payload.affiliation,\n '&tr': payload.revenue,\n '&ts': payload.shipping,\n '&tt': payload.tax,\n '&tcc': payload.coupon,\n '&cu': payload.currency,\n });\n payload.products.forEach((product) => {\n sendGoogleAnalytics('item', {\n '&ti': payload.orderId,\n '&in': product.name,\n '&ic': product.sku,\n '&iv': `${product.category}`,\n '&ip': product.price,\n '&iq': product.quantity,\n });\n });\n\n // TODO: decide how to send large orders to Segment without sending to GA again\n return this.analyticsExtraItemsManager.clearExtraItemData(cartId);\n }\n\n this.analytics.track('Order Completed', payload);\n\n this.analyticsExtraItemsManager.clearExtraItemData(cartId);\n }\n\n trackStepViewed(step: AnalyticStepType): void {\n const stepId = this.getIdFromStep(step);\n\n if (!stepId || this.hasStepViewed(stepId)) {\n return;\n }\n\n this.trackViewed(stepId);\n this.backfill(stepId);\n }\n\n trackStepCompleted(step: AnalyticStepType): void {\n const stepId = this.getIdFromStep(step);\n\n if (!stepId || this.hasStepCompleted(stepId)) {\n return;\n }\n\n this.backfill(stepId);\n this.trackCompleted(stepId);\n }\n\n private backfill(stepId: AnalyticStepId): void {\n for (const i of this._analyticStepOrder) {\n const id = this.getIdFromStep(i);\n\n if (!id) {\n break;\n }\n\n if (!this.hasStepViewed(id)) {\n this.trackViewed(id);\n }\n\n if (id === stepId) {\n break;\n }\n\n if (!this.hasStepCompleted(id)) {\n this.trackCompleted(id);\n }\n }\n }\n\n private trackCompleted(stepId: AnalyticStepId): void {\n const shippingMethod = this.getSelectedShippingOption();\n const { code: currency = '' } = this.getShopperCurrency() || {};\n const paymentMethod = this.getPaymentMethodName();\n\n const payload: {\n step: number;\n currency: string;\n shippingMethod?: string;\n paymentMethod?: string;\n } = {\n step: stepId,\n currency,\n };\n\n if (shippingMethod) {\n payload.shippingMethod = shippingMethod.description;\n }\n\n if (paymentMethod) {\n payload.paymentMethod = paymentMethod;\n }\n\n // due to an issue with the way the segment library works, we must send at least one of the two\n // options--otherwise it rejects the track call with no diagnostic messages. however, if we blindly\n // include both options, it sends a single comma for the value, which is undesireable. by only adding\n // one of the two (shippingMethod here being arbitrarily chosen), we always have at least one value, but\n // never send two empty values.\n if (!payload.shippingMethod && !payload.paymentMethod) {\n payload.shippingMethod = ' ';\n }\n\n this.analytics.track('Checkout Step Completed', payload);\n\n const shippingMethodId = shippingMethod ? shippingMethod.id : '';\n const completedStepId =\n stepId === AnalyticStepId.SHIPPING ? `${stepId}-${shippingMethodId}` : stepId;\n\n this._completedSteps[completedStepId] = true;\n }\n\n private getTrackingPayload({\n orderId,\n revenue,\n shipping,\n tax,\n discount,\n coupons,\n extraItemsData,\n lineItems,\n }: {\n orderId?: number;\n revenue: number;\n shipping: number;\n tax: number;\n discount: number;\n coupons: Coupon[];\n extraItemsData: ExtraItemsData;\n lineItems: LineItemMap;\n }) {\n const { code = '' } = this.getShopperCurrency() || {};\n const { storeName = '' } = this.getStoreProfile() || {};\n\n return {\n orderId,\n affiliation: storeName,\n revenue: this.toShopperCurrency(revenue),\n shipping: this.toShopperCurrency(shipping),\n tax: this.toShopperCurrency(tax),\n discount: this.toShopperCurrency(discount),\n coupon: (coupons || []).map((coupon) => coupon.code.toUpperCase()).join(','),\n currency: code,\n products: this.getProducts(extraItemsData, lineItems),\n };\n }\n\n private hasStepCompleted(stepId: AnalyticStepId): boolean {\n const shippingOption = this.getSelectedShippingOption();\n const shippingMethodId = shippingOption ? shippingOption.id : '';\n\n return (\n Object.prototype.hasOwnProperty.call(this._completedSteps, stepId) ||\n (stepId === AnalyticStepId.SHIPPING &&\n Object.prototype.hasOwnProperty.call(\n this._completedSteps,\n `${stepId}-${shippingMethodId}`,\n ))\n );\n }\n\n private hasStepViewed(stepId: AnalyticStepId): boolean {\n return !!this._viewedSteps[stepId];\n }\n\n private getIdFromStep(step: string): AnalyticStepId | null {\n const name = step.split('.');\n\n return ANALYTIC_STEPS[name[0]] || null;\n }\n\n private trackViewed(stepId: AnalyticStepId): void {\n const currency = this.getShopperCurrency();\n\n this.analytics.track('Checkout Step Viewed', {\n step: stepId,\n currency: currency ? currency.code : '',\n });\n\n this._viewedSteps[stepId] = true;\n }\n\n private getOrder(): Order | undefined {\n const {\n data: { getOrder },\n } = this.checkoutService.getState();\n\n return getOrder();\n }\n\n private getCheckout(): Checkout | undefined {\n const {\n data: { getCheckout },\n } = this.checkoutService.getState();\n\n return getCheckout();\n }\n\n private getShopperCurrency(): ShopperCurrency | undefined {\n const {\n data: { getConfig },\n } = this.checkoutService.getState();\n const config = getConfig();\n\n return config && config.shopperCurrency;\n }\n\n private getStoreProfile(): StoreProfile | undefined {\n const {\n data: { getConfig },\n } = this.checkoutService.getState();\n const config = getConfig();\n\n return config && config.storeProfile;\n }\n\n private toShopperCurrency(amount: number): number {\n const { exchangeRate = 1 } = this.getShopperCurrency() || {};\n\n return Math.round(amount * exchangeRate * 100) / 100;\n }\n\n private getSelectedShippingOption(): ShippingOption | null {\n const { data } = this.checkoutService.getState();\n const shippingOption = data.getSelectedShippingOption();\n\n return shippingOption && shippingOption.id && shippingOption.description\n ? shippingOption\n : null;\n }\n\n private getPaymentMethodName(): string {\n const { data } = this.checkoutService.getState();\n const paymentMethod = data.getSelectedPaymentMethod();\n\n return paymentMethod && paymentMethod.config ? paymentMethod.config.displayName || '' : '';\n }\n\n private getProducts(itemsData: ExtraItemsData, lineItems: LineItemMap): AnalyticsProduct[] {\n const customItems: AnalyticsProduct[] = (lineItems.customItems || []).map((item) => ({\n product_id: item.id,\n sku: item.sku,\n price: item.listPrice,\n quantity: item.quantity,\n name: item.name,\n }));\n\n const giftCertificateItems: AnalyticsProduct[] = lineItems.giftCertificates.map((item) => {\n return {\n product_id: item.id,\n price: this.toShopperCurrency(item.amount),\n name: item.name,\n quantity: 1,\n };\n });\n\n const physicalAndDigitalItems: AnalyticsProduct[] = [\n ...lineItems.physicalItems,\n ...lineItems.digitalItems,\n ].map((item) => {\n let itemAttributes;\n\n if (item.options && item.options.length) {\n itemAttributes = item.options.map((option) => `${option.name}:${option.value}`);\n itemAttributes.sort();\n }\n\n return {\n product_id: item.productId,\n sku: item.sku,\n price: item.salePrice,\n image_url: item.imageUrl,\n name: item.name,\n quantity: item.quantity,\n brand: itemsData[item.productId] ? itemsData[item.productId].brand : '',\n category: itemsData[item.productId] ? itemsData[item.productId].category : '',\n variant: (itemAttributes || []).join(', '),\n };\n });\n\n return [...customItems, ...physicalAndDigitalItems, ...giftCertificateItems];\n }\n}\n\nexport interface AnalyticsProduct {\n product_id: string | number;\n price: number;\n quantity: number;\n name: string;\n sku?: string;\n image_url?: string;\n category?: string;\n variant?: string;\n brand?: string;\n}\n","import StepTracker from './step-tracker';\n\nexport default class NoopStepTracker implements StepTracker {\n trackCheckoutStarted(): void {}\n\n trackOrderComplete(): void {}\n\n trackStepViewed(): void {}\n\n trackStepCompleted(): void {}\n}\n","import localStorageFallback from 'local-storage-fallback';\n\nimport {\n AnalyticsExtraItemsManager,\n isAnalyticsTrackerWindow,\n} from '@bigcommerce/checkout-sdk/analytics';\n\nimport { CheckoutService } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\n\nimport AnalyticsStepTracker, { StepTrackerConfig } from './analytics-step-tracker';\nimport NoopStepTracker from './noop-step-tracker';\nimport StepTracker from './step-tracker';\n\n/**\n * Creates an instance of `StepTracker`.\n *\n * @remarks\n * ```js\n * const checkoutService = createCheckoutService();\n * await checkoutService.loadCheckout();\n * const stepTracker = createStepTracker(checkoutService);\n *\n * stepTracker.trackCheckoutStarted();\n * ```\n *\n * @param CheckoutService - An instance of CheckoutService\n * @param StepTrackerConfig - A step tracker config object\n * @returns an instance of `StepTracker`.\n */\nexport default function createStepTracker(\n checkoutService: CheckoutService,\n stepTrackerConfig?: StepTrackerConfig,\n): StepTracker {\n const { data } = checkoutService.getState();\n const config = data.getConfig();\n\n if (!config) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n\n const { isAnalyticsEnabled } = config.checkoutSettings;\n\n if (isAnalyticsEnabled && isAnalyticsTrackerWindow(window)) {\n return new AnalyticsStepTracker(\n checkoutService,\n new AnalyticsExtraItemsManager(localStorageFallback),\n window.analytics,\n stepTrackerConfig,\n );\n }\n\n return new NoopStepTracker();\n}\n","export enum AnalyticStepType {\n CUSTOMER = 'customer',\n SHIPPING = 'shipping',\n BILLING = 'billing',\n PAYMENT = 'payment',\n}\n\nexport const AnalyticStepOrder: AnalyticStepType[] = [\n AnalyticStepType.CUSTOMER,\n AnalyticStepType.SHIPPING,\n AnalyticStepType.BILLING,\n AnalyticStepType.PAYMENT,\n];\n","import { LineItem, LineItemMap } from '../cart';\nimport { CheckoutSelectors, CheckoutStoreSelector } from '../checkout';\nimport { MissingDataError, MissingDataErrorType } from '../common/error/errors';\nimport { flatten } from 'lodash';\n\nimport { AnalyticStepOrder, AnalyticStepType } from './analytics-steps';\nimport BodlService from './bodl-service';\nimport {\n BodlEventsCheckout,\n BodlEventsPayload,\n BODLProduct,\n CommonCheckoutData,\n} from './bodl-window';\n\nexport default class BodlEmitterService implements BodlService {\n private _checkoutStarted = false;\n private _emailEntryBegan = false;\n private _shippingOptionsShown = false;\n private _completedSteps: { [key: string]: boolean } = {};\n private state?: CheckoutStoreSelector;\n\n constructor(\n private subscribe: (subscriber: (state: CheckoutSelectors) => void) => void,\n private bodlEvents: BodlEventsCheckout,\n ) {\n this.subscribe((state) => {\n this.setState(state.data);\n\n const config = this.state?.getConfig();\n\n if (!config) {\n throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig);\n }\n });\n }\n\n setState(state: CheckoutStoreSelector) {\n this.state = state;\n }\n\n checkoutBegin(): void {\n const data = this._getCommonCheckoutData();\n\n if (this._checkoutStarted || !data) {\n return;\n }\n\n this.bodlEvents.emitCheckoutBeginEvent(data);\n\n this._checkoutStarted = true;\n }\n\n orderPurchased(): void {\n const order = this.state?.getOrder();\n\n if (!order) {\n return;\n }\n\n const {\n currency,\n isComplete,\n orderId,\n orderAmount,\n shippingCostTotal,\n lineItems,\n cartId,\n coupons,\n channelId,\n taxTotal,\n } = order;\n\n if (!isComplete) {\n return;\n }\n\n this.bodlEvents.emitOrderPurchasedEvent({\n event_id: cartId,\n currency: currency.code,\n order_id: orderId,\n tax: taxTotal,\n channel_id: channelId,\n cart_value: orderAmount,\n coupon_codes: coupons.map((coupon) => coupon.code.toUpperCase()),\n shipping_cost: shippingCostTotal,\n line_items: this._getProducts(lineItems, currency.code),\n });\n }\n\n stepCompleted(currentStep?: AnalyticStepType): void {\n if (!currentStep) {\n return;\n }\n\n AnalyticStepOrder.some((step: AnalyticStepType) => {\n if (!this._hasStepCompleted(step)) {\n this._trackCompletedStep(step);\n }\n\n return step === currentStep;\n });\n }\n\n customerEmailEntry(email?: string) {\n if (this._emailEntryBegan || !email?.length) {\n return;\n }\n\n this._emailEntryBegan = true;\n this.bodlEvents.emit('bodl_checkout_email_entry_began');\n }\n\n customerSuggestionInit(payload?: BodlEventsPayload) {\n this.bodlEvents.emit('bodl_checkout_customer_suggestion_initialization', payload);\n }\n\n customerSuggestionExecute() {\n this.bodlEvents.emit('bodl_checkout_customer_suggestion_execute');\n }\n\n customerPaymentMethodExecuted(payload?: BodlEventsPayload) {\n this.bodlEvents.emit('bodl_checkout_customer_payment_method_executed', payload);\n }\n\n showShippingMethods() {\n if (this._shippingOptionsShown) {\n return;\n }\n\n this._shippingOptionsShown = true;\n this.bodlEvents.emit('bodl_checkout_show_shipping_options');\n }\n\n selectedPaymentMethod(paymentOption?: string) {\n const commonData = this._getCommonCheckoutData();\n\n if (!commonData || !paymentOption) {\n return;\n }\n\n this.bodlEvents.emitPaymentDetailsProvidedEvent({\n ...commonData,\n payment_type: paymentOption,\n });\n }\n\n clickPayButton(payload?: BodlEventsPayload) {\n this.bodlEvents.emit('bodl_checkout_click_pay_button', payload);\n }\n\n paymentRejected() {\n this.bodlEvents.emit('bodl_checkout_payment_rejected');\n }\n\n paymentComplete() {\n this.bodlEvents.emit('bodl_checkout_payment_complete');\n }\n\n exitCheckout() {\n this.bodlEvents.emit('bodl_checkout_exit');\n }\n\n private _trackCompletedStep(step: AnalyticStepType) {\n this._completedSteps[step] = true;\n\n const bodlEventsMap: { [key in AnalyticStepType]?: () => void } = {\n [AnalyticStepType.SHIPPING]: this._trackShippingStepCompleted.bind(this),\n };\n const emit = bodlEventsMap[step];\n\n if (emit) {\n emit();\n } else {\n this.bodlEvents.emit('bodl_checkout_step_completed', { step });\n }\n }\n\n private _trackShippingStepCompleted(): void {\n const shippingMethod = this.state?.getSelectedShippingOption()?.description;\n const commonData = this._getCommonCheckoutData();\n\n if (!commonData || !shippingMethod) {\n return;\n }\n\n this.bodlEvents.emitShippingDetailsProvidedEvent({\n ...commonData,\n shipping_method: shippingMethod,\n });\n }\n\n private _getCommonCheckoutData(): CommonCheckoutData | null {\n const checkout = this.state?.getCheckout();\n\n if (!checkout) {\n return null;\n }\n\n const {\n cart: { cartAmount, currency, lineItems, id, coupons },\n channelId,\n } = checkout;\n\n return {\n event_id: id,\n currency: currency.code,\n cart_value: cartAmount,\n coupon_codes: coupons.map((coupon) => coupon.code.toUpperCase()),\n line_items: this._getProducts(lineItems, currency.code),\n channel_id: channelId,\n };\n }\n\n private _getProducts(lineItems: LineItemMap, currencyCode: string): BODLProduct[] {\n const customItems: BODLProduct[] = (lineItems.customItems || []).map((item) => ({\n product_id: item.id,\n sku: item.sku,\n base_price: item.listPrice,\n sale_price: item.listPrice,\n purchase_price: item.listPrice,\n quantity: item.quantity,\n product_name: item.name,\n currency: currencyCode,\n }));\n\n const giftCertificateItems: BODLProduct[] = lineItems.giftCertificates.map((item) => {\n return {\n product_id: item.id,\n gift_certificate_id: item.id,\n base_price: item.amount,\n sale_price: item.amount,\n purchase_price: item.amount,\n product_name: item.name,\n gift_certificate_name: item.name,\n gift_certificate_theme: item.theme,\n quantity: 1,\n currency: currencyCode,\n };\n });\n\n const physicalAndDigitalItems: BODLProduct[] = [\n ...lineItems.physicalItems,\n ...lineItems.digitalItems,\n ].map((item) => {\n const getCategoryNames = (lineItem: LineItem): string[] => {\n if (Array.isArray(lineItem.categoryNames)) {\n return lineItem.categoryNames;\n } else if (Array.isArray(lineItem.categories)) {\n return flatten(lineItem.categories).map(({ name }) => name);\n }\n\n return [];\n };\n\n let itemAttributes;\n\n if (item.options && item.options.length) {\n itemAttributes = item.options.map((option) => `${option.name}:${option.value}`);\n itemAttributes.sort();\n }\n\n return {\n product_id: item.productId,\n quantity: item.quantity,\n product_name: item.name,\n base_price: item.listPrice,\n sale_price: item.salePrice,\n purchase_price: item.salePrice > 0 ? item.salePrice : item.listPrice,\n sku: item.sku,\n variant_id: item.variantId,\n discount: item.discountAmount,\n brand_name: item.brand,\n currency: currencyCode,\n category_names: getCategoryNames(item),\n retail_price: item.retailPrice,\n };\n });\n\n return [...customItems, ...physicalAndDigitalItems, ...giftCertificateItems].map(\n (item) => ({\n ...item,\n product_id: String(item.product_id),\n }),\n );\n }\n\n private _hasStepCompleted(step: AnalyticStepType): boolean {\n return this._completedSteps[step];\n }\n}\n","import BodlService from './bodl-service';\n\nexport default class NoopBodlService implements BodlService {\n checkoutBegin(): void {}\n\n orderPurchased(): void {}\n\n stepCompleted(): void {}\n\n customerEmailEntry(): void {}\n\n customerSuggestionInit(): void {}\n\n customerSuggestionExecute(): void {}\n\n customerPaymentMethodExecuted(): void {}\n\n showShippingMethods(): void {}\n\n selectedPaymentMethod(): void {}\n\n clickPayButton(): void {}\n\n paymentRejected(): void {}\n\n paymentComplete(): void {}\n\n exitCheckout(): void {}\n}\n","import { CheckoutSelectors } from '../checkout';\n\nimport BodlEmitterService from './bodl-emitter-service';\nimport BodlService from './bodl-service';\nimport { isBodlEnabled } from './is-bodl-enabled';\nimport NoopBodlService from './noop-bodl-service';\n\n/**\n * Creates an instance of `BodlService`.\n *\n * @remarks\n *\n * ```js\n * const bodlService = BodlService();\n * bodlService.checkoutBegin();\n *\n * ```\n *\n * @param {CheckoutService} checkoutService - An instance of CheckoutService\n * @returns an instance of `BodlService`.\n */\nexport default function createBodlService(\n subscribe: (subscriber: (state: CheckoutSelectors) => void) => void,\n): BodlService {\n if (isBodlEnabled(window)) {\n return new BodlEmitterService(subscribe, window.bodlEvents.checkout);\n }\n\n return new NoopBodlService();\n}\n","import BodlEventsWindow from './bodl-window';\n\nexport function isBodlEnabled(window: Window): window is BodlEventsWindow {\n return 'bodlEvents' in window;\n}\n"],"names":["module","exports","require","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","undefined","__webpack_modules__","n","getter","__esModule","d","a","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","r","Symbol","toStringTag","value","throwErrorAction","type","error","meta","action","concat","of","throwError","createErrorAction","payload","message","object","name","setPrototypeOf","__proto__","Error","captureStackTrace","stack","MissingDataErrorType","subtype","MissingBillingAddress","MissingCart","MissingConsignments","MissingCheckout","MissingCustomer","MissingCheckoutConfig","MissingOrderConfig","MissingOrder","MissingOrderId","MissingPayment","MissingPaymentToken","MissingPaymentMethod","MissingShippingAddress","getErrorMessage","BillingAddressActionType","_requestSender","_subscriptionActionCreator","continueAsGuest","credentials","options","store","state","getState","checkout","getCheckout","customer","getCustomer","isGuest","billingAddressRequestBody","billingAddress","getBillingAddress","existingBillingAddressRequestBody","merge","createAction","ContinueAsGuestRequested","defer","this","_createOrUpdateBillingAddress","id","body","ContinueAsGuestSucceeded","pipe","catchError","ContinueAsGuestFailed","_updateCustomerConsent","updateAddress","address","Observable","observer","next","UpdateBillingAddressRequested","email","then","UpdateBillingAddressSucceeded","complete","catch","response","UpdateBillingAddressFailed","acceptsAbandonedCartEmails","acceptsMarketingNewsletter","empty","updateSubscriptions","checkoutId","createAddress","ContentType","SDK_VERSION_HEADERS","DEFAULT_PARAMS","include","join","timeout","url","headers","Accept","post","params","put","ErrorActionType","clearError","ClearError","getEnvironment","process","env","NODE_ENV","e","_console","log","_logToConsole","messages","info","warn","debug","isEnabled","logger","console","getDefaultLogger","cachableActionDecorator","_","descriptor","memoizedMethods","WeakMap","decorateMethod","method","param","lastArg","args","length","useCache","fn","instanceMethods","set","memoize","from","shareReplay","ConfigActionType","_configRequestSender","loadConfig","LoadConfigRequested","LoadConfigSucceeded","LoadConfigFailed","DEFAULT_RESPONSE","status","errors","title","INTERNAL_USE_ONLY","CouponActionType","_couponRequestSender","applyCoupon","code","ApplyCouponRequested","ApplyCouponSucceeded","ApplyCouponFailed","removeCoupon","RemoveCouponRequested","RemoveCouponSucceeded","RemoveCouponFailed","CheckoutIncludes","joinIncludes","includes","uniq","couponCode","AvailableShippingOptions","delete","GiftCertificateActionType","_giftCertificateRequestSender","applyGiftCertificate","giftCertificate","ApplyGiftCertificateRequested","ApplyGiftCertificateSucceeded","ApplyGiftCertificateFailed","removeGiftCertificate","RemoveGiftCertificateRequested","RemoveGiftCertificateSucceeded","RemoveGiftCertificateFailed","giftCertificateCode","isResolvableModule","_factories","_instances","_defaultToken","defaultToken","_useFallback","useFallback","_tokenResolver","tokenResolver","token","cacheToken","_getInstance","register","factory","_hasFactory","_hasInstance","resolvedToken","keys","_registry","_resolveToken","bind","resolveId","_encodeToken","btoa","JSON","stringify","_decodeToken","parse","atob","registeredTokens","query","results","forEach","registeredToken","resolverId","result","matches","default","entries","push","matchedResults","sort","b","filter","matched","find","toResolvableModule","resolveIds","assign","assertApplePayWindow","window","isApplePayWindow","create","request","ApplePaySession","DefaultLabels","_paymentIntegrationService","_sessionFactory","_onAuthorizeCallback","noop","_onError","_subTotalLabel","Subtotal","_shippingLabel","Shipping","initialize","methodId","applepay","container","shippingLabel","subtotalLabel","onError","onPaymentAuthorize","loadPaymentMethod","_paymentMethod","getPaymentMethodOrThrow","verifyCheckoutSpamProtection","_applePayButton","_createButton","addEventListener","_handleWalletButtonClick","deinitialize","Promise","resolve","signIn","signOut","executePaymentMethodCheckout","continueWithCheckoutCallback","containerId","document","getElementById","button","createElement","setAttribute","appendChild","event","preventDefault","cart","getCartOrThrow","config","getStoreConfigOrThrow","getCheckoutOrThrow","initializationData","_getBaseRequest","applePaySession","_handleApplePayEvents","begin","paymentMethod","storeCountryCode","storeName","decimalPlaces","merchantCapabilities","supportedNetworks","requiresShipping","lineItems","physicalItems","requiredBillingContactFields","requiredShippingContactFields","countryCode","currencyCode","total","label","amount","grandTotal","toFixed","subtotal","taxes","tax","onvalidatemerchant","_onValidateMerchant","merchantSession","completeMerchantValidation","onshippingcontactselected","_handleShippingContactSelected","onshippingmethodselected","_handleShippingMethodSelected","oncancel","loadCheckout","onpaymentauthorized","_onPaymentAuthorized","shippingAddress","_transformContactToAddress","shippingContact","updateShippingAddress","abort","selectionShippingOptionId","consignments","selectedShippingOption","availableOptions","availableShippingOptions","selectedOption","unselectedOptions","option","shippingOptions","description","cost","detail","additionalDescription","identifier","isRecommended","Array","completeShippingContactSelection","STATUS_INVALID_SHIPPING_POSTAL_ADDRESS","recommendedOption","optionId","selectedOptionId","_updateShippingOption","newShippingMethods","newTotal","newLineItems","_getUpdatedLineItems","completeShippingMethodSelection","shippingCostTotal","selectShippingOption","paymentData","validationURL","merchantId","location","hostname","bigPayEndpoint","paymentsUrl","payment","billingContact","formattedPayload","apple_pay_token","payment_data","payment_method","transaction_id","transactionIdentifier","transformedBillingAddress","transformedShippingAddress","emailAddress","phone","phoneNumber","updateBillingAddress","submitOrder","useStoreCredit","submitPayment","completePayment","STATUS_SUCCESS","STATUS_FAILURE","contact","firstName","givenName","lastName","familyName","city","locality","company","address1","addressLines","address2","postalCode","stateOrProvince","administrativeArea","stateOrProvinceCode","customFields","paymentIntegrationService","getHost","createRequestSender","host","NotInitializedErrorType","CustomerNotInitialized","PaymentNotInitialized","ShippingNotInitialized","SpamProtectionNotInitialized","boltScriptLoader","boltHostWindow","bolt","onInit","publishableKey","developerConfig","loadBoltClient","testMode","getCustomerEmail","hasBoltAccount","signInCustomer","signOutCustomer","checkoutPaymentMethodExecuted","openBoltCheckoutModalOrThrow","boltClient","getBoltClientOrThrow","getPaymentMethod","embeddedOneClickEnabled","callbacks","close","openCheckout","BoltCheckout","BoltDeveloperMode","StyleButtonSize","StyleButtonShape","scriptLoader","developerModeParams","cartId","storefrontApiToken","loadScript","getDomainURL","getScriptOptions","loadBoltEmbedded","async","attributes","Bolt","developerMode","StagingMode","DevelopmentMode","developerDomain","getScriptLoader","BraintreeEnv","isBraintreeError","Boolean","PaypalButtonStyleLayoutOption","PaypalButtonStyleSizeOption","PaypalButtonStyleColorOption","PaypalButtonStyleLabelOption","PaypalButtonStyleShapeOption","PAYPAL_COMPONENTS","braintreeScriptLoader","braintreeHostWindow","dataCollectors","clientToken","getClient","client","loadClient","clientCreator","authorization","getPaypalCheckout","onSuccess","loadPaypalCheckout","paypalCheckout","paypalCheckoutConfig","paypalCheckoutCallback","braintreePaypalCheckout","paypalSdkLoadConfig","currency","isCreditEnabled","components","toString","intent","paypal","loadPayPalSDK","loadBraintreeLocalMethods","getLocalPaymentInstance","merchantAccountId","braintreeLocalMethods","localPaymentErr","localPaymentInstance","getUsBankAccount","usBankAccount","loadUsBankAccount","getDataCollector","cacheKey","cached","loadDataCollector","kount","deviceData","teardown","getBraintreeEnv","isTestMode","Sandbox","Production","mapToBraintreeShippingAddressOverride","recipientName","line1","line2","mapToLegacyShippingAddress","details","split","first_name","last_name","phone_number","address_line_1","address_line_2","country_code","postal_code","mapToLegacyBillingAddress","removeElement","elementId","element","remove","getSessionId","teardownModule","VERSION","braintree","localPayment","dataCollector","formPoster","braintreeIntegrationService","braintreepaypal","buttonHeight","paypalCheckoutOptions","paypalCheckoutSuccessCallback","renderPayPalButton","paypalCheckoutErrorCallback","handleError","fundingSource","FUNDING","PAYPAL","paypalButtonRender","Buttons","commit","style","height","createOrder","setupPayment","onApprove","authorizeData","tokenizePayment","isEligible","render","loadDefaultCheckout","outstandingBalance","addresses","shippingAddressOverride","createPayment","flow","enableShippingAddress","shippingAddressEditable","offerCredit","tokenizePayload","nonce","postForm","payment_type","provider","device_data","billing_address","shipping_address","buttonContainerId","onErrorCallback","createFormPoster","CartSource","PayPalCommerceIntent","StyleButtonLabel","StyleButtonColor","NonInstantAlternativePaymentMethods","PayPalOrderStatus","paypalCommerceRequestSender","paypalCommerceScriptLoader","loadPayPalSdk","providedCurrencyCode","initializesOnCheckoutPage","getPayPalSDK","paypalSdk","getPayPalSdkOrThrow","createBuyNowCartOrThrow","buyNowInitializeOptions","cartRequestBody","getBuyNowCartRequestBody","createBuyNowCart","providerId","requestBody","updateOrder","consignment","getConsignmentsOrThrow","getOrderStatus","orderId","order_id","source","BuyNow","cart_id","vault_payment_instrument","set_as_default_stored_instrument","device_info","method_id","paypal_account","getShippingOptionOrThrow","selectedShippingOptionId","recommendedShippingOption","shippingOptionToSelect","getAddress","getBillingAddressFromOrderDetails","payer","given_name","surname","email_address","admin_area_2","admin_area_1","getShippingAddressFromOrderDetails","orderDetails","shipping","getValidButtonStyle","color","shape","validStyles","getValidHeight","omitBy","isNil","requestSender","getPayPalSdkScriptConfigOrThrow","paypalSdkScriptConfig","paypalLoadScript","clientId","buyerCountry","attributionId","isVenmoEnabled","isHostedCheckoutEnabled","isPayPalCreditAvailable","isDeveloperModeApplicable","availableAlternativePaymentMethods","enabledAlternativePaymentMethods","shouldEnableCard","enableCardFunding","disableCardFunding","enableCreditFunding","disableCreditFunding","shouldEnableAPMs","enableVenmoFunding","disableVenmoFunding","enableAPMsFunding","disableAPMsFunding","apm","disableFunding","enableFunding","paypalCommerceIntegrationService","paypalcommerce","renderButton","onComplete","defaultCallbacks","orderID","hostedCheckoutCallbacks","onShippingAddressChange","data","onShippingOptionsChange","actions","onHostedCheckoutApprove","buttonRenderOptions","paypalButton","order","shippingOption","paypalcommercecredit","paypalCommerceCredit","fundingSources","PAYLATER","CREDIT","hasRenderedSmartButton","gold","paypalcommercevenmo","VENMO","createCustomerStrategyRegistry","customerStrategyFactories","registry","createCustomerStrategy","isSpamProtectionExecuteSucceededAction","succeededAction","CustomerActionType","_customerRequestSender","_checkoutActionCreator","_spamProtectionActionCreator","createCustomer","customerAccount","isStorefrontSpamProtectionEnabled","checkoutSettings","createAccount","switchMap","loadCurrentCheckout","CreateCustomerSucceeded","CreateCustomerRequested","execute","CreateCustomerFailed","customerAddress","CreateCustomerAddressRequested","CreateCustomerAddressSucceeded","CreateCustomerAddressFailed","SignInCustomerRequested","SignInCustomerSucceeded","SignInCustomerFailed","SignOutCustomerRequested","SignOutCustomerSucceeded","SignOutCustomerFailed","CustomerStrategyActionType","_strategyRegistry","_strategyRegistryV2","SignInRequested","_getStrategy","SignInSucceeded","SignInFailed","SignOutRequested","SignOutSucceeded","SignOutFailed","ExecutePaymentMethodCheckoutRequested","ExecutePaymentMethodCheckoutSucceeded","ExecutePaymentMethodCheckoutFailed","customerStrategies","isInitialized","InitializeRequested","InitializeSucceeded","InitializeFailed","DeinitializeRequested","DeinitializeSucceeded","DeinitializeFailed","widgetInteraction","WidgetInteractionStarted","WidgetInteractionFinished","WidgetInteractionFailed","strategy","joinOrMergeIncludes","baseIncludes","includeDictionaryOrList","isArray","includesDictionary","deletions","pickBy","on","additions","difference","mergeIncludes","updateCheckout","CheckoutActionType","_checkoutRequestSender","_configActionCreator","_formFieldsActionCreator","LoadCheckoutRequested","loadFormFields","LoadCheckoutSucceeded","LoadCheckoutFailed","context","getContextConfig","UpdateCheckoutRequested","UpdateCheckoutSucceeded","UpdateCheckoutFailed","FormFieldsActionType","_formFieldsRequestSender","LoadFormFieldsRequested","loadFields","LoadFormFieldsSucceeded","LoadFormFieldsFailed","PaymentMethodActionType","loadPaymentMethods","LoadPaymentMethodsRequested","deviceSessionId","sessionHash","methods","filteredMethods","_filterApplePay","LoadPaymentMethodsSucceeded","LoadPaymentMethodsFailed","getCart","LoadPaymentMethodRequested","LoadPaymentMethodSucceeded","LoadPaymentMethodFailed","isEqual","cartA","cartB","_normalize","cartAmount","digitalItems","slice","itemA","itemB","productId","variantId","localeCompare","map","item","extendedSalePrice","quantity","giftCertificates","recipient","giftWrapping","previous","updated","validate","comparator","_compareCoupons","coupons","_compareGiftCertificates","_getComparableCheckout","couponsA","couponsB","giftCertificatesA","giftCertificatesB","promise","cancellable","reject","cancel","race","_mutationObserver","ensurePresence","targets","mutationsList","mutation","removedNodes","node","some","target","contains","observe","childList","subtree","output","disconnect","_window","callback","MutationObserver","parseUrl","test","anchor","href","port","indexOf","hash","origin","protocol","pathname","search","isIframeEvent","targetOrigin","_targetWindow","_targetOrigin","targetWindow","fromEvent","successType","errorType","take","toPromise","postMessage","setTarget","bindMethodDecorator","decoratedTarget","getOwnPropertyNames","getOwnPropertyDescriptor","bindClassDecorator","boundMethod","sourceOrigin","_sourceOrigins","replace","_isListening","_listeners","listen","_handleMessage","stopListen","removeEventListener","addListener","listener","listeners","removeListener","index","splice","trigger","_googleRecaptcha","handle","errorOrId","handleWithRecaptchaSitekey","handleWithPaymentHumanVerificationRequestError","_isPaymentHumanVerificationRequest","_initialize","additional_action_required","_performRecaptcha","human_verification_token","recaptchaSitekey","cardingProtectionElementId","cardingProtectionElement","parentNode","removeChild","load","googleRecaptchaScriptLoader","mutationObserverFactory","_memoized","recaptcha","sitekey","event$","Subject","_widgetId","size","getResponse","reset","_event$","_recaptcha","querySelector","retryWhen","delay","TIMEOUT","_watchRecaptchaChallengeWindow","iframeContainer","parentElement","visibility","attributeFilter","_scriptLoader","_loadPromise","_loadScript","callbackName","grecaptcha","createSpamProtection","MutationObserverFactory","mapFromPaymentErrorResponse","joinErrors","reduce","flatMap","values","fieldErrors","HostedFieldEventType","HostedInputEventType","_type","_containerId","_placeholder","_accessibilityLabel","_styles","_eventPoster","_eventListener","_detachmentObserver","_cardInstrument","_iframe","src","border","overflow","width","getType","attach","contentWindow","AttachRequested","accessibilityLabel","cardInstrument","fontUrls","_getFontUrls","placeholder","styles","AttachSucceeded","AttachFailed","detach","submitForm","fields","SubmitRequested","SubmitSucceeded","SubmitFailed","_isSubmitErrorEvent","validateForm","ValidateRequested","Validated","isValid","links","querySelectorAll","link","fontFamily","family","_fields","_payloadTransformer","_eventCallbacks","_paymentHumanVerificationHandler","_handleEnter","onBlur","onCardTypeChange","onFocus","onValidate","Blurred","CardTypeChanged","Focused","Entered","_cardType","cardType","BinChanged","_bin","bin","getBin","getCardType","field","_getFirstField","otherFields","without","all","otherField","submit","additionalActionData","transform","additionalAction","isVaultedInstrument","instrument","instrumentId","_store","getConfig","instrumentMeta","instruments","getInstrumentsMeta","getOrder","orderMeta","getOrderMeta","omit","paymentMethods","gatewayId","paymentMethodMeta","getPaymentMethodsMeta","authToken","getPaymentToken","vaultAccessToken","fieldOptions","_getCardInstrument","pick","createScriptLoader","getCardInstrument","MissingPaymentInstrument","OrderActionType","_orderRequestSender","_checkoutValidator","loadOrder","LoadOrderRequested","LoadOrderSucceeded","LoadOrderFailed","loadOrderPayments","LoadOrderPaymentsRequested","LoadOrderPaymentsSucceeded","LoadOrderPaymentsFailed","loadCurrentOrder","_getCurrentOrderId","SubmitOrderRequested","externalSource","getExternalSource","variantIdentificationToken","getVariantIdentificationToken","shouldExecuteSpamCheck","_mapToOrderRequestBody","customerMessage","checkoutVariant","SubmitOrderSucceeded","SubmitOrderFailed","finalizeOrder","FinalizeOrderRequested","FinalizeOrderSucceeded","FinalizeOrderFailed","gateway","PaymentActionType","_paymentRequestSender","_orderActionCreator","_paymentRequestTransformer","initializeOffsitePayment","shouldSaveInstrument","shouldSetAsDefaultInstrument","bigpay_token","InitializeOffsitePaymentRequested","InitializeOffsitePaymentSucceeded","InitializeOffsitePaymentFailed","SubmitPaymentRequested","SubmitPaymentSucceeded","SubmitPaymentFailed","_client","_transformResponse","statusText","createPaymentClient","paymentClient","subscribe","getStoreConfig","setHost","paymentSettings","bigpayBaseUrl","isBillingAddressLike","mapToInternalAddress","addressId","addressLine1","addressLine2","province","provinceCode","postCode","country","_decimalPlaces","toInteger","Math","round","pow","CheckoutButtonMethodType","couponTypes","mapToInternalCoupon","coupon","discount","displayName","discountType","couponType","mapToInternalGiftCertificate","discountedAmount","used","remainingBalance","remaining","balance","purchaseDate","mapToInternalLineItems","itemMap","idKey","amountTransformer","imageUrl","amountAfterDiscount","integerAmount","integerAmountAfterDiscount","integerUnitPrice","integerUnitPriceAfterDiscount","integerDiscount","sender","mapGiftCertificateToInternalLineItem","extendedListPrice","discountAmount","listPrice","salePrice","downloadsPageUrl","downloadPageUrl","brand","sku","categoryNames","addedByPromotion","mapToInternalLineItem","mapToInternalLineItemType","mapToInternalCart","promotions","notifications","items","sum","discountNotifications","promotion","banners","banner","placeholders","messageHtml","text","totalDiscountedAmount","certificate","appliedGiftCertificates","keyBy","amountBeforeDiscount","shippingCostBeforeDiscount","integerAmountBeforeDiscount","required","lineItem","isShippingRequired","storeCredit","taxSubtotal","taxTotal","handling","handlingCostTotal","mapToInternalCustomer","customerId","fullName","customerGroupName","customerGroup","format","RegExp","month","year","trimmedMonth","trimmedYear","toObject","card","number","maxLength","max","creditCardType","lengths","unformattedValue","unformat","gaps","gapIndex","mapToInternalOrder","payments","customerCanBeCreated","mapToInternalOrderPayment","baseAmount","orderToken","callbackUrl","socialData","mapToInternalSocialDataList","hasDigitalItems","isDownloadable","isComplete","mapToStoreCredit","orderAmount","orderAmountAsInteger","isDefaultOrderPayment","step","helpText","instructions","returnUrl","socialDataObject","socialMedia","image","shareText","sharingLink","channelName","channel","channelCode","mapToInternalShippingOption","isSelected","price","selected","transitTime","_cardExpiryFormatter","_cardNumberFormatter","checkoutState","formattedInstrument","_mapShippingAddress","getConsignments","getShippingOption","storeConfig","contextConfig","paymentMeta","internalCustomer","_transformPaymentMethod","quoteMeta","geoCountryCode","storeProfile","transformWithHostedFormData","_transformHostedInputValues","ccCvv","cardCodeVerification","ccNumber","cardNumberVerification","hostedFormNonce","cardCode","ccExpiry","cardExpiry","ccName","cardName","cardNumber","isBopisEnabled","bopis","enabled","requiredAddress","isPickup","every","selectedPickupOption","getShippingAddress","ConsignmentActionType","_consignmentRequestSender","unassignItemsByAddress","_consignmentHasAddress","existingConsignment","getConsignmentByAddress","_removeLineItems","updateConsignment","deleteConsignment","assignItemsByAddress","_createOrUpdateConsignment","_addLineItems","consignmentUpdateBody","shippingOptionId","consignmentMeta","UpdateShippingOptionRequested","UpdateShippingOptionSucceeded","UpdateShippingOptionFailed","loadShippingOptions","LoadShippingOptionsRequested","LoadShippingOptionsSucceeded","LoadShippingOptionsFailed","_getUpdateAddressRequestBody","createConsignments","CreateConsignmentsRequested","CreateConsignmentsSucceeded","CreateConsignmentsFailed","UpdateConsignmentRequested","UpdateConsignmentSucceeded","UpdateConsignmentFailed","consignmentId","DeleteConsignmentRequested","DeleteConsignmentSucceeded","DeleteConsignmentFailed","updateShippingOption","_isUpdateConsignmentRequest","customItems","itemId","_hydrateLineItems","lineItemIds","existingItem","sharedItem","DEFAULT_INCLUDES","SpamProtectionActionType","spamProtectionElementId","spamProtectionElement","googleRecaptchaSitekey","VerifyCheckoutRequested","VerifyCheckoutSucceeded","VerifyCheckoutFailed","ExecuteRequested","ExecuteSucceeded","ExecuteFailed","StoreCreditActionType","_storeCreditRequestSender","applyStoreCredit","ApplyStoreCreditRequested","removeStoreCredit","ApplyStoreCreditSucceeded","ApplyStoreCreditFailed","SubscriptionsActionType","_subscriptionsRequestSender","subscriptions","UpdateSubscriptionsRequested","UpdateSubscriptionsSucceeded","UpdateSubscriptionsFailed","isPlainObject","cloneDeep","input","cloneDeepSafe","cache","cloneResult","createPaymentIntegrationSelectors","getBillingAddressOrThrow","getLocale","getCustomerOrThrow","getCardInstrumentOrThrow","getOrderOrThrow","getPaymentTokenOrThrow","getPaymentId","getPaymentIdOrThrow","getPaymentStatus","getPaymentStatusOrThrow","getPaymentRedirectUrl","getPaymentRedirectUrlOrThrow","isPaymentDataRequired","isPaymentMethodInitialized","getShippingAddressOrThrow","getShippingAddresses","getShippingAddressesOrThrow","_storeProjectionFactory","_hostedFormFactory","_billingAddressActionCreator","_consignmentActionCreator","_paymentMethodActionCreator","_paymentActionCreator","_customerActionCreator","_cartRequestSender","_storeCreditActionCreator","_storeProjection","createHostedForm","subscriber","filters","initializeOffsitePaymentConfig","dispatch","buyNowCartRequestBody","ProjectionActionType","createDataStoreProjection","stateTransformer","projection","createDataStore","Synchronize","initial","_transformSelectors","createPaymentIntegrationService","storeProjectionFactory","checkoutActionCreator","hostedFormFactory","orderActionCreator","billingAddressActionCreator","consignmentActionCreator","paymentMethodActionCreator","paymentActionCreator","customerActionCreator","storeCreditActionCreator","spamProtection","spamProtectionRequestSender","spamProtectionActionCreator","cartRequestSender","getShippableItemsCount","guard","errorFactory","AmazonPayV2Regions","AmazonPayV2CheckoutLanguage","AmazonPayV2Placement","AmazonPayV2LedgerCurrency","AmazonPayV2PayOptions","AmazonPayV2ButtonColor","AmazonPayV2ButtonDesign","_amazonPayV2ScriptLoader","_amazonPayV2SDK","_buttonParentContainer","_createAmazonPayButtonParentContainer","_amazonPayV2Button","bindButton","buttonId","sessionId","changeAction","_getAmazonPayV2SDK","Pay","bindChangeAction","amazonCheckoutSessionId","createButton","prepareCheckout","createCheckoutSessionConfig","requestConfig","_prepareRequestConfig","_getAmazonPayV2Button","onClick","initCheckout","prepareCheckoutWithCreationRequestConfig","createCheckoutConfig","estimatedOrderAmount","productType","signout","renderAmazonPayButton","buttonColor","decoupleCheckoutInitiation","placement","parentContainerId","_getButtonParentContainer","design","C0001","amazonPayV2ButtonOptions","_getAmazonPayV2ButtonOptions","setCartRequestBody","_buyNowCartRequestBody","isPh4Enabled","features","isPh4UsOnly","publicKeyId","signedPayload","_isEnvironmentSpecific","uid","random","substr","parentContainer","Gold","checkoutLanguage","checkoutSessionMethod","extractAmazonCheckoutSessionId","ledgerCurrency","buttonBaseConfig","sandbox","PayOnly","PayAndShip","shopPath","buttonOptions","tmpConfig","createCheckoutSession","_getOrThrow","region","amazonPayV2Region","amazon","createAmazonPayV2PaymentProcessor","_braintreeScriptLoader","_dataCollectors","_clientToken","getPaypal","_paypal","loadPaypal","_paypalCheckout","getVenmoCheckout","_venmoCheckout","loadVenmoCheckout","venmoCheckout","venmoCheckoutConfig","allowDesktop","paymentMethodUsage","venmoCheckoutCallback","braintreeVenmoCheckout","isBrowserSupported","get3DS","_3ds","load3DS","version","getVisaCheckout","_visaCheckout","loadVisaCheckout","getGooglePaymentComponent","_googlePay","loadGooglePayment","createHostedFields","loadHostedFields","_teardown","mod","threeDSecure","visaCheckout","venmo","googlePayment","hostedFields","_braintreeSDKCreator","createInitOptions","settings","locale","collectShipping","paymentRequest","String","handleSuccess","billing","braintreeVisaCheckout","tokenize","tokenizedPayload","_toVisaCheckoutAddress","_postForm","userData","cardInformation","userEmail","card_information","_getCardInformation","_getAddress","streetAddress","extendedAddress","lastTwo","createBraintreeVisaCheckoutPaymentProcessor","braintreeSDKCreator","V","JPMC","CallbackTriggerType","TotalPriceStatusType","CallbackIntentsType","ButtonType","ButtonColor","BillingAddressFormat","getFirstAndLastName","nameParts","_googlePayScriptLoader","_googlePayInitializer","_isBuyNowFlow","googlePayClientOptions","_methodId","_configureWallet","buttonType","Short","Default","_googlePayClient","updatePaymentDataRequest","paymentDataRequest","existingPaymentDataRequest","_getPaymentDataRequest","_paymentDataRequest","merchantInfo","transactionInfo","shippingAddressParameters","displayWallet","loadPaymentData","parseResponse","_updateBillingAddress","_mapGooglePayAddressToShippingAddress","updateBuyNowFlowFlag","isBuyNowFlow","_getMethodId","_getCheckout","hasShippingAddress","googlePay","_getGooglePayClient","isReadyToPay","allowedPaymentMethods","parameters","allowedAuthMethods","allowedCardNetworks","apiVersion","apiVersionMinor","lastFour","google","environment","api","PaymentsClient","_mapGooglePayAddressToBillingAddress","customerEmail","paymentMethodData","companyName","address3","postPaymentData","buyNowCartId","tokenFormat","remoteBillingAddress","googlePayAddressMapped","createGooglePayPaymentProcessor","initializer","_getGooglePayPaymentDataRequest","totalPrice","gatewayMerchantId","merchantName","authJwt","billingAddressRequired","billingAddressParameters","Full","phoneNumberRequired","tokenizationSpecification","totalPriceStatus","FINAL","emailRequired","shippingAddressRequired","baseRequest","_getGooglePaymentDataRequest","supportedCards","paymentGatewaySpecification","_getPaymentGatewaySpecification","cardPaymentMethod","_getCardPaymentMethod","googleBraintreePaymentInstance","_googlePaymentInstance","_createGooglePayPayload","tokenizationData","androidPayCards","binData","platformToken","googlePayBraintreePaymentDataRequest","googleMerchantName","googleMerchantId","cardRequirements","billingAddressFormat","_mapGooglePayBraintreeDataRequestToGooglePayDataRequestV2","createPaymentDataRequest","googlePayBraintreeDataRequestV1","paymentMethodTokenizationParameters","_publishableKey","_testMode","_errorMessage","checkoutcomkey","_mapGooglePayCheckoutcomDataRequestToGooglePayDataRequestV2","err","signature","protocolVersion","signedMessage","_convertToken","finalToken","cardNetwork","cardDetails","token_format","_requestCheckoutcomTokenize","token_data","checkoutcomToken","checkoutcomKey","Authorization","last4","stripeVersion","stripePublishableKey","stripeConnectedAccount","useMasterpassSrc","language","sourceUrl","masterpass","getStripeClient","stripeAccount","stripeClient","bcStripeClient","stripe","betas","getElements","stripeElements","bcStripeElements","fetchUpdates","update","elements","Stripe","initializeBilling","methodName","initializeShipping","initializePayment","loadSettings","generateToken","trackAuthorizationEvent","forgetCheckout","RemoteCheckoutActionType","_remoteCheckoutRequestSender","InitializeRemoteBillingRequested","InitializeRemoteBillingSucceeded","InitializeRemoteBillingFailed","InitializeRemoteShippingRequested","InitializeRemoteShippingSucceeded","InitializeRemoteShippingFailed","InitializeRemotePaymentRequested","InitializeRemotePaymentSucceeded","InitializeRemotePaymentFailed","LoadRemoteSettingsRequested","LoadRemoteSettingsSucceeded","LoadRemoteSettingsFailed","SignOutRemoteCustomerRequested","SignOutRemoteCustomerSucceeded","SignOutRemoteCustomerFailed","ForgetCheckoutRemoteCustomerRequested","ForgetCheckoutRemoteCustomerSucceeded","ForgetCheckoutRemoteCustomerFailed","UpdateRemoteCheckout","_remoteCheckoutActionCreator","_amazonPayV2PaymentProcessor","amazonpay","Checkout","_customerStrategyActionCreator","_braintreeVisaCheckoutPaymentProcessor","_visaCheckoutScriptLoader","_formPoster","_buttonClassName","visaCheckoutOptions","initOptions","storeLanguage","signInButton","_createSignInButton","init","paymentSuccessPayload","_paymentInstrumentSelected","_onPaymentSelectComplete","queueId","buttonClass","_insertVisaCheckoutButton","visaCheckoutButton","display","flexDirection","className","innerHTML","braintreepaypalcredit","_renderPayPalButton","_handleError","buttonStyle","_setupPayment","_tokenizePayment","_removeElement","_chasePayScriptLoader","chasePayOptions","digitalSessionId","ChasePay","configure","isChasePayUp","insertButtons","containers","EventType","START_CHECKOUT","startCheckout","COMPLETE_CHECKOUT","requestId","merchantRequestId","_setExternalCheckoutData","_reloadPage","sessionToken","sendRequest","fromChasePay","GooglePayCustomerMethodType","_googlePayPaymentProcessor","googlePayOptions","_getGooglePayOptions","_walletButton","googlepayadyenv2","googlepayadyenv3","googlepayauthorizenet","googlepaybnz","googlepaybraintree","googlepaycheckoutcom","googlepaycybersourcev2","googlepayorbital","googlepaystripe","googlepaystripeupe","googlepayworldpayaccess","hasPhysicalItems","payloadToUpdate","checkoutUrl","siteLink","getCallbackUrl","supportedLocales","es","en","pt","zu","ar","zh","ms","uk","sv","hr","pl","nl","it","de","fr","formatLocale","localeLanguage","toLowerCase","formattedLocale","countryLocales","_masterpassScriptLoader","_locale","masterpassOptions","allowedCardTypes","suppressShippingAddress","masterpassScriptLoaderParams","isMasterpassSrcEnabled","Masterpass","_signInButton","subdomain","StripeFormMode","DisplayName","StripePaymentMethodType","StripeStringConstants","StripeElementType","_stripeUPEScriptLoader","stripeupe","onEmailChange","getStyles","isLoading","isStripeLinkAuthenticated","appearance","variables","colorPrimary","fieldInnerShadow","colorBackground","fieldBackground","colorText","labelText","colorDanger","fieldErrorText","colorTextSecondary","colorTextPlaceholder","fieldPlaceholderText","rules","borderColor","fieldBorder","fieldText","boxShadow","stripeUPEClient","_stripeElements","clientSecret","billingEmail","defaultValues","mode","SHIPPING","linkAuthenticationElement","getElement","AUTHENTICATION","StripeLinkAuthenticated","authenticated","mount","unmount","ExtensionActionType","_extension","_cartId","URL","searchParams","InvalidExtensionConfigError","loadExtensions","LoadExtensionsRequested","extensions","LoadExtensionsSucceeded","LoadExtensionsFailed","renderExtension","extension","getExtensionByRegion","ExtensionNotFoundError","RenderExtensionRequested","ExtensionIframe","RenderExtensionSucceeded","RenderExtensionFailed","invalidFields","getBrowserInfo","navigator","userLanguage","color_depth","screen","colorDepth","java_enabled","javaEnabled","screen_height","screen_width","time_zone_offset","Date","getTimezoneOffset","AdyenActionType","AdyenComponentType","AdyenPaymentMethodType","HTTPMethod","ResultCode","AdyenV2CardFields","isCardState","encryptedSecurityCode","encryptedExpiryMonth","adyenv2","_paymentInitializeOptions","originKey","clientKey","paymentMethodsResponse","clientSideAuthentication","translations","_adyenClient","_mountPaymentComponent","_paymentComponent","CreditCard","Bancontact","_mountCardVerificationComponent","_cardVerificationComponent","_validateCardData","componentState","_componentState","bigpayToken","encryptedCardNumber","encryptedExpiryYear","credit_card_number_confirmation","expiry_month","expiry_year","verification_value","browser_info","_processAdditionalAction","credit_card_token","finalize","_getAdyenClient","_getPaymentInitializeOptions","_getThreeDS2ChallengeWidgetSize","additionalActionOptions","threeDS2Options","widgetSize","_handleAction","threeDS2ContainerId","onBeforeLoad","onLoad","adyenAction","additionalActionComponent","createFromAction","onAdditionalDetails","additionalActionState","paymentPayload","paymentMethodType","ThreeDS2Challenge","QRCode","_mapAdyenPlaceholderData","prefillCardHolderName","holderName","street","houseNumberOrName","cardVerificationComponent","adyenClient","cardVerificationContainerId","SecuredFields","caretColor","onChange","_updateComponentState","validateState","validateCardFields","onFieldValid","paymentComponent","ACH","IDEAL","SEPA","hasVaultedInstruments","AliPay","GiroPay","Sofort","Klarna","KlarnaPayNow","KlarnaAccount","Vipps","WeChatPayQR","provider_data","cardComponent","componentRef","showValidation","issuer","_mapCardErrors","cardStateErrors","_stylesheetLoader","configuration","loadStylesheet","AdyenCheckout","getStylesheetLoader","isHostedInstrumentLike","AdyenV3CardFields","adyenv3","paymentMethodsConfiguration","klarna","useKlarnaWidget","klarna_account","klarna_paynow","showPayButton","challengeWindowSize","showBrandsUnderCardNumber","onSubmit","HostedFieldType","isHostedCardFieldOptionsMap","isHostedStoredCardFieldOptionsMap","_blueSnapDirectHostedForm","creditCard","is3dsEnabled","_paymentFieldsToken","_shouldUseHostedFields","form","_getPaymentFieldsToken","pfToken","_getBlueSnapDirectThreeDSecureData","bluesnapSubmitedForm","cardHolderName","billingFirstName","billingLastName","billingCountry","billingState","billingCity","trim","billingZip","shippingFirstName","shippingLastName","shippingCountry","shippingState","shippingCity","shippingZip","BlueSnapDirectCardType","BlueSnapDirectEventOrigin","BlueSnapDirectErrorDescription","BlueSnapDirectErrorCode","BlueSnapDirectHostedFieldTagId","BlueSnapHostedFieldType","CREDIT_CARD_ERRORS","fieldType","invalid","_nameOnCardInput","_hostedInputValidator","_blueSnapSdk","initializeValidationFields","initializeValidationCVVFields","paymentFieldsToken","enable3DS","callbacksAndStyles","blueSnapSdk","_getBlueSnapSdk","_onValidate","_setCustomBlueSnapAttributes","_setCustomStoredCardsBlueSnapAttributes","_getHostedPaymentFieldsOptions","hostedPaymentFieldsCreate","threeDSecureData","shouldSendName","hostedPaymentFieldsSubmitData","_isBlueSnapDirectCallbackError","statusCode","errorDescription","cardData","getValue","onEnter","onFieldEventHandler","setupComplete","_usetUiEventCallback","onType","_tagId","onValid","tagId","ccnPlaceHolder","cvvPlaceHolder","expPlaceHolder","_mapStyles","focus","selector","declaration","declarationBlock","property","kebabCase","errorCode","eventOrigin","EMPTY","INVALID","cardNumberContainer","cardExpiryContainer","cardCodeContainer","cardNameContainer","dataset","bluesnap","_errors","_updateErrors","errorData","_style","_create","_getInput","_handleFocus","_handleBlur","_input","_applyStyles","HTMLInputElement","allowedStyle","fontSize","fontWeight","styleKeys","_configureInput","autocomplete","inputMode","backgroundColor","margin","outline","padding","BlueSnapDirectSdkEnv","SANDBOX","PRODUCTION","isBlueSnapDirectEcpInstrument","assertBlueSnapDirectEcpInstrument","ecp","account_number","accountNumber","account_type","accountType","shopper_permission","shopperPermission","routing_number","routingNumber","bluesnapdirect","_initializeOptions","_isBlueSnapDirectRedirectResponse","partialValue","merchantid","isBlueSnapDirectRedirectResponseProviderData","providerData","providerDataQuery","URLSearchParams","frameUrl","redirect_url","frame","iframe","createIframe","partialResponse","partialBody","storage","saveExtraItemsData","category","setItem","getStorageKey","readExtraItemsData","getItem","itemsData","isObject","hasNotExtraItems","isExtraItemsData","clearExtraItemData","removeItem","ORDER_ITEMS_STORAGE_KEY","isAnalyticsTrackerWindow","isWithAccountCreation","BoltError","getError","analyticsExtraItemsManager","useBoltClient","useBoltEmbedded","onPaymentSelect","useBigCommerceCheckout","boltEmbedded","mountBoltEmbeddedField","embeddedField","setExtraItemsForAnalytics","isBoltPaymentData","getBoltClientPaymentPayload","getBoltEmbeddedPaymentPayload","getBoltFullCheckoutPaymentPayload","isStoreCreditApplied","success","transaction","reference","open","boltTransaction","validateTokenizeResultOrThrow","tokenizeResult","last_four_digits","iin","expiration_month","expiration","expiration_year","create_account","shouldCreateAccount","embedded_checkout","setBoltOrderId","getTransactionReference","transactionReference","getBoltEmbeddedOrThrow","setOrderId","renderSeparateFields","lastFourDigits","expirationMonth","expirationYear","Number","isNaN","isAnalyticsEnabled","isUsBankAccountInstrumentLike","getMandateText","braintreeach","orderRequest","isSubmittingWithVaultingInstrument","tokenizePaymentForVaultedInstrument","preparePaymentDataForVaultedInstrument","preparePaymentData","submitPaymentPayload","tokenized_bank_account","masked_account_number","getUsBankAccountOrThrow","mandateText","bankDetails","getBankDetails","isVaultingEnabled","ownershipType","businessName","loadingIndicator","braintreelocalmethods","loadingIndicatorContainer","toggleLoadingIndicator","startPayment","paymentType","fallback","buttonText","onPaymentStart","start","paymentId","startPaymentError","payloadData","show","hide","DEFAULT_STYLES","ROTATION_ANIMATION","defineAnimation","buildContainer","indicator","buildIndicator","parentId","opacity","handleTransitionEnd","bottom","left","position","right","top","transition","borderRadius","transformStyle","animation","head","sheet","CSSStyleSheet","insertRule","_isHostedPaymentFormEnabled","_shouldRenderHostedForm","_executeWithHostedForm","_executeWithoutHostedForm","_isHostedFieldAvailable","formOptions","_hostedForm","isHostedFormEnabled","_isAdditionalActionRequired","redirectUrl","PaymentStatusTypes","orderPayload","_shouldSubmitFullPayload","onRenderButton","handleClick","handleApprove","onCancel","paypalOptions","pollingInterval","maxPollingTime","pollingTimer","stopPolling","paypalcommercealternativemethods","shouldRenderFields","renderFields","isNonInstantPaymentMethod","deinitializePollingMechanism","reinitializeStrategy","resetPollingMechanism","initializePollingMechanism","apmFieldsContainer","apmFieldsStyles","fieldContainerElement","fieldsOptions","PaymentFields","setTimeout","clearTimeout","orderStatus","isOrderApproved","Approved","isOrderPending","Created","PayerActionRequired","toUpperCase","isCreditCardFormFields","paypalcommercecreditcards","hostedFormOptions","isCreditCardForm","executionPaymentData","validateHostedFormOrThrow","submitHostedForm","hostedFieldsOptions","mapFieldOptions","mapStyleOptions","paymentsSDK","getInstrumentParams","HostedFields","setFormFieldEvents","renderCardNameField","cardNameFiledStylesPreset","defaultCardNameFiledStyles","focusCardNameFiledStyles","defaultStyleProperties","getValidStyleString","focusStyleProperties","cardNameField","setFieldStyleAttribute","eventsData","eventName","formCallback","eventHandler","getFieldTypeByEmittedField","getCardTypeByEvent","getValidityData","emittedBy","mapFieldType","cards","getHostedFieldsOrThrow","cardholderName","contingencies","liabilityShift","hostedFieldState","validationData","mapValidationErrors","fieldsKeys","fieldsErrors","getInvalidErrorByFieldType","validationErrors","expirationDate","cvv","mapStyles","newObject","applicationId","locationId","square","_payments","_formValidationSubscription","unsubscribe","_card","destroy","initializeCard","onValidationChange","_getPayments","_subscribeToFormValidation","_getCard","errorMessage","verifyBuyer","_mapToSquareBillingContact","blacklist","Set","eventObservables","eventType","isCompletelyValid","distinctUntilChanged","_squareV2PaymentProcessor","squarev2","_shouldVerify","SquareV2WebPaymentsSdkEnv","LIVE","isSquareV2Window","assertSquareV2Window","Square","CountryActionType","_countryRequestSender","loadCountries","LoadCountriesRequested","LoadCountriesSucceeded","LoadCountriesFailed","_config","createPaymentStrategyRegistry","paymentStrategyFactories","createPaymentStrategy","PaymentStrategyActionType","PaymentStrategyType","FinalizeRequested","_loadOrderPaymentsIfNeeded","FinalizeSucceeded","FinalizeFailed","paymentStrategies","getByMethod","_namespace","rawValue","withNamespace","getItemOnce","isPPSDKPaymentMethod","initializationStrategy","checkoutcomStrategies","credit_card","sepa","ideal","fawry","_getToken","_hasFactoryForMethod","saveExternalId","externalId","_affirmScriptLoader","publicKey","affirm","_affirm","_getCheckoutInformation","onFail","failObject","reason","successObject","ui","checkout_token","_getBillingAddress","merchant","user_confirmation_url","checkoutLink","user_cancel_url","user_confirmation_url_action","_getShippingAddress","_getItems","metadata","shipping_type","_getShippingType","platform_type","platform_version","platform_affirm","discounts","_getDiscounts","shipping_amount","tax_amount","first","last","full","zipcode","display_name","unit_price","qty","item_image_url","item_url","categories","_getCategories","line","discount_amount","discount_display_name","DISCOUNTED_AMOUNT","categoryTree","apikey","scriptURI","_getScriptURI","m","g","h","c","k","p","getElementsByTagName","l","arguments","f","a1","c1","a2","c2","insertBefore","public_api_key","script","_afterpayScriptLoader","_mapCurrencyToISO2","_afterpaySdk","_loadPaymentMethod","_redirectToAfterpay","redirect","AUD","NZD","CAD","USD","AfterPay","_paymentStrategyActionCreator","paymentToken","_isReadyToPay","editButtonId","_bindEditButton","_isModalFlow","_createContainer","_amazonPayButton","_isOneTimeTransaction","_getAmazonPayButton","click","isModalFlow","clone","cloneNode","replaceChild","_showLoadingSpinner","_options","_threeDSecureFlow","prepare","ACKNOWLEDGE","FINALIZE","_createIframe","bluesnapv2","_createElements","closeElement","mainElement","_element","_closeElement","_mainElement","_registerClick","_unregisterClick","_removeAfterTransition","classLayout","classClose","classOverlayText","background","transitionDuration","hasCloseButton","innerHtml","overlayText","addClassLayout","innerText","getOverlayStyle","_addEventListener","_removeEventListener","handleTransition","propertyName","BraintreeFormFieldType","off","isBraintreeFormFieldsMap","BraintreeHostedFormType","_isInitializedHostedForm","_formOptions","_mapFieldType","_mapErrors","_handleNameBlur","CardName","_handleNameFocus","_handleCardTypeChange","_handleInputSubmitRequest","_handleValidityChange","_mapValidationErrors","StoredCardVerification","_mapFieldOptions","isEmpty","_mapStyleOptions","_cardFields","_cardNameField","_mapBillingAddress","_mapTokenizeError","tokenizeForStoredCardVerification","countryName","internalLabel","CardNumberVerification","CardNumber","CardExpiry","CardCodeVerification","CardCode","_isValidParam","isPotentiallyValid","fieldKey","_createInvalidError","isStoredCard","cvvValidation","_createRequiredError","expirationDateValidation","cardNumberValidation","invalidFieldKeys","formErrorDataKey","_braintreeHostedForm","_overlay","_threeDSecureOptions","preloadPaypal","tokenizeCard","_getErrorsRequiredFields","requestData","_mapToCreditCard","verifyCard","challenge3DSVerification","newWindowFlow","supportsPopups","focusWindow","useraction","appendSessionId","processedPayment","initializeHostedForm","isInitializedHostedForm","deinitializeHostedForm","tokenizeHostedForm","tokenizeHostedFormForStoredCardVerification","verifyCardWithHostedForm","_present3DSChallenge","addFrame","removeFrame","cancelVerifyCard","verification","roundedAmount","challengeRequested","onLookupComplete","_data","countryCodeAlpha2","endpoint","_braintreePaymentProcessor","_isHostedFormInitialized","_is3dsEnabled","_deviceSessionId","_prepareHostedPaymentData","_preparePaymentData","commonPaymentData","_isSubmittingWithStoredCard","_isStoringNewCard","_shouldPerform3DSVerification","storedCreditCardNonce","three_ds_result","_credit","braintreeOptions","_loadPaypal","getOutstandingBalance","_formattedPayload","vaultPaymentInstrument","_initializeBraintreeVenmo","_braintreeVenmoCheckout","_braintreeVenmoTokenize","visaInitOptions","_cardinalClient","hostedForm","xid","payer_auth_request","_getBin","runBinProcess","_submitPayment","threeDsResult","getThreeDSecureData","_getOrderData","isCreditCardLike","CardinalInitializationType","CardinalEventType","CardinalValidatedAction","CardinalPaymentType","CardinalTriggerEvents","CardinalPaymentBrand","CardinalSignatureVerification","CardinalSignatureValidationErrors","_provider","_configurationToken","_sdk","now","_getClientSDK","SetupCompleted","ActionCode","ErrorNumber","ErrorDescription","setup","Init","jwt","binNumber","BinProcess","Status","orderData","Success","NoAction","Payment","ExtendedData","SignatureVerification","Yes","Failure","continueObject","AcsUrl","acs_url","Payload","merchant_data","partialOrder","_mapToPartialOrder","continue","CCA","transactionId","consumer","BillingAddress","_mapToCardinalAddress","Account","_mapToCardinalAccount","Email1","ShippingAddress","Consumer","OrderDetails","OrderNumber","Amount","CurrencyCode","OrderChannel","TransactionId","AccountNumber","ExpirationMonth","ExpirationYear","NameOnAccount","cardinalAddress","FirstName","LastName","Address1","City","State","PostalCode","CountryCode","Address2","Phone1","Cardinal","_getClientToken","_CBAMGPSScriptLoader","_sessionId","isTestModeFlagEnabled","_threeDSjs","isConfigured","wsVersion","newPaymentData","storeId","_initiateAuthentication","initiateAuthentication","msg","gatewayRecommendation","restApiResponse","authenticationStatus","_authenticatePayer","attempt","_resolve","authenticatePayer","cause","fullScreenRedirect","ThreeDS","ChasePayEventType","_wepayRiskClient","_walletEvent$","chasepay","walletButton","_chasePayClient","_getPayment","_displayWallet","_createOrder","logoContainer","insertBrandings","CancelCheckout","CompleteCheckout","_setSessionToken","showLoadingAnimation","getRiskToken","riskToken","paymentCryptogram","cryptogramId","eci","reqTokenId","expDate","accountNum","accountMask","extraData","AdditionalActionType","_processResponse","additionalActionRequired","OffsiteRedirect","_performRedirect","DOCUMENT_SUPPORTED_APMS","_createFormattedPayload","ccDocument","customerMobile","bic","iban","_clearpayScriptLoader","_clearpaySdk","_isCountrySupported","_redirectToClearpay","_getScriptUrl","PaReq","TermUrl","callback_url","MD","AuthenticationSourceStatus","_digitalRiverScriptLoader","_digitalRiverInitializeOptions","digitalriver","_getDigitalRiverInitializeOptions","_digitalRiverJS","_loadWidget","_unsubscribe","_digitalRiverCheckoutData","_submitVaultedInstrument","checkoutData","_isAuthenticateSourceAction","_authenticateSource","_loadSuccessResponse","readyForStorage","_getDigitalRiverJs","_getErrorMessage","_onSuccessResponse","_submitFormEvent","browserInfo","owner","reusable","billingAddressPayPal","_onReadyResponse","paymentMethodConfiguration","_mountComplianceSection","sellingEntity","onSubmitForm","disabledPaymentMethods","digitalRiverConfiguration","showSavePaymentAgreement","onReady","descriptiveError","createDropin","_digitalRiverDropComponent","authenticateSource","sourceId","source_id","sourceClientSecret","source_client_secret","authenticateSourceResponse","failed","authentication_not_required","confirm","complianceDiv","complianceOptions","classes","base","compliance","entity","drfooter","cssText","classList","add","DigitalRiver","_googlePayProviderProcessor","isThreeDSecureEnabled","_googlePayOptions","_buttonClickEventHandler","_handleButtonClickedEvent","_verifyCard","newPayment","processAdditionalAction","_braintreePresent3DSChallenge","requireRenewNonce","_encodeNonce","googlePayToken","processable","_isOffsiteRedirectResponse","_handleOffsiteRedirectResponse","supportedCountries","supportedCountriesRequiringStates","_klarnaScriptLoader","klarnaCredit","_klarnaCredit","_authorize","authorizationToken","client_token","_getUpdateSessionData","_mapToKlarnaAddress","_needsStateCode","klarnaAddress","street_address","family_name","street_address2","updateSessionData","authorize","res","approved","show_form","Credit","_klarnav2ScriptLoader","_klarnav2TokenUpdater","klarnaPayments","_klarnaPayments","_loadPaymentsWidget","klarnav2","updateClientToken","payment_method_category","Payments","_masterpassClient","_createMasterpassPayload","MolliePaymentMethodType","methodsNotAllowedWhenDigitalOrder","_mollieScriptLoader","mollie","controllers","each","controller","isCreditCard","shouldShowTSVHostedForm","_mountCardVerificationfields","_loadMollieJs","_mollieClient","_mountElements","disableButton","_loadPaymentMethodsAllowed","executeWithVaulted","executeWithCC","executeWithAPM","_cardHolderElement","_cardNumberElement","_verificationCodeElement","_expiryDateElement","_getMollieClient","createToken","shopper_locale","_getShopperLocale","creditcard","_getInitializeOptions","testmode","cardNumberId","cardCvcId","cardExpiryId","cardHolderId","mollieClient","createComponent","cartDigitalItems","paragraph","unsupportedMethodMessage","_isMollieWindow","Mollie","monerisOptions","profileId","_shouldShowTSVHostedForm","_executeWithVaulted","_executeWithCC","_windowEventListener","instrumentSettings","frameref","_monerisURL","_handleMonerisResponse","definedFields","monerisQueryParams","pmmsg","display_labels","enable_exp","enable_cvd","css_body","cssBody","css_textbox","cssTextbox","css_textbox_pan","cssTextboxCardNumber","css_textbox_exp","cssTextboxExpiryDate","css_textbox_cvd","cssTextboxCVV","css_input_label","cssInputLabel","pan_label","creditCardLabel","exp_label","expiryDateLabel","cvd_label","cvdLabel","queryString","monerisResponse","responseCode","dataKey","ActionTypes","OpyErrorType","isOpyPaymentMethod","widgetConfig","InvalidCart","_storefrontPaymentRequestSender","opy","_installWidget","nextAction","FORM_POST","formPost","formPostUrl","formFields","fieldName","fieldValue","append","decodeURI","widgetContainer","loadOpyWidget","Config","OpyRegion","AU_REGION_URL","SOURCES","AU","UK","US","OpenpayWidgets","_useRedirectFlow","paypalexpress","useRedirectFlow","_isInContextEnabled","_paypalSdk","closeFlow","_isAcknowledgedOrFinalized","initXO","startFlow","scriptSrc","SubStrategyType","PENDING_REDIRECT_PARAM","_isRedirecting","currentUrlHasRedirectingParam","isRedirecting","setRedirecting","setRedirectingParamOnUrl","removeRedirectingParamFromUrl","getCurrentUrl","replaceCurrentUrl","history","replaceState","currentUrl","updatedUrl","stringifyUrl","exclude","isAnyContinue","overSome","x","isString","isUndefined","availableMethods","_humanVerificationHandler","form_fields","redirectionState","RedirectionState","handleRedirect","humanVerificationHandler","available_methods","handleHumanVerification","humanVerification","_continueHandler","isSuccess","isContinue","isFailure","failureResponse","handleFailure","isError","createStepHandler","StepHandler","ContinueHandler","COMPLETED_PAYMENTS_KEY","_browserStorage","isCompleted","getCompletedPayments","setCompleted","completedPayments","setCompletedPayments","_subStrategyRegistry","_paymentResumer","browserStorage","_completedPayments","PPSDKCompletedPayments","subStrategy","resume","getPPSDKMethod","_subStrategy","getToken","cond","constant","CARD","NONE","stubTrue","UNSUPPORTED","_ppsdkStepHandler","humanVerificationCallback","_stepHandler","payment_method_id","createSubStrategyRegistry","stepHandler","SubStrategyRegistry","CardSubStrategy","NoneSubStrategy","auth_token","_prepareForReferredRegistration","_isThreeDSTwoExperimentOn","creq","SquareIntent","CardBrand","DigitalWalletType","squareOptions","_squareOptions","_syncPaymentMethod","createSquareForm","_paymentForm","_getFormOptions","_getPaymentForm","build","_getNonceInstrument","_getCountryCode","_deferredRequestNonce","requestCardNonce","deferred","cardNonceResponseReceived","deferredRequest","_getDeferredRequestNonce","digital_wallet_type","none","_handleWalletNonceResponse","_is3DSExperimentOn","_getVerificationDetails","verificationResults","createPaymentRequest","_paymentRequestPayload","paymentFormLoaded","_setPostalCode","unsupportedBrowserDetected","requestShippingAddress","requestBillingInfo","storeCountry","pending","setPostalCode","_getBillingContact","_getAmountAndCurrencyCode","CHARGE","_isSquareWindow","SqPaymentForm","bg","cs","da","el","et","fi","fil","he","hu","ja","ko","lt","lv","mt","nb","ro","ru","sk","sl","th","tr","vi","APM_REDIRECT","SOFORT","EPS","GRABPAY","BANCONTACT","GIROPAY","ALIPAY","KLARNA","_stripeScriptLoader","_isMounted","_isDeinitialize","_loadStripeElement","_state","PAYMENT","_stripeUPEClient","_executeWithAPM","_executeWithoutRedirect","_isCancellationError","stripeError","payment_intent","last_payment_error","_throwDisplayableStripeError","_processVaultedAdditionalAction","shopperLanguage","_loadStripeJs","colorIcon","stripeElement","billingDetails","NEVER","AUTO","wallets","applePay","confirmPayment","_mapStripePaymentData","paymentIntent","catchedConfirmError","stripePaymentData","retrievePaymentIntent","confirmCardPayment","_mapStripeAddress","IF_REQUIRED","confirmParams","payment_method_data","billing_details","return_url","IconStyle","StripeV3ErrorType","isIndividualCardElementOptions","individualCardElementOptions","cardNumberElementOptions","cardCvcElementOptions","cardExpiryElementOptions","AuthFailure","stripev3","useIndividualCardFields","_useIndividualCardFields","_stripeV3Client","_isCreditCard","_mountCardVerificationFields","_mountCardFields","_stripeElement","shouldSubmitOrderBeforeLoadingAPM","_confirmStripePayment","_buildPaymentPayload","_handleEmptyPaymentIntentError","_unmountElement","_isAuthError","_getStripeJs","confirmAlipayPayment","handleActions","confirmIdealPayment","confirmSepaDebitPayment","_getStripeCardElements","_getStripeElement","_mapStripeBillingDetails","createPaymentMethod","_stripeCardElements","zipCodeElementOptions","stripePaymentMethodType","cardNumberElement","cardExpiryElement","cardCvcElement","isAdditionalActionError","isThreeDSecureRequiredError","needsConfirm","_getPaymentToken","_riskClient","WePay","risk","generate_risk_token","get_risk_token","payloadWithToken","PAYMENT_CANNOT_CONTINUE","worldpay","_submitAdditionalAction","iframeHidden","messageEvent","_isValidJsonWithSessionId","removeEvent","SessionId","_createHiddenIframe","formId","inputBin","inputJWT","userAgent","match","srcdoc","outerHTML","str","InstrumentActionType","_instrumentRequestSender","loadInstruments","LoadInstrumentsRequested","session","_getSessionContext","_getCurrentAccessToken","_getValidAccessToken","currentToken","LoadInstrumentsSucceeded","LoadInstrumentsFailed","deleteInstrument","DeleteInstrumentRequested","DeleteInstrumentSucceeded","DeleteInstrumentFailed","_isValidVaultAccessToken","date","valueOf","isFuture","vaultAccessExpiry","newDate","getTime","setMinutes","getMinutes","getVaultAccessToken","shopperCurrency","isTransactional","transformResponse","vaultedInstruments","_transformVaultedInstruments","vaulted_instruments","transformErrorResponse","transformVaultAccessResponse","expires_at","_isPayPalInstrument","defaultInstrument","default_instrument","external_id","trustedShippingAddress","trusted_shipping_address","mapToPayPalInstrument","_isBankInstrument","mapToBankInstrument","last_4","expiryMonth","expiryYear","untrustedShippingCardVerificationMode","untrusted_shipping_address_card_verification_mode","mapToCardInstrument","method_type","_transformer","requestContext","_loadInstrumentsWithAddress","_loadInstruments","deleteShopperInstrument","errorResponse","loadInstrumentsWithAddress","PickupOptionActionType","_pickupOptionRequestSender","loadPickupOptions","apiQuery","_hydrateApiQuery","LoadPickupOptionsRequested","fetchPickupOptions","LoadPickupOptionsSucceeded","LoadPickupOptionsFailed","getConsignmentById","consignmentLineItems","cartItems","searchArea","ShippingCountryActionType","_shippingCountryRequestSender","LoadShippingCountriesRequested","LoadShippingCountriesSucceeded","LoadShippingCountriesFailed","ShippingStrategyActionType","UpdateAddressRequested","UpdateAddressSucceeded","UpdateAddressFailed","selectOption","SelectOptionRequested","SelectOptionSucceeded","SelectOptionFailed","mergedOptions","shippingStrategies","_shippingStrategyActionCreator","updateAddressRequestBody","editAddressButtonId","shouldShowLoadingSpinner","_shouldShowLoadingSpinner","onChangeShipping","availableCountries","getStripeState","getShippingAddressFields","shippingFields","spacingUnit","shippingPhoneField","allowedCountries","validation","SPLIT","stripeState","shippingAddressElement","isNewAddress","sendData","phoneFieldRequired","SignInEmailActionType","sendSignInEmail","emailRequest","SendSignInEmailRequested","SendSignInEmailSucceeded","SendSignInEmailFailed","withMemoizedCombiner","creator","combiner","pop","combinerArgs","createSelectorCreator","defaultMemoize","_messageCustomizer","_countryActionCreator","_couponActionCreator","_errorActionCreator","_giftCertificateActionCreator","_instrumentActionCreator","_pickupOptionActionCreator","_shippingCountryActionCreator","_signInEmailActionCreator","_subscriptionsActionCreator","_extensionActionCreator","isDevelopment","getShippingOptions","getSelectedShippingOption","getShippingCountries","getBillingCountries","getPaymentMethods","getSelectedPaymentMethod","getCoupons","getGiftCertificates","getSignInEmail","isPaymentDataSubmitted","getInstruments","getCustomerAccountFields","getBillingAddressFields","getFlashMessages","getPickupOptions","getUserExperienceSettings","getExtensions","getSelectShippingOptionError","isPending","isSelectingShippingOption","isCustomerStepPending","isShippingStepPending","isPaymentStepPending","isSubmittingOrder","createCheckoutStoreSelector","createCheckoutStoreErrorSelector","createCheckoutStoreStatusSelector","_errorTransformer","isCheckoutServiceError","_selectorsFactory","shippingConsignment","val","getCountries","getEmail","getInstrumentsByPaymentMethod","checkoutUserExperienceSettings","memoizeOne","getSelectOptionError","getUpdateShippingOptionError","getLoadCheckoutError","getLoadError","getUpdateCheckoutError","getUpdateError","getSubmitOrderError","getExecuteError","getFinalizeOrderError","getFinalizeError","getLoadOrderError","getLoadCartError","getLoadBillingCountriesError","countries","getLoadShippingCountriesError","shippingCountries","getLoadPaymentMethodsError","getLoadPaymentMethodError","getLoadMethodError","getInitializePaymentError","getInitializeError","getSignInError","getSignOutError","getInitializeCustomerError","getLoadShippingOptionsError","getContinueAsGuestError","getUpdateBillingAddressError","getUpdateSubscriptionsError","getUpdateShippingAddressError","getUpdateAddressError","getDeleteConsignmentError","getDeleteError","getUpdateConsignmentError","getCreateConsignmentsError","getCreateError","getInitializeShippingError","getApplyStoreCreditError","getApplyError","getApplyCouponError","getRemoveCouponError","getRemoveError","getApplyGiftCertificateError","getRemoveGiftCertificateError","getLoadInstrumentsError","getDeleteInstrumentError","getLoadConfigError","getSignInEmailError","signInEmail","getSendError","getCreateCustomerAccountError","getCreateAccountError","getCreateCustomerAddressError","getCreateAddressError","getPickupOptionsError","pickupOptions","getLoadExtensionsError","isSelectingOption","isUpdatingShippingOption","isInitializing","isSigningIn","isSigningOut","isExecutingPaymentMethodCheckout","isWidgetInteracting","isUpdatingAddress","isExecuting","isFinalizing","isExecutingSpamCheck","isLoadingCheckout","isUpdatingCheckout","isUpdating","isFinalizingOrder","isLoadingOrder","isLoadingCart","isLoadingBillingCountries","isLoadingShippingCountries","isLoadingPaymentMethods","isLoadingPaymentMethod","isLoadingMethod","isInitializingPayment","isInitializingCustomer","isInitializedCustomer","isLoadingShippingOptions","isUpdatingBillingAddress","isUpdatingSubscriptions","isCreatingCustomerAccount","isCreatingCustomerAddress","isContinuingAsGuest","isUpdatingShippingAddress","isUpdatingConsignment","isDeletingConsignment","isDeleting","isCreatingConsignments","isCreating","isInitializingShipping","isApplyingStoreCredit","isApplying","isApplyingCoupon","isRemovingCoupon","isRemoving","isApplyingGiftCertificate","isRemovingGiftCertificate","isLoadingInstruments","isDeletingInstrument","isLoadingConfig","isSendingSignInEmail","isSending","isLoadingPickupOptions","selectors","statuses","notifyState","_dispatch","loadCheckoutAction","formFieldsAction","loadConfigAction","finalizeOrderIfNeeded","deinitializePayment","loadBillingCountries","loadShippingCountries","loadBillingAddressFields","loadShippingAddressFields","initializeCustomer","deinitializeCustomer","signInEmailRequest","createCustomerAccount","createCustomerAddress","deinitializeShipping","assignItemsToAddress","unassignItemsToAddress","selectConsignmentShippingOption","initializeSpamProtection","executeSpamCheck","CheckoutService","_factoryMethods","mapFromInternalErrorResponse","mapFromStorefrontErrorResponse","factoryMethod","createError","_getType","_isStorefrontErrorResponseBody","_isInternalErrorResponseBody","internalType","storefrontErrorResponse","internalErrorResponse","omitDeep","predicate","clearErrorReducer","isClearErrorAction","objectA","objectB","isArrayEqual","isDateEqual","isRegExpEqual","keyFilter","keysA","keysB","isObjectEqual","currentValue","newValue","objectSet","DEFAULT_STATE","billingAddressReducer","combineReducers","dataReducer","composeReducers","errorsReducer","statusesReducer","reducer","arrayReplace","currentArray","newArray","matchObject","sameAsCurrentCount","sameAsNewCount","countSameAsReplaced","replacedValue","newItem","currentItem","objectMerge","currentObject","CheckoutButtonActionType","cartReducer","DEFAULT_DATA_STATE","initializedContainers","DEFAULT_ERROR_STATE","DEFAULT_STATUS_STATE","checkoutButtonReducer","InitializeButtonSucceeded","DeinitializeButtonSucceeded","InitializeButtonRequested","InitializeButtonFailed","DeinitializeButtonRequested","DeinitializeButtonFailed","configReducer","couponReducer","giftCertificateReducer","customerReducer","customerStrategyReducer","initializeErrors","initializeMethodId","deinitializeError","deinitializeMethodId","signInError","signInMethodId","signOutError","signOutMethodId","executePaymentMethodCheckoutError","executePaymentMethodCheckoutMethodId","widgetInteractionError","widgetInteractionMethodId","isDeinitializing","extensionReducer","formFieldsReducer","countryReducer","orderReducer","metaReducer","orderBillingAddressReducer","paymentReducer","paymentMethodReducer","array","defaultPredicate","findIndex","mergeOrPush","methodA","methodB","loadMethodId","loadMethodError","paymentStrategyReducer","initializeError","executeError","executeMethodId","finalizeError","finalizeMethodId","instrumentReducer","deleteError","failedInstrument","deletingInstrument","remoteCheckoutReducer","updateShippingOptionError","updateError","consignmentReducer","objectFlatten","parent","flattened","keyString","objectWithSortedKeys","sortedArray","current","pickupOptionReducer","sortedflattenedMeta","shippingCountryReducer","shippingStrategyReducer","updateAddressError","updateAddressMethodId","selectOptionError","selectOptionMethodId","signInEmailReducer","storeCreditReducer","subscriptionsReducer","checkoutReducer","createFreezeProxy","trap","proxy","iteratee","getPrototypeOf","traversePrototypeOf","charAt","deepFreeze","createProxy","barclays","authorizenet","elavon","checkoutcom","sagepay","cybersource","cybersourcev2","bnz","converge","orbital","paymetric","moneris","cba_mpgs","worldpayaccess","normalize","identity","createInternalCheckoutSelectorsFactory","getDeinitializeError","getOrderBillingAddress","getInternalPayment","getGatewayPayment","getHostedPayment","createBillingAddressSelector","continueAsGuestError","loadError","createCartSelector","createCartSelectorFactory","createCheckoutButtonSelector","createConfigSelector","filterType","flashMessages","formState","createConfigSelectorFactory","createCountrySelector","createCountrySelectorFactory","createCouponSelector","removeCouponError","applyCouponError","createCustomerSelector","createAddressError","isCreatingAddress","createCustomerStrategySelector","getExecutePaymentMethodCheckoutError","getWidgetInteractionError","createCustomerStrategySelectorFactory","createGiftCertificateSelector","removeGiftCertificateError","applyGiftCertificateError","createGiftCertificateSelectorFactory","createInstrumentSelector","paymentMethodKey","currentMethod","isMatch","supportedProvider","createInstrumentSelectorFactory","createFormSelector","selectedCountry","processField","itemtype","processCountry","subdivisions","requiresState","processProvince","hasPostalCodes","processsPostCode","createFormSelectorFactory","createPaymentMethodSelector","createPaymentMethodSelectorFactory","createPaymentStrategySelector","getWidgetInteractingError","createPaymentStrategySelectorFactory","createPickupOptionSelector","sortedFlattenedParams","createPickupOptionSelectorFactory","createRemoteCheckoutSelector","createShippingAddressSelector","shippingConsignments","createShippingCountrySelector","createShippingCountrySelectorFactory","createShippingStrategySelector","createShippingStrategySelectorFactory","createConsignmentSelector","addressA","addressB","loadShippingOptionsError","getUnassignedItems","assignedLineItemIds","itemIds","getItemAssignmentError","isAssigningItems","createConsignmentSelectorFactory","createCheckoutSelector","createCheckoutSelectorFactory","createOrderSelector","currentPayment","createOrderSelectorFactory","createOrderBillingAddressSelector","createPaymentSelector","internalPayment","MissingPaymentId","MissingPaymentStatus","MissingPaymentRedirectUrl","createStoreCreditSelector","applyError","createStoreCreditSelectorFactory","createSubscriptionsSelector","createSubscriptionsSelectorFactory","createSignInEmailSelector","sendError","createExtensionSelector","createExtensionSelectorFactory","checkoutButton","orderBillingAddress","remoteCheckout","shouldWarnMutation","createCheckoutStore","initialState","requestErrorFactory","actionTransformer","action$","createInternalCheckoutSelectors","createCheckoutService","checkoutVariantIdentificationToken","orderRequestSender","checkoutRequestSender","configActionCreator","subscriptionsActionCreator","formFieldsActionCreator","registryV2","customerRegistryV2","extensionActionCreator","ExtensionActionCreator","ExtensionRequestSender","remoteCheckoutRequestSender","remoteCheckoutActionCreator","paymentRequestTransformer","paymentRequestSender","braintreePaymentProcessor","braintreeHostedForm","overlay","createBraintreePaymentProcessor","checkoutValidator","paymentHumanVerificationHandler","paymentStrategyActionCreator","storefrontPaymentRequestSender","PPSDKStrategy","PaymentResumer","consignmentRequestSender","createShippingStrategyRegistry","isTerminalCacheKeyMap","_lastId","_map","maps","_usedMaps","maxSize","onExpire","getKey","_resolveMap","parentMap","usedCount","_generateMap","_removeLeastUsedMap","getUsedCount","isMatched","mapIndex","unshift","terminalMap","recentlyUsedMap","_removeMap","isRootCacheKeyMap","selectorDecorator","resolver","memoizedMethod","cachedValue","isPrivate","selectorMethodDecorator","_checkoutButton","getInitializeButtonError","getDeinitializeButtonError","CheckoutButtonErrorSelector","isInitializingButton","isDeinitializingButton","CheckoutButtonStatusSelector","createCheckoutButtonSelectors","_buttonStrategyActionCreator","initializeButton","containerIds","idPrefix","uniqueId","setUniqueElementId","deinitializeButton","CheckoutButtonInitializer","_registryV2","paymentMethodRequestParams","paymentMethodRequestOptions","isWithBuyNowFeatures","_amazonPayV2ConfigRequestSender","initializeAmazonButtonOptions","Cart","_getCheckoutCreationRequestConfig","_createBuyNowCart","_createCheckoutConfig","public_key","rest","payloadJSON","buyNowCart","fundingicons","layout","tagline","messagingContainerId","_renderPayPalComponents","_renderPayPalMessages","shouldProcessPayment","onAuthorizeError","validButtonStyle","isMessageContainerAvailable","Messages","onPaymentError","_buyNowCart","venmoButtonStyle","backgroundPosition","backgroundSize","backgroundImage","backgroundRepeat","cursor","minHeight","minWidth","braintreevenmo","_handleInitializationVenmoSuccess","_handleInitializationVenmoError","_renderVenmoButton","_removeVenmoContainer","buttonContainer","venmoButton","buyBowCart","removeAttribute","_handlePostForm","_getGooglePayClientOptions","paymentDataCallbacks","onPaymentDataChanged","callbackTrigger","INITIALIZE","newTransactionInfo","googlePayButton","ESTIMATED","callbackIntents","OFFER","_paypalScriptLoader","_host","fundingCreditOption","allowedSources","allowCredit","disallowedSources","Button","funding","allowed","disallowed","onAuthorize","paymentID","payerID","payerId","payerInfo","payer_info","buttonClassName","_requiresShipping","_buyNowInitializeOptions","_getRequestWithEmptyTotal","onpaymentmethodselected","_handlePaymentMethodSelected","completePaymentMethodSelection","BoltConnect","setupProductPageCheckout","addButtonContainer","boltButtonContainer","boltButtonObject","getBoltObjectData","domainUrl","getButtonHeight","buttonBorderRadius","getButtonBorderRadius","publishable_key","variant","border_radius","buttonSize","Small","Large","Medium","buttonShape","Pill","Rect","buyNowFlowCallbacks","renderMessages","paypalMessagesOptions","getValidVenmoButtonStyles","paypalExpressScriptLoader","loadPaypalSDK","paypalSDK","getStyle","CheckoutButtonNotInitialized","getPaymentData","createCheckoutButtonInitializer","checkoutButtonStrategyFactories","createCheckoutButtonStrategy","braintreeSdkCreator","amazonPayV2RequestSender","createCheckoutButtonRegistry","EmbeddedCheckoutEventType","NotEmbeddableErrorType","UnknownError","EmbeddedContentEventType","IS_COOKIE_ALLOWED_KEY","LAST_ALLOW_COOKIE_ATTEMPT_KEY","_iframeCreator","_messageListener","_messagePoster","_loadingIndicator","_storage","_location","_isAttached","CheckoutComplete","CheckoutError","CheckoutLoaded","onFrameLoad","FrameLoaded","onSignOut","SignedOut","_configureStyles","_allowCookie","_attemptLogin","createFrame","_retryAllowCookie","FrameError","iFrameResizer","StyleConfigured","encodeURIComponent","lastAttempt","MissingContent","EmbeddedCheckout","MissingContainer","allowPaymentRequest","_toResizableFrame","timeoutInterval","handleMessage","iframes","scrolling","sizeWidth","heightCalculationMethod","contentId","originalIframeResizer","STORAGE_PREFIX","embedCheckout","handleFrameLoadedEvent","hasAttribute","_untargetedMessagePoster","_messageHandlers","postComplete","_postMessage","postError","_transformError","postFrameError","untargeted","postFrameLoaded","postLoaded","postSignedOut","receiveStyles","handler","_notifyMessageHandlers","IframeEmbeddedCheckoutMessenger","NoopEmbeddedCheckoutMessenger","createEmbeddedCheckoutMessenger","parentWindow","parentOrigin","DEFAULT_LOCALE","KEY_PREFIX","_logger","_transformConfig","locales","_locales","_translations","_formatters","mapKeys","translationKey","_hasTranslations","translate","prefixedKey","messageFormat","compile","_transformData","defaultLocale","defaultTranslations","_flattenObject","fallbackTranslations","union","fallbackLocale","parentKey","resultKey","LanguageService","createLanguageService","currencySettings","symbolLocation","symbol","thousandsSeparator","decimalSeparator","parseInt","_symbolLocation","_symbol","_thousandsSeparator","_decimalSeparator","formattedNumber","_formatNumber","formattedCurrency","_formatCurrency","positiveAmount","abs","_toFixed","decimalAmount","parsedIntegerAmount","precision","_storeConfig","_customerFormatter","_storeFormatter","toCustomerCurrency","exchangeRate","toStoreCurrency","CurrencyService","createCurrencyService","isAnalyticsTrackerWindowGA","ga","sendGoogleAnalytics","nonInteraction","isPayloadSizeLimitReached","serializeAnalyticsEventPayload","acc","AnalyticStepId","ANALYTIC_STEPS","CUSTOMER","BILLING","checkoutService","analytics","checkoutSteps","_checkoutStarted","_completedSteps","_viewedSteps","_analyticStepOrder","trackCheckoutStarted","extraItemsData","track","getTrackingPayload","revenue","trackOrderComplete","isMissingOrdersExperimentEnabled","affiliation","products","product","trackStepViewed","stepId","getIdFromStep","hasStepViewed","trackViewed","backfill","trackStepCompleted","hasStepCompleted","trackCompleted","i","shippingMethod","getShopperCurrency","getPaymentMethodName","shippingMethodId","completedStepId","getStoreProfile","toShopperCurrency","getProducts","product_id","giftCertificateItems","physicalAndDigitalItems","itemAttributes","image_url","createStepTracker","stepTrackerConfig","AnalyticStepType","AnalyticStepOrder","bodlEvents","_emailEntryBegan","_shippingOptionsShown","setState","checkoutBegin","_getCommonCheckoutData","emitCheckoutBeginEvent","orderPurchased","channelId","emitOrderPurchasedEvent","event_id","channel_id","cart_value","coupon_codes","shipping_cost","line_items","_getProducts","stepCompleted","currentStep","_hasStepCompleted","_trackCompletedStep","customerEmailEntry","emit","customerSuggestionInit","customerSuggestionExecute","customerPaymentMethodExecuted","showShippingMethods","selectedPaymentMethod","paymentOption","commonData","emitPaymentDetailsProvidedEvent","clickPayButton","paymentRejected","paymentComplete","exitCheckout","_trackShippingStepCompleted","emitShippingDetailsProvidedEvent","shipping_method","base_price","sale_price","purchase_price","product_name","gift_certificate_id","gift_certificate_name","gift_certificate_theme","theme","variant_id","brand_name","category_names","flatten","retail_price","retailPrice","createBodlService","isBodlEnabled"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/checkout-sdk.umd.js b/dist/checkout-sdk.umd.js index ffc8a2878d..495d606e0f 100644 --- a/dist/checkout-sdk.umd.js +++ b/dist/checkout-sdk.umd.js @@ -1,3 +1,3 @@ /*! For license information please see checkout-sdk.umd.js.LICENSE.txt */ -!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.checkoutKit=e():t.checkoutKit=e()}(self,(()=>(()=>{var t={89538:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=d(n(66534)),o=d(n(43279)),a=d(n(86202)),s=d(n(98834)),u=d(n(43961)),c=d(n(11906));function d(t){return t&&t.__esModule?t:{default:t}}function l(t){return l="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},l(t)}function p(t,e){for(var n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;e.default={host:""}},56280:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.APPLICATION_JSON=void 0,e.APPLICATION_JSON="application/json"},44955:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var r=n(56280),i=n(99338),o={headers:{Accept:r.APPLICATION_JSON,"Content-Type":r.APPLICATION_JSON},method:i.GET};e.default=o},99338:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.POST=e.GET=e.DELETE=void 0,e.GET="GET",e.POST="POST",e.DELETE="DELETE"},92197:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(5099),n(38490),n(64668),n(16368),n(99023),n(40737),n(74035),n(10951),n(58443),n(34500),n(25959),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i,o=(i=n(66534))&&i.__esModule?i:{default:i},a=n(56280),s=n(60301);function u(t){return u="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},u(t)}function c(t,e){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:a.APPLICATION_JSON;return t&&(0,s.includes)(e,a.APPLICATION_JSON)?JSON.stringify(t):t}},{key:"fromResponse",value:function(t){var e=this.parseResponseHeaders(t.getAllResponseHeaders()),n=t.getResponseHeader("Content-Type"),r=t.status,i=t.statusText,o="response"in t?t.response:t.responseText;return o&&(0,s.includes)(n,a.APPLICATION_JSON)&&(o=JSON.parse(o)),{data:o,headers:e,status:r,statusText:i}}},{key:"parseResponseHeaders",value:function(t){return(t?t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/):[]).reduce((function(t,e){var n=e.split(":"),r=(n.shift()||"").trim();return r?(0,o.default)({},t,function(t,e,n){return(e=d(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}({},r.toLowerCase(),n.join(":").trim())):t}),{})}}],r=[{key:"create",value:function(){return new t}}],n&&c(e.prototype,n),r&&c(e,r),Object.defineProperty(e,"prototype",{writable:!1}),t}();e.default=l},48773:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function o(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=d(n(18712)),o=d(n(66534)),a=n(99338),s=d(n(44955)),u=d(n(92197)),c=d(n(48773));function d(t){return t&&t.__esModule?t:{default:t}}function l(t){return l="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},l(t)}function p(t,e){for(var n=0;n=200&&t.status<300}}])&&p(e.prototype,n),r&&p(e,r),Object.defineProperty(e,"prototype",{writable:!1}),t}();e.default=h},50630:(t,e,n)=>{"use strict";n(6550),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t,e){return!(!Array.isArray(t)&&"string"!=typeof t)&&-1!==t.indexOf(e)}},60301:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"includes",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(e,"isNil",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(e,"isObject",{enumerable:!0,get:function(){return o.default}}),Object.defineProperty(e,"omitEmptyStringAndNil",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(e,"omitNil",{enumerable:!0,get:function(){return s.default}}),Object.defineProperty(e,"omitProperty",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(e,"toNumber",{enumerable:!0,get:function(){return c.default}}),Object.defineProperty(e,"toSnakeCase",{enumerable:!0,get:function(){return d.default}}),Object.defineProperty(e,"toString",{enumerable:!0,get:function(){return l.default}});var r=p(n(50630)),i=p(n(65480)),o=p(n(63387)),a=p(n(91145)),s=p(n(75750)),u=p(n(66206)),c=p(n(30439)),d=p(n(27302)),l=p(n(78267));function p(t){return t&&t.__esModule?t:{default:t}}},57457:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return""===t}},32713:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return(0,r.default)(t)||(0,i.default)(t)};var r=o(n(57457)),i=o(n(65480));function o(t){return t&&t.__esModule?t:{default:t}}},65480:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return null==t}},63387:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}n(93942),n(70472),n(93270),n(38490),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return null!==t&&"object"===i(t)&&!Array.isArray(t)}},91145:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return(0,i.default)(t,r.default)};var r=o(n(32713)),i=o(n(66206));function o(t){return t&&t.__esModule?t:{default:t}}},75750:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return(0,i.default)(t,r.default)};var r=o(n(65480)),i=o(n(66206));function o(t){return t&&t.__esModule?t:{default:t}}},66206:(t,e,n)=>{"use strict";n(13722),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t,e){return(0,i.default)(t)?Object.keys(t).reduce((function(n,r){var i=t[r];return e(i)||(n[r]=i),n}),{}):t};var r,i=(r=n(63387))&&r.__esModule?r:{default:r}},30439:(t,e,n)=>{"use strict";n(83681),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return parseFloat(t)||0}},27302:(t,e,n)=>{"use strict";n(58443),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return"string"!=typeof t?t:t.replace(/([a-z\d])([A-Z]+)/g,"$1_$2").replace(/[-\s]+/g,"_").toLowerCase()}},78267:(t,e,n)=>{"use strict";n(99023),n(80226),n(40737),n(26667),Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return"string"==typeof t?t:"number"!=typeof t||Number.isNaN(t)?"":t.toString()}},36438:(t,e,n)=>{"use strict";e.e=function(t){return i.default.create(t)};var r,i=(r=n(89538))&&r.__esModule?r:{default:r}},98834:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=s(n(14735)),o=s(n(15859)),a=s(n(92239));function s(t){return t&&t.__esModule?t:{default:t}}function u(t){return u="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},u(t)}function c(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(13751),o=n(7969),a=u(n(14088)),s=u(n(92239));function u(t){return t&&t.__esModule?t:{default:t}}function c(t){return c="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},c(t)}function d(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e,n){return(e=u(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function s(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(34745),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(26667),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=l(n(66534)),o=n(60301),a=l(n(45860)),s=l(n(31146)),u=l(n(8006)),c=l(n(80720)),d=l(n(85064));function l(t){return t&&t.__esModule?t:{default:t}}function p(t){return p="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},p(t)}function h(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(26667),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.PAYPAL_COMMERCE_VENMO=e.PAYPAL_COMMERCE_CREDIT_CARDS=e.PAYPAL_COMMERCE_CREDIT=e.PAYPAL_COMMERCE_ALTERNATIVE_METHODS=e.PAYPAL_COMMERCE=e.BRAINTREE_VISACHECKOUT=e.BRAINTREE_PAYPAL_CREDIT=e.BRAINTREE_PAYPAL=e.BRAINTREE_LOCAL_METHODS=e.BRAINTREE_GOOGLEPAY=e.BRAINTREE_ACH=e.BRAINTREE=void 0,e.BRAINTREE="braintree",e.BRAINTREE_PAYPAL="braintreepaypal",e.BRAINTREE_PAYPAL_CREDIT="braintreepaypalcredit",e.BRAINTREE_VISACHECKOUT="braintreevisacheckout",e.BRAINTREE_LOCAL_METHODS="braintreelocalmethods",e.BRAINTREE_GOOGLEPAY="googlepaybraintree",e.BRAINTREE_ACH="braintreeach",e.PAYPAL_COMMERCE="paypalcommerce",e.PAYPAL_COMMERCE_ALTERNATIVE_METHODS="paypalcommercealternativemethods",e.PAYPAL_COMMERCE_CREDIT="paypalcommercecredit",e.PAYPAL_COMMERCE_CREDIT_CARDS="paypalcommercecreditcards",e.PAYPAL_COMMERCE_VENMO="paypalcommercevenmo"},80720:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(9257),o=n(86879);function a(t){return a="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},a(t)}function s(t,e){for(var n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.PPSDK_CREDIT_CARD=e.MULTI_OPTION=e.CREDIT_CARD=void 0,e.CREDIT_CARD="credit-card",e.MULTI_OPTION="multi-option",e.PPSDK_CREDIT_CARD="card"},86202:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=c(n(14735)),o=n(7969),a=c(n(86130)),s=c(n(22147)),u=c(n(92239));function c(t){return t&&t.__esModule?t:{default:t}}function d(t){return d="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},d(t)}function l(t,e){for(var n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.SDK=e.OFFLINE=e.HOSTED=e.API=void 0,e.API="PAYMENT_TYPE_API",e.HOSTED="PAYMENT_TYPE_HOSTED",e.OFFLINE="PAYMENT_TYPE_OFFLINE",e.SDK="PAYMENT_TYPE_SDK"},22147:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301),o=n(9257);function a(t){return a="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},a(t)}function s(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function o(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(26667),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(95412),n(16368),n(34745),n(99023),n(40737),n(26667),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301),o=c(n(43085)),a=c(n(11106)),s=c(n(47752)),u=c(n(58332));function c(t){return t&&t.__esModule?t:{default:t}}function d(t){return d="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},d(t)}function l(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=s(n(66534)),o=n(60301),a=s(n(80720));function s(t){return t&&t.__esModule?t:{default:t}}function u(t){return u="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},u(t)}function c(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(26667),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(95412),n(16368),n(34745),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301),o=c(n(45873)),a=c(n(43026)),s=c(n(70170)),u=c(n(23393));function c(t){return t&&t.__esModule?t:{default:t}}function d(t){return d="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},d(t)}function l(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i,o=n(60301),a=(i=n(80720))&&i.__esModule?i:{default:i};function s(t){return s="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},s(t)}function u(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n(60301);function o(t){return o="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},o(t)}function a(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(8962),n(38490),n(16368),n(99023),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=u(n(14735)),o=n(99338),a=u(n(25682)),s=n(68109);function u(t){return t&&t.__esModule?t:{default:t}}function c(t){return c="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},c(t)}function d(t,e){for(var n=0;n{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function i(t){return i="function"==typeof Symbol&&"symbol"==r(Symbol.iterator)?function(t){return r(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":r(t)},i(t)}function o(t,e){for(var n=0;n{"use strict";n(95412),Object.defineProperty(e,"__esModule",{value:!0}),e.mapToHeaders=function(){var t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).authToken;return(0,r.omitNil)({Authorization:t})},e.mapToInstrumentPayload=function(){var t,e,n,o,a=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},s=a.providerName,u=a.defaultInstrument,c=(0,r.omitNil)({name:s});return(0,r.omitNil)({provider:c,credit_card:(t=a,e=t.creditCard,n=void 0===e?{}:e,o=(0,r.omitNil)(n.threeDSecure),(0,r.omitNil)({cardholder_name:n.cardholderName,number:n.number,month:n.month,year:n.year,verification_code:n.verificationCode,issue_month:n.issueMonth,issue_year:n.issueYear,issue_number:n.issueNumber,track_data:n.trackData,is_manual_entry:n.isManualEntry,icc_data:n.iccData,fallback_reason:n.fallbackReason,is_contactless:n.isContactless,encrypted_pin_cryptogram:n.encryptedPinCryptogram,encrypted_pin_ksn:n.encryptedPinKsn,three_d_secure:o})),billing_address:i(a.billingAddress),default_instrument:u})},e.mapToTrustedShippingAddressPayload=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Array.isArray(t.shippingAddress)?(0,r.omitNil)({shipping_addresses:t.shippingAddress.map((function(t){return i(t)}))}):(0,r.omitNil)({shipping_address:i(t.shippingAddress)})};var r=n(60301);function i(){var t,e,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=(t=n.provinceCode,e=n.province,(0,r.omitNil)({code:t,name:e}));return(0,r.omitNil)({address_line_1:n.addressLine1,address_line_2:n.addressLine2,city:n.city,company:n.company,country_code:n.countryCode,email:n.email,first_name:n.firstName,last_name:n.lastName,phone:n.phone,postal_code:n.postCode,state:i})}},119:(t,e,n)=>{"use strict";n(13722),Object.defineProperty(e,"__esModule",{value:!0});var r=n(87275),i=n(10874);e.default=function(t,e){var n=(e||{}).equalityCheck,o=void 0===n?i:n;return function(e,n){return Object.keys(t).reduce((function(i,a){var s,u=t[a],c=e?e[a]:void 0,d=u(c,n);return o(c,d)&&i?i:r.assign({},i,((s={})[a]=d,s))}),e||{})}}},50538:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(51725),n(38490),n(95412),n(16516),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0});var i=n(61699),o=n(87275),a=n(10874);e.default=function(){for(var t=[],e=0;e{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(61699),i=n(87275);e.default=function(t,e,n){if("string"!=typeof t||""===t)throw new Error("`type` must be a string");return r.__assign({type:t},i.omitBy({payload:e,meta:n},(function(t){return void 0===t})))}},17372:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(119),i=n(58941);e.default=function(t,e,n){return"function"==typeof t?new i.default(t,e,n):new i.default(r.default(t,{equalityCheck:n&&n.equalityCheck}),e,n)}},13304:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(61699),i=n(10520);e.default=function(t,e,n){return r.__assign({},i.default(t,e,n),{error:!0})}},58941:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(51725),n(38490),n(95412),n(40737),n(83823),n(10951),n(71806),n(5193),Object.defineProperty(e,"__esModule",{value:!0});var i=n(61699),o=n(87275),a=n(57469),s=n(11065),u=n(10874),c=n(35580),d=n(35643),l=n(25151),p=n(32168),h=function(){function t(t,e,n){void 0===e&&(e={});var r=this;this._reducer=t,this._options=i.__assign({actionTransformer:l.default,equalityCheck:u,shouldWarnMutation:!0,stateTransformer:p.default},n),this._state$=new a.BehaviorSubject(this._options.stateTransformer(e)),this._notification$=new a.Subject,this._dispatchers={},this._dispatchQueue$=new a.Subject,this._errors={},this._dispatchQueue$.pipe(s.mergeMap((function(t){return t.pipe(s.concatMap((function(t){return t})))})),s.filter((function(t){return!!t.type})),s.scan((function(t,e){return r._transformStates(t,e)}),{state:e,transformedState:this._state$.getValue()}),s.distinctUntilChanged((function(t,e){var n=t.state,i=e.state;return r._options.equalityCheck(n,i)})),s.map((function(t){return t.transformedState}))).subscribe(this._state$),this.dispatch({type:"INIT"})}return t.prototype.dispatch=function(t,e){return d.default(t)?this._dispatchObservableAction(t,e):"function"==typeof t?this._dispatchThunkAction(t,e):this._dispatchAction(t)},t.prototype.getState=function(){return this._state$.getValue()},t.prototype.notifyState=function(){this._notification$.next(this.getState())},t.prototype.subscribe=function(t){for(var e=this,n=[],i=1;i0&&(u=u.pipe(s.distinctUntilChanged((function(t,n){return a.every((function(r){return e._options.equalityCheck(r(t),r(n))}))})))),o&&!1===o.initial&&(u=u.pipe(s.skip(1)));var c=[u.subscribe(t),this._notification$.subscribe(t)];return function(){return c.forEach((function(t){return t.unsubscribe()}))}},t.prototype._transformStates=function(t,e){try{var n=!1===this._options.shouldWarnMutation?this._reducer(t.state,e):c.default(this._reducer(t.state,e),{equalityCheck:this._options.equalityCheck,previousValue:t.state});return{state:n,transformedState:this._options.stateTransformer(n)}}catch(n){return this._getDispatchError(e.meta&&e.meta.queueId).next(n),{state:t.state,transformedState:t.transformedState}}},t.prototype._dispatchAction=function(t){return this._dispatchObservableAction(t.error?a.throwError(t):a.of(t))},t.prototype._dispatchObservableAction=function(t,e){var n=this;return void 0===e&&(e={}),new Promise((function(r,i){var u=n._getDispatchError(e.queueId),c=n._options.actionTransformer(a.from(t).pipe(s.map((function(t){return e.queueId?o.merge({},t,{meta:{queueId:e.queueId}}):t}))));n._getDispatcher(e.queueId).next(a.from(c).pipe(s.map((function(t,e){return 0===e&&u.pipe(s.first()).subscribe(i),t.error&&i(t.payload),t})),s.catchError((function(t){return i(t instanceof Error?t:t.payload),a.of(t)})),s.tap({complete:function(){r(n.getState())}})))}))},t.prototype._dispatchThunkAction=function(t,e){var n=this;return void 0===e&&(e={}),this._dispatchObservableAction(a.defer((function(){return t(n)})),e)},t.prototype._getDispatcher=function(t){return void 0===t&&(t="default"),this._dispatchers[t]||(this._dispatchers[t]=new a.Subject,this._dispatchQueue$.next(this._dispatchers[t])),this._dispatchers[t]},t.prototype._getDispatchError=function(t){return void 0===t&&(t="default"),this._errors[t]||(this._errors[t]=new a.Subject),this._errors[t]},t}();e.default=h},35580:(t,e,n)=>{"use strict";n(95412),n(33409),n(60678),n(97814),Object.defineProperty(e,"__esModule",{value:!0});var r=n(87275),i=n(10874);e.default=function t(e,n){try{var o=n||{},a=o.equalityCheck,s=void 0===a?i:a,u=o.previousValue,c=void 0===u?null:u;return s(e,c)&&Object.isFrozen(c)?c:Object.isFrozen(e)||!Array.isArray(e)&&!r.isPlainObject(e)?e:Array.isArray(e)?Object.freeze(e.map((function(e,n){return t(e,{equalityCheck:s,previousValue:Array.isArray(c)?c[n]:void 0})}))):Object.freeze(Object.getOwnPropertyNames(e).reduce((function(n,r){return n[r]=t(e[r],{equalityCheck:s,previousValue:c&&c.hasOwnProperty(r)?c[r]:void 0}),n}),{}))}catch(t){if(t instanceof TypeError)return e;throw t}}},45346:(t,e,n)=>{"use strict";n(58941).default;var r=n(119);e.UY=r.default;var i=n(50538);e.g0=i.default;var o=n(10520);e.PH=o.default;var a=n(17372);e.Mg=a.default;var s=n(13304);e.bR=s.default;var u=n(35580);e._A=u.default},35643:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return"function"==typeof t.subscribe||"function"==typeof t.then}},25151:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return t}},32168:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return t}},78545:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(11077),i=n(51243);e.default=function(t){var e=new r.default;return new i.default(e,t)}},11077:(t,e,n)=>{"use strict";n(13722),n(71806),Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(){}return t.prototype.build=function(t,e,n){var r=this,i=document.createElement("form");return i.style.display="none",i.setAttribute("action",t),i.setAttribute("method","POST"),i.setAttribute("target",n||"_top"),Object.keys(e).forEach((function(t){var n=e[t];i.appendChild(r._createInput(n,t))})),i},t.prototype._createInput=function(t,e){var n=document.createElement("input");return n.setAttribute("name",e),n.setAttribute("type","hidden"),n.setAttribute("value",t),n},t}();e.default=r},51243:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(73543),i=function(){function t(t,e){this._formBuilder=t,this._options=e}return t.prototype.postForm=function(t,e,n,r){var i=this._formBuilder.build(this._prependHost(t),e,r);window.addEventListener("unload",(function t(){window.removeEventListener("unload",t),n&&n()})),document.body.appendChild(i),i.submit(),document.body.removeChild(i)},t.prototype._prependHost=function(t){return this._options&&this._options.host&&!r.isAbsoluteUrl(t)?r.joinPaths(this._options.host,t):t},t}();e.default=i},13751:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(78545);e.createFormPoster=r.default;var i=n(51243);e.FormPoster=i.default},73543:(t,e,n)=>{"use strict";n(58443),Object.defineProperty(e,"__esModule",{value:!0}),e.isAbsoluteUrl=function(t){return/^https?:\/\//.test(t)},e.joinPaths=function(t,e){return t.replace(/\/$/,"")+"/"+e.replace(/^\//,"")}},65934:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.isTerminalCacheKeyMap=function(t){return t.hasOwnProperty("cacheKey")},e.isRootCacheKeyMap=function(t){return t.hasOwnProperty("parentMap")}},67959:(t,e,n)=>{"use strict";n(6550),n(95412),n(16516),n(32345),Object.defineProperty(e,"__esModule",{value:!0});var r=n(61699),i=n(87275),o=r.__importDefault(n(10874)),a=n(65934),s=function(){function t(t){this._lastId=0,this._map={maps:[]},this._usedMaps=[],this._options=r.__assign({isEqual:o.default,maxSize:0,onExpire:i.noop},t)}return t.prototype.getKey=function(){for(var t=[],e=0;e{"use strict";var r=n(78497);e.HP=r.default,e.qe=r.memoizeOne},78497:(t,e,n)=>{"use strict";n(38490),n(34897),n(40737),n(10951),n(5193),Object.defineProperty(e,"__esModule",{value:!0});var r=n(61699),i=r.__importDefault(n(84026)),o=r.__importDefault(n(10874)),a=r.__importDefault(n(67959));function s(t,e){var n=r.__assign({maxSize:0,isEqual:o.default},e),s=n.maxSize,u=n.isEqual,c=new Map,d=new a.default({isEqual:u,maxSize:s,onExpire:function(t){return c.delete(t)}}),l=i.default(t,(function(){for(var t=[],e=0;e{"use strict";n.d(e,{v:()=>i}),n(13722);var r=n(52163),i=function(){function t(){this._cache={}}return t.prototype.read=function(t,e){var n=this.getKey(t,e.params);return this._cache[n]||null},t.prototype.write=function(t,e,n){var r=this.getKey(t,e.params);this._cache[r]=n},t.prototype.getKey=function(t,e){return void 0===e&&(e={}),0===Object.keys(e).length?t:t+"?"+r.Pz(e)},t}()},78128:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s});var r=n(53028),i=n(70613),o=n(44169),a=n(73185);function s(t){return new a.Z(new o.Z,new i.Z,r,t)}},98215:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i});var r=n(88287);function i(t){return new r.Z(t)}},14121:(t,e,n)=>{"use strict";n.r(e),n.d(e,{RequestSender:()=>o.Z,Timeout:()=>a.Z,createRequestSender:()=>r.Z,createTimeout:()=>i.Z});var r=n(78128),i=n(98215),o=n(73185),a=n(88287)},16927:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function i(t){return!!t&&("object"===r(t)||"function"==typeof t)&&"function"==typeof t.then}n.d(e,{Z:()=>i}),n(93942),n(70472),n(93270),n(38490),n(40737),n(10951),n(5193)},70613:(t,e,n)=>{"use strict";n.d(e,{Z:()=>s}),n(64668),n(58443),n(34500),n(25959);var r=n(61699),i=n(75457),o=/application\/(\w+\+)?json/,a=/application\/x-www-form-urlencoded/;const s=function(){function t(){}return t.prototype.toRequestBody=function(t){var e=t.headers?this._getHeader(t.headers,"Content-Type"):"";if(t.body){if(o.test(e))return JSON.stringify(t.body);if(a.test(e))return(0,i.Z)(t.body)}return t.body},t.prototype.toResponse=function(t){var e=this._parseResponseHeaders(t.getAllResponseHeaders());return{body:this._parseResponseBody("response"in t?t.response:t.responseText,e),headers:e,status:t.status,statusText:t.statusText}},t.prototype._parseResponseBody=function(t,e){var n=this._getHeader(e,"Content-Type");return t&&o.test(n)?JSON.parse(t):t},t.prototype._parseResponseHeaders=function(t){return(t?t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/):[]).reduce((function(t,e){var n,i=e.split(":"),o=(i.shift()||"").trim();return o?(0,r.__assign)((0,r.__assign)({},t),((n={})[o.toLowerCase()]=i.join(":").trim(),n)):t}),{})},t.prototype._getHeader=function(t,e){return t&&e&&(t[e]||t[e.toLowerCase()])||""},t}()},44169:(t,e,n)=>{"use strict";n.d(e,{Z:()=>i}),n(51725),n(13722),n(71806);var r=n(52163);const i=function(){function t(){}return t.prototype.createRequest=function(t,e){var n=new XMLHttpRequest;return this._configureRequest(n,t,e),n},t.prototype._configureRequest=function(t,e,n){void 0===n&&(n={}),t.open(n.method||"GET",this._formatUrl(e,n.params,n.encodeParams),!0),n.headers&&this._configureRequestHeaders(t,n.headers),"boolean"==typeof n.credentials&&(t.withCredentials=n.credentials),"number"==typeof n.timeout&&(t.timeout=n.timeout)},t.prototype._configureRequestHeaders=function(t,e){Object.keys(e).filter((function(t){return null!==e[t]})).forEach((function(n){t.setRequestHeader(n,e[n])}))},t.prototype._formatUrl=function(t,e,n){return void 0===n&&(n=!0),e&&0!==Object.keys(e).length?t+"?"+r.Pz(e,{encode:n}):t},t}()},73185:(t,e,n)=>{"use strict";n.d(e,{Z:()=>c}),n(40737),n(83823),n(58443),n(34500);var r=n(61699),i=n(59947),o=n.n(i),a=n(90956),s=n(16927),u=n(88287);const c=function(){function t(t,e,n,r){void 0===r&&(r={}),this._requestFactory=t,this._payloadTransformer=e,this._cookie=n,this._options=r,this._cache=this._options.cache||new a.v}return t.prototype.sendRequest=function(t,e){var n=this,r=this._mergeDefaultOptions(t,e),i=this._getCachedRequest(t,r);if(i)return Promise.resolve(i);var o=this._requestFactory.createRequest(this._prependHost(t),r);return new Promise((function(e,i){var a=function(){var a=n._payloadTransformer.toResponse(o);a.status>=200&&a.status<300?(n._cacheRequest(t,r,a),e(a)):i(a)};o.onload=a,o.onerror=a,o.onabort=a,o.ontimeout=a,r.timeout instanceof u.Z&&(r.timeout.onComplete((function(){return o.abort()})),r.timeout.start()),(0,s.Z)(r.timeout)&&r.timeout.then((function(){return o.abort()})),o.send(n._payloadTransformer.toRequestBody(r))}))},t.prototype.get=function(t,e){return this.sendRequest(t,(0,r.__assign)((0,r.__assign)({},e),{method:"GET"}))},t.prototype.post=function(t,e){return this.sendRequest(t,(0,r.__assign)((0,r.__assign)({},e),{method:"POST"}))},t.prototype.put=function(t,e){return this.sendRequest(t,(0,r.__assign)((0,r.__assign)({},e),{method:"PUT"}))},t.prototype.patch=function(t,e){return this.sendRequest(t,(0,r.__assign)((0,r.__assign)({},e),{method:"PATCH"}))},t.prototype.delete=function(t,e){return this.sendRequest(t,(0,r.__assign)((0,r.__assign)({},e),{method:"DELETE"}))},t.prototype._mergeDefaultOptions=function(t,e){var n={credentials:!0,encodeParams:!0,headers:{Accept:"application/json, text/plain, */*"},method:"GET"},r=this._cookie.get("XSRF-TOKEN");return r&&n.headers&&!this._isAssetRequest(t,e)&&(n.headers["X-XSRF-TOKEN"]=r),e&&e.body&&n.headers&&(n.headers["Content-Type"]="application/json"),o()({},n,e)},t.prototype._prependHost=function(t){return!this._options.host||/^https?:\/\//.test(t)?t:this._options.host.replace(/\/$/,"")+"/"+t.replace(/^\//,"")},t.prototype._shouldCacheRequest=function(t){return"GET"===(t.method||"GET").toUpperCase()&&Boolean(t.cache)},t.prototype._getCachedRequest=function(t,e){return this._shouldCacheRequest(e)?this._cache.read(t,e):null},t.prototype._cacheRequest=function(t,e,n){this._shouldCacheRequest(e)&&this._cache.write(t,e,n)},t.prototype._isAssetRequest=function(t,e){return(!e||!e.method||"GET"===e.method.toUpperCase())&&/\.(png|gif|jpe?g|css|js|json|svg|html?)$/.test(t.split("?")[0])},t}()},88287:(t,e,n)=>{"use strict";n.d(e,{Z:()=>r}),n(40737),n(83823);const r=function(){function t(t){var e=this;this._delay=t,this._resolve=function(){},this._promise=new Promise((function(t){e._resolve=t}))}return t.prototype.onComplete=function(t){this._promise.then(t)},t.prototype.complete=function(){this._resolve(),this._timeoutToken&&window.clearTimeout(this._timeoutToken)},t.prototype.start=function(){var t=this;this._delay&&(this._timeoutToken=window.setTimeout((function(){return t.complete()}),this._delay))},t}()},75457:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}function i(t){return"object"!==r(t)||null===t?t:Object.keys(t).filter((function(e){return void 0!==t[e]})).map((function(e){var n=t[e];return"string"==typeof n?e+"="+encodeURIComponent(n):e+"="+encodeURIComponent(JSON.stringify(n)||"")})).join("&")}n.d(e,{Z:()=>i}),n(93942),n(70472),n(93270),n(51725),n(38490),n(64668),n(95412),n(13722),n(40737),n(10951),n(5193)},52163:(t,e,n)=>{"use strict";n(93942),n(70472),n(93270),n(88033),n(51725),n(6550),n(38490),n(64668),n(95412),n(16516),n(2934),n(99023),n(13722),n(40737),n(10951),n(58443),n(34500),n(25959),n(71806),n(5193);var r=n(29590),i=n(66534);n(99684);function o(t,e){return e.encode?e.strict?r(t):encodeURIComponent(t):t}e.Pz=function(t,e){!1===(e=i({encode:!0,strict:!0,arrayFormat:"none"},e)).sort&&(e.sort=function(){});var n=function(t){switch(t.arrayFormat){case"index":return function(e,n,r){return null===n?[o(e,t),"[",r,"]"].join(""):[o(e,t),"[",o(r,t),"]=",o(n,t)].join("")};case"bracket":return function(e,n){return null===n?o(e,t):[o(e,t),"[]=",o(n,t)].join("")};default:return function(e,n){return null===n?o(e,t):[o(e,t),"=",o(n,t)].join("")}}}(e);return t?Object.keys(t).sort(e.sort).map((function(r){var i=t[r];if(void 0===i)return"";if(null===i)return o(r,e);if(Array.isArray(i)){var a=[];return i.slice().forEach((function(t){void 0!==t&&a.push(n(r,t,a.length))})),a.join("&")}return o(r,e)+"="+o(i,e)})).filter((function(t){return t.length>0})).join("&"):""}},42372:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function t(){}return t.prototype.canSupportRel=function(t){var e=document.createElement("link");return!!(e.relList&&e.relList.supports&&e.relList.supports(t))},t}();e.default=n},30799:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(14121),i=n(42372),o=n(89379);e.default=function(){return new o.default(new i.default,r.createRequestSender())}},83116:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(14121),i=n(42372),o=n(41583);e.default=function(){return new o.default(new i.default,r.createRequestSender())}},57537:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=n(30799);e.default=function(){return r||(r=i.default()),r}},59136:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=n(83116);e.default=function(){return r||(r=i.default()),r}},56046:(t,e,n)=>{"use strict";n(89379).default;var r=n(30799);e.VD=r.default;var i=n(57537);e.Vr=i.default,n(41583).default,n(83116).default;var o=n(59136);e.TX=o.default},89379:(t,e,n)=>{"use strict";n(38490),n(95412),n(13722),n(40737),n(83823),n(10951),n(71806),n(5193),Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){this._browserSupport=t,this._requestSender=e,this._scripts={},this._preloadedScripts={}}return t.prototype.loadScript=function(t,e){var n=this;return this._scripts[t]||(this._scripts[t]=new Promise((function(r,i){var o=document.createElement("script"),a=e||{},s=a.async,u=void 0!==s&&s,c=a.attributes,d=void 0===c?{}:c;Object.keys(d).forEach((function(t){o.setAttribute(t,d[t])})),o.onload=function(){return r()},o.onreadystatechange=function(){return r()},o.onerror=function(e){delete n._scripts[t],i(e)},o.async=u,o.src=t,document.body.appendChild(o)}))),this._scripts[t]},t.prototype.loadScripts=function(t,e){var n=this;return Promise.all(t.map((function(t){return n.loadScript(t,e)}))).then((function(){}))},t.prototype.preloadScript=function(t,e){var n=this;return this._preloadedScripts[t]||(this._preloadedScripts[t]=new Promise((function(r,i){var o=(e||{}).prefetch,a=void 0!==o&&o?"prefetch":"preload";if(n._browserSupport.canSupportRel(a)){var s=document.createElement("link");s.as="script",s.rel=a,s.href=t,s.onload=function(){r()},s.onerror=function(){delete n._preloadedScripts[t],i()},document.head.appendChild(s)}else n._requestSender.get(t,{credentials:!1,headers:{Accept:"application/javascript"}}).then((function(){return r()})).catch(i)}))),this._preloadedScripts[t]},t.prototype.preloadScripts=function(t,e){var n=this;return Promise.all(t.map((function(t){return n.preloadScript(t,e)}))).then((function(){}))},t}();e.default=r},41583:(t,e,n)=>{"use strict";n(38490),n(95412),n(13722),n(40737),n(83823),n(10951),n(71806),n(5193),Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){this._browserSupport=t,this._requestSender=e,this._stylesheets={},this._preloadedStylesheets={}}return t.prototype.loadStylesheet=function(t,e){var n=this;return this._stylesheets[t]||(this._stylesheets[t]=new Promise((function(r,i){var o=document.createElement("link"),a=e||{},s=a.prepend,u=void 0!==s&&s,c=a.attributes,d=void 0===c?{}:c;Object.keys(d).forEach((function(t){o.setAttribute(t,d[t])})),o.onload=function(){return r()},o.onerror=function(e){delete n._stylesheets[t],i(e)},o.rel="stylesheet",o.href=t,u&&document.head.children[0]?document.head.insertBefore(o,document.head.children[0]):document.head.appendChild(o)}))),this._stylesheets[t]},t.prototype.loadStylesheets=function(t,e){var n=this;return Promise.all(t.map((function(t){return n.loadStylesheet(t,e)}))).then((function(){}))},t.prototype.preloadStylesheet=function(t,e){var n=this;return this._preloadedStylesheets[t]||(this._preloadedStylesheets[t]=new Promise((function(r,i){var o=(e||{}).prefetch,a=void 0!==o&&o,s=a?"prefetch":"preload";if(n._browserSupport.canSupportRel(s)){var u=document.createElement("link");u.as="style",u.rel=a?"prefetch":"preload",u.href=t,u.onload=function(){r()},u.onerror=function(e){delete n._preloadedStylesheets[t],i(e)},document.head.appendChild(u)}else n._requestSender.get(t,{credentials:!1,headers:{Accept:"text/css"}}).then((function(){return r()})).catch(i)}))),this._preloadedStylesheets[t]},t.prototype.preloadStylesheets=function(t,e){var n=this;return Promise.all(t.map((function(t){return n.preloadStylesheet(t,e)}))).then((function(){}))},t}();e.default=r},93816:(t,e,n)=>{"use strict";e.RN=void 0,n(52388),n(98588),n(48431),n(58606),n(26463),n(74147),n(32530),n(79169),n(32574),n(51356),n(26645),n(38661),n(32552),n(47040),n(3390),n(79089),n(71202),n(9698),n(46560),n(1467),n(13243),n(65740);var r=n(29218);e.RN=r,n(35228)},65740:(t,e,n)=>{"use strict";var r=n(52388),i=n(98588),o=n(26645);t.exports=function(){return r()||i()||o()}},52388:t=>{"use strict";t.exports=function(t){return t=t||window.navigator.userAgent,/Android/i.test(t)}},98588:t=>{"use strict";t.exports=function(t){return t=t||window.navigator.userAgent,/CrOS/i.test(t)}},48431:(t,e,n)=>{"use strict";n(6550);var r=n(32574),i=n(1467),o=n(58606),a=n(46560),s=n(13243);t.exports=function(t){return!(-1===(t=t||window.navigator.userAgent).indexOf("Chrome")&&-1===t.indexOf("CriOS")||r(t)||i(t)||o(t)||a(t)||s(t))}},58606:(t,e,n)=>{"use strict";n(6550),t.exports=function(t){return-1!==(t=t||window.navigator.userAgent).indexOf("DuckDuckGo/")}},32574:(t,e,n)=>{"use strict";n(6550),t.exports=function(t){return-1!==(t=t||window.navigator.userAgent).indexOf("Edge/")}},51356:t=>{"use strict";t.exports=function(t){return t=t||window.navigator.userAgent,/Firefox/i.test(t)}},26463:(t,e,n)=>{"use strict";n(6550);var r=n(79169);t.exports=function(t){return-1!==(t=t||window.navigator.userAgent).indexOf("MSIE")||r(t)}},32530:(t,e,n)=>{"use strict";n(6550),t.exports=function(t){return-1!==(t=t||window.navigator.userAgent).indexOf("MSIE 10")}},79169:(t,e,n)=>{"use strict";n(6550),t.exports=function(t){return-1!==(t=t||window.navigator.userAgent).indexOf("Trident/7")}},74147:(t,e,n)=>{"use strict";n(6550),t.exports=function(t){return-1!==(t=t||window.navigator.userAgent).indexOf("MSIE 9")}},38661:t=>{"use strict";t.exports=function(t){return t=t||window.navigator.userAgent,/FxiOS/i.test(t)}},32552:(t,e,n)=>{"use strict";var r=n(26645);t.exports=function(t){return t=t||window.navigator.userAgent,r(t)&&function(t){return/\bGSA\b/.test(t)}(t)}},47040:(t,e,n)=>{"use strict";n(6550);var r=n(26645),i=n(38661),o=/webkit/i;t.exports=function(t){return t=t||window.navigator.userAgent,r(t)&&function(t){return o.test(t)}(t)&&!function(t){return t.indexOf("CriOS")>-1}(t)&&!i(t)&&!function(t){return t.indexOf("FBAN")>-1}(t)}},3390:(t,e,n)=>{"use strict";var r=n(79089);t.exports=function(t,e){return e=void 0!==e?e:window.statusbar.visible,r(t)&&!e}},79089:(t,e,n)=>{"use strict";var r=n(26645),i=n(32552);t.exports=function(t){return t=t||window.navigator.userAgent,!!r(t)&&(!!i(t)||/.+AppleWebKit(?!.*Safari)/i.test(t))}},71202:(t,e,n)=>{"use strict";var r=n(79089);t.exports=function(t,e){return e=void 0!==e?e:window.statusbar.visible,r(t)&&e}},26645:t=>{"use strict";t.exports=function(t){return t=t||window.navigator.userAgent,/iPhone|iPod|iPad/i.test(t)}},9698:(t,e,n)=>{"use strict";var r=n(38661),i=n(51356);t.exports=function(t){return t=t||window.navigator.userAgent,r(t)||/iPhone|iPod|iPad|Mobile|Tablet/i.test(t)&&i(t)}},46560:(t,e,n)=>{"use strict";n(6550),t.exports=function(t){return-1!==(t=t||window.navigator.userAgent).indexOf("OPR/")||-1!==t.indexOf("Opera/")||-1!==t.indexOf("OPT/")}},1467:t=>{"use strict";t.exports=function(t){return t=t||window.navigator.userAgent,/SamsungBrowser/i.test(t)}},13243:(t,e,n)=>{"use strict";n(6550),t.exports=function(t){return-1!==(t=t||window.navigator.userAgent).indexOf("Silk/")}},35228:(t,e,n)=>{"use strict";n(50633),n(15483);var r=n(48431);t.exports=function(t){return t=t||window.navigator.userAgent,!!window.PaymentRequest&&(!r(t)||function(t){var e=t.match(/Chrome\/(\d+)\./);return!!e&&parseInt(e[1],10)>=61}(t))}},29218:(t,e,n)=>{"use strict";n(6550),n(50633),n(15483);var r=n(52388),i=n(38661),o=n(79089),a=n(48431),s=n(1467),u=n(58606);function c(t){return(t=t||window.navigator.userAgent).indexOf("Opera Mini")>-1}t.exports=function(t){return t=t||window.navigator.userAgent,!(o(t)||i(t)||function(t){return t=t||window.navigator.userAgent,!!r(t)&&/Version\/[\d.]+/i.test(t)&&!c(t)&&!u(t)}(t)||c(t)||function(t){var e=(t=t||window.navigator.userAgent).match(/CriOS\/(\d+)\./);return!!e&&parseInt(e[1],10)<48}(t)||function(t){return!a(t)&&!s(t)&&/samsung/i.test(t)}(t))}},67061:(t,e,n)=>{"use strict";t.exports={number:n(9428),expirationDate:n(10370),expirationMonth:n(86075),expirationYear:n(34005),cvv:n(56348),postalCode:n(46887),creditCardType:n(56897)}},9428:(t,e,n)=>{"use strict";n(58443);var r=n(54442),i=n(56897);function o(t,e,n){return{card:t,isPotentiallyValid:e,isValid:n}}t.exports=function(t,e){var n,a,s,u,c;if(e=e||{},"number"==typeof t&&(t=String(t)),"string"!=typeof t)return o(null,!1,!1);if(t=t.replace(/\-|\s/g,""),!/^\d*$/.test(t))return o(null,!1,!1);if(0===(n=i(t)).length)return o(null,!1,!1);if(1!==n.length)return o(null,!0,!1);if(a=n[0],e.maxLength&&t.length>e.maxLength)return o(a,!1,!1);for(s=a.type===i.types.UNIONPAY&&!0!==e.luhnValidateUnionPay||r(t),c=Math.max.apply(null,a.lengths),e.maxLength&&(c=Math.min(e.maxLength,c)),u=0;u{"use strict";function e(t,e){return{isValid:t,isPotentiallyValid:e}}t.exports=function(t,n){return n=(n=n||3)instanceof Array?n:[n],"string"!=typeof t?e(!1,!1):/^\d*$/.test(t)?function(t,e){for(var n=0;nfunction(t){for(var e=3,n=0;ne?t[n]:e;return e}(n)?e(!1,!1):e(!0,!0):e(!1,!1)}},10370:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(38490),n(40737),n(10951),n(58443),n(5193);var i=n(30443),o=n(86075),a=n(34005);function s(t,e,n,r){return{isValid:t,isPotentiallyValid:e,month:n,year:r}}t.exports=function(t,e){var n,u,c,d;if("string"==typeof t)t=t.replace(/^(\d\d) (\d\d(\d\d)?)$/,"$1/$2"),n=i(t);else{if(null===t||"object"!==r(t))return s(!1,!1,null,null);n={month:String(t.month),year:String(t.year)}}if(u=o(n.month),c=a(n.year,e),u.isValid){if(c.isCurrentYear)return s(d=u.isValidForThisYear,d,n.month,n.year);if(c.isValid)return s(!0,!0,n.month,n.year)}return u.isPotentiallyValid&&c.isPotentiallyValid?s(!1,!0,null,null):s(!1,!1,null,null)}},86075:(t,e,n)=>{"use strict";function r(t,e,n){return{isValid:t,isPotentiallyValid:e,isValidForThisYear:n||!1}}n(50633),n(58443),t.exports=function(t){var e,n,i=(new Date).getMonth()+1;return"string"!=typeof t?r(!1,!1):""===t.replace(/\s/g,"")||"0"===t?r(!1,!0):/^\d*$/.test(t)?(e=parseInt(t,10),isNaN(t)?r(!1,!1):r(n=e>0&&e<13,n,n&&e>=i)):r(!1,!1)}},34005:(t,e,n)=>{"use strict";n(16516),n(99023),n(50633),n(58443);function r(t,e,n){return{isValid:t,isPotentiallyValid:e,isCurrentYear:n||!1}}t.exports=function(t,e){var n,i,o,a,s;return e=e||19,"string"!=typeof t?r(!1,!1):""===t.replace(/\s/g,"")?r(!1,!0):/^\d*$/.test(t)?(i=t.length)<2?r(!1,!0):(n=(new Date).getFullYear(),3===i?r(!1,t.slice(0,2)===String(n).slice(0,2)):i>4?r(!1,!1):(t=parseInt(t,10),o=Number(String(n).substr(2,2)),2===i?(s=o===t,a=t>=o&&t<=o+e):4===i&&(s=n===t,a=t>=n&&t<=n+e),r(a,a,s))):r(!1,!1)}},16108:(t,e,n)=>{"use strict";n(40737),n(26667),t.exports=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},54442:(t,e,n)=>{"use strict";n(50633),t.exports=function(t){for(var e,n=0,r=!1,i=t.length-1;i>=0;)e=parseInt(t.charAt(i),10),r&&(e*=2)>9&&(e=e%10+1),r=!r,n+=e,i--;return n%10==0}},30443:(t,e,n)=>{"use strict";n(64668),n(72590),n(16516),n(99023),n(34500);var r=n(34005),i=n(16108);t.exports=function(t){var e,n,o,a,s;return/^\d{4}-\d{1,2}$/.test(t)?t=t.split("-").reverse():/\//.test(t)?t=t.split(/\s*\/\s*/g):/\s/.test(t)&&(t=t.split(/ +/g)),i(t)?{month:t[0]||"",year:t.slice(1).join()}:(o=t,n=0===(s=Number(o[0]))?2:s>1||1===s&&Number(o[1])>2?1:1===s?(a=o.substr(1),r(a).isPotentiallyValid?1:2):5===o.length?1:o.length>5?2:1,{month:e=t.substr(0,n),year:t.substr(e.length)})}},46887:t=>{"use strict";function e(t,e){return{isValid:t,isPotentiallyValid:e}}t.exports=function(t,n){var r;return r=(n=n||{}).minLength||3,"string"!=typeof t?e(!1,!1):t.length{"use strict";n(6550),n(16516),n(34500),n(25959),e.parse=function(t,e){if("string"!=typeof t)throw new TypeError("argument str must be a string");for(var n={},i=e||{},a=t.split(o),u=i.decode||r,c=0;c{"use strict";n(6550),n(95412),n(32345),n(13722),n(71806);var r,i=n(18906),o=n(80826),a=n(16538),s=n(76754),u=n(25578),c={},d={VISA:"visa",MASTERCARD:"mastercard",AMERICAN_EXPRESS:"american-express",DINERS_CLUB:"diners-club",DISCOVER:"discover",JCB:"jcb",UNIONPAY:"unionpay",MAESTRO:"maestro",ELO:"elo",MIR:"mir",HIPER:"hiper",HIPERCARD:"hipercard"},l=[d.VISA,d.MASTERCARD,d.AMERICAN_EXPRESS,d.DINERS_CLUB,d.DISCOVER,d.JCB,d.UNIONPAY,d.MAESTRO,d.ELO,d.MIR,d.HIPER,d.HIPERCARD];function p(t){return c[t]||i[t]}function h(t,e){var n=r.indexOf(t);if(!e&&-1===n)throw new Error('"'+t+'" is not a supported card type.');return n}function f(t){var e,n=[];return s(t)?0===t.length?r.map((function(t){return o(p(t))})):(r.forEach((function(e){var r=p(e);u(t,r,n)})),(e=a(n))?[e]:n):[]}r=o(l),f.getTypeInfo=function(t){return o(p(t))},f.removeCard=function(t){var e=h(t);r.splice(e,1)},f.addCard=function(t){var e=h(t.type,!0);c[t.type]=t,-1===e&&r.push(t.type)},f.updateCard=function(t,e){var n,r=c[t]||i[t];if(!r)throw new Error('"'+t+'" is not a recognized type. Use `addCard` instead.');if(e.type&&r.type!==e.type)throw new Error("Cannot overwrite type parameter.");n=o(r,!0),Object.keys(n).forEach((function(t){e[t]&&(n[t]=e[t])})),c[n.type]=n},f.changeOrder=function(t,e){var n=h(t);r.splice(n,1),r.splice(e,0,t)},f.resetModifications=function(){r=o(l),c={}},f.types=d,t.exports=f},25578:(t,e,n)=>{"use strict";var r=n(80826),i=n(90013);t.exports=function(t,e,n){var o,a,s,u;for(o=0;o=s&&(u.matchStrength=s),n.push(u);break}}},18906:t=>{"use strict";t.exports={visa:{niceType:"Visa",type:"visa",patterns:[4],gaps:[4,8,12],lengths:[16,18,19],code:{name:"CVV",size:3}},mastercard:{niceType:"Mastercard",type:"mastercard",patterns:[[51,55],[2221,2229],[223,229],[23,26],[270,271],2720],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},"american-express":{niceType:"American Express",type:"american-express",patterns:[34,37],gaps:[4,10],lengths:[15],code:{name:"CID",size:4}},"diners-club":{niceType:"Diners Club",type:"diners-club",patterns:[[300,305],36,38,39],gaps:[4,10],lengths:[14,16,19],code:{name:"CVV",size:3}},discover:{niceType:"Discover",type:"discover",patterns:[6011,[644,649],65],gaps:[4,8,12],lengths:[16,19],code:{name:"CID",size:3}},jcb:{niceType:"JCB",type:"jcb",patterns:[2131,1800,[3528,3589]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVV",size:3}},unionpay:{niceType:"UnionPay",type:"unionpay",patterns:[620,[624,626],[62100,62182],[62184,62187],[62185,62197],[62200,62205],[622010,622999],622018,[622019,622999],[62207,62209],[622126,622925],[623,626],6270,6272,6276,[627700,627779],[627781,627799],[6282,6289],6291,6292,810,[8110,8131],[8132,8151],[8152,8163],[8164,8171]],gaps:[4,8,12],lengths:[14,15,16,17,18,19],code:{name:"CVN",size:3}},maestro:{niceType:"Maestro",type:"maestro",patterns:[493698,[5e5,506698],[506779,508999],[56,59],63,67,6],gaps:[4,8,12],lengths:[12,13,14,15,16,17,18,19],code:{name:"CVC",size:3}},elo:{niceType:"Elo",type:"elo",patterns:[401178,401179,438935,457631,457632,431274,451416,457393,504175,[506699,506778],[509e3,509999],627780,636297,636368,[650031,650033],[650035,650051],[650405,650439],[650485,650538],[650541,650598],[650700,650718],[650720,650727],[650901,650978],[651652,651679],[655e3,655019],[655021,655058]],gaps:[4,8,12],lengths:[16],code:{name:"CVE",size:3}},mir:{niceType:"Mir",type:"mir",patterns:[[2200,2204]],gaps:[4,8,12],lengths:[16,17,18,19],code:{name:"CVP2",size:3}},hiper:{niceType:"Hiper",type:"hiper",patterns:[637095,637568,637599,637609,637612],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}},hipercard:{niceType:"Hipercard",type:"hipercard",patterns:[606282],gaps:[4,8,12],lengths:[16],code:{name:"CVC",size:3}}}},80826:t=>{"use strict";t.exports=function(t){return t?JSON.parse(JSON.stringify(t)):null}},16538:(t,e,n)=>{"use strict";n(51725),t.exports=function(t){if(function(t){var e=t.filter((function(t){return t.matchStrength})).length;return e>0&&e===t.length}(t))return t.reduce((function(t,e){return t?t.matchStrength{"use strict";t.exports=function(t){return"string"==typeof t||t instanceof String}},90013:(t,e,n)=>{"use strict";n(50633),t.exports=function(t,e){return Array.isArray(e)?function(t,e,n){var r=String(e).length,i=t.substr(0,r),o=parseInt(i,10);return e=parseInt(String(e).substr(0,i.length),10),n=parseInt(String(n).substr(0,i.length),10),o>=e&&o<=n}(t,e[0],e[1]):function(t,e){return(e=String(e)).substring(0,t.length)===t.substring(0,e.length)}(t,e)}},99684:(t,e,n)=>{"use strict";function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(88033),n(38490),n(64668),n(16516),n(13722),n(40737),n(84868),n(26667),n(10951),n(15483),n(58443),n(5193);var i="%[a-f0-9]{2}",o=new RegExp("("+i+")|([^%]+?)","gi"),a=new RegExp("("+i+")+","gi");function s(t,e){try{return[decodeURIComponent(t.join(""))]}catch(t){}if(1===t.length)return t;e=e||1;var n=t.slice(0,e),r=t.slice(e);return Array.prototype.concat.call([],s(n),s(r))}function u(t){try{return decodeURIComponent(t)}catch(r){for(var e=t.match(o)||[],n=1;n{"use strict";n(93942);var r=n(59788),i=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable;function a(t,e,n){var o=e[n];if(null!=o){if(i.call(t,n)&&(void 0===t[n]||null===t[n]))throw new TypeError("Cannot convert undefined or null to object ("+n+")");i.call(t,n)&&r(o)?t[n]=s(Object(t[n]),e[n]):t[n]=o}}function s(t,e){if(t===e)return t;for(var n in e=Object(e))i.call(e,n)&&a(t,e,n);if(Object.getOwnPropertySymbols)for(var r=Object.getOwnPropertySymbols(e),s=0;s{"use strict";n(6550),n(13722),t.exports=function(t,e){for(var n={},r=Object.keys(t),i=Array.isArray(e),o=0;o{"use strict";t.exports=n(53312)},41587:(t,e,n)=>{function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}n(93942),n(70472),n(93270),n(6550),n(38490),n(95412),n(16516),n(32345),n(99023),n(40737),n(50633),n(10951),n(34500),n(71806),n(5193),function(e){"use strict";if("undefined"!=typeof window){var n=!0,i=10,o="",a=0,s="",u=null,c="",d=!1,l={resize:1,click:1},p=128,h=!0,f=1,y="bodyOffset",m=y,_=!0,g="",v={},b=32,w=null,S=!1,C="[iFrameSizer]",I=C.length,P="",E={max:1,min:1,bodyScroll:1,documentElementScroll:1},A="child",O=!0,k=window.parent,T="*",x=0,M=!1,R=null,N=16,D=1,z="scroll",L=z,F=window,U=function(){ct("MessageCallback function not defined")},B=function(){},j=function(){},q={height:function(){return ct("Custom height calculation function not defined"),document.documentElement.offsetHeight},width:function(){return ct("Custom width calculation function not defined"),document.body.scrollWidth}},V={},H=!1;try{var G=Object.create({},{passive:{get:function(){H=!0}},once:{get:function(){}}});window.addEventListener("test",rt,G),window.removeEventListener("test",rt,G)}catch(t){}var Y,W,K,J,Z,$,Q,X=Date.now||function(){return(new Date).getTime()},tt={bodyOffset:function(){return document.body.offsetHeight+bt("marginTop")+bt("marginBottom")},offset:function(){return tt.bodyOffset()},bodyScroll:function(){return document.body.scrollHeight},custom:function(){return q.height()},documentElementOffset:function(){return document.documentElement.offsetHeight},documentElementScroll:function(){return document.documentElement.scrollHeight},max:function(){return Math.max.apply(null,St(tt))},min:function(){return Math.min.apply(null,St(tt))},grow:function(){return tt.max()},lowestElement:function(){return Math.max(tt.bodyOffset()||tt.documentElementOffset(),wt("bottom",It()))},taggedElement:function(){return Ct("bottom","data-iframe-height")}},et={bodyScroll:function(){return document.body.scrollWidth},bodyOffset:function(){return document.body.offsetWidth},custom:function(){return q.width()},documentElementScroll:function(){return document.documentElement.scrollWidth},documentElementOffset:function(){return document.documentElement.offsetWidth},scroll:function(){return Math.max(et.bodyScroll(),et.documentElementScroll())},max:function(){return Math.max.apply(null,St(et))},min:function(){return Math.min.apply(null,St(et))},rightMostElement:function(){return wt("right",It())},taggedElement:function(){return Ct("right","data-iframe-width")}},nt=(Y=Pt,Z=null,$=0,Q=function(){$=X(),Z=null,J=Y.apply(W,K),Z||(W=K=null)},function(){var t=X();$||($=t);var e=N-(t-$);return W=this,K=arguments,e<=0||e>N?(Z&&(clearTimeout(Z),Z=null),$=t,J=Y.apply(W,K),Z||(W=K=null)):Z||(Z=setTimeout(Q,e)),J});it(window,"message",xt),it(window,"readystatechange",Mt),Mt()}function rt(){}function it(t,e,n,r){"addEventListener"in window?t.addEventListener(e,n,!!H&&(r||{})):"attachEvent"in window&&t.attachEvent("on"+e,n)}function ot(t,e,n){"removeEventListener"in window?t.removeEventListener(e,n,!1):"detachEvent"in window&&t.detachEvent("on"+e,n)}function at(t){return t.charAt(0).toUpperCase()+t.slice(1)}function st(t){return C+"["+P+"] "+t}function ut(t){S&&"object"===r(window.console)&&console.log(st(t))}function ct(t){"object"===r(window.console)&&console.warn(st(t))}function dt(){var t,r;!function(){function t(t){return"true"===t}var r=g.substr(I).split(":");P=r[0],a=e!==r[1]?Number(r[1]):a,d=e!==r[2]?t(r[2]):d,S=e!==r[3]?t(r[3]):S,b=e!==r[4]?Number(r[4]):b,n=e!==r[6]?t(r[6]):n,s=r[7],m=e!==r[8]?r[8]:m,o=r[9],c=r[10],x=e!==r[11]?Number(r[11]):x,v.enable=e!==r[12]&&t(r[12]),A=e!==r[13]?r[13]:A,L=e!==r[14]?r[14]:L}(),ut("Initialising iFrame ("+location.href+")"),function(){function t(t,e){return"function"==typeof t&&(ut("Setup custom "+e+"CalcMethod"),q[e]=t,t="custom"),t}var e;"iFrameResizer"in window&&Object===window.iFrameResizer.constructor&&(e=window.iFrameResizer,ut("Reading data from page: "+JSON.stringify(e)),U="messageCallback"in e?e.messageCallback:U,B="readyCallback"in e?e.readyCallback:B,T="targetOrigin"in e?e.targetOrigin:T,m="heightCalculationMethod"in e?e.heightCalculationMethod:m,L="widthCalculationMethod"in e?e.widthCalculationMethod:L,m=t(m,"height"),L=t(L,"width")),ut("TargetOrigin for parent set to: "+T)}(),e===s&&(s=a+"px"),lt("margin",(-1!==(r=s).indexOf("-")&&(ct("Negative CSS value ignored for margin"),r=""),r)),lt("background",o),lt("padding",c),(t=document.createElement("div")).style.clear="both",t.style.display="block",document.body.appendChild(t),yt(),mt(),document.documentElement.style.height="",document.body.style.height="",ut('HTML & body height set to "auto"'),ut("Enable public methods"),F.parentIFrame={autoResize:function(t){return!0===t&&!1===n?(n=!0,_t()):!1===t&&!0===n&&(n=!1,gt()),n},close:function(){Tt(0,0,"close"),ut("Disable outgoing messages"),O=!1,ut("Remove event listener: Message"),ot(window,"message",xt),!0===n&>()},getId:function(){return P},getPageInfo:function(t){"function"==typeof t?(j=t,Tt(0,0,"pageInfo")):(j=function(){},Tt(0,0,"pageInfoStop"))},moveToAnchor:function(t){v.findTarget(t)},reset:function(){kt("parentIFrame.reset")},scrollTo:function(t,e){Tt(e,t,"scrollTo")},scrollToOffset:function(t,e){Tt(e,t,"scrollToOffset")},sendMessage:function(t,e){Tt(0,0,"message",JSON.stringify(t),e)},setHeightCalculationMethod:function(t){m=t,yt()},setWidthCalculationMethod:function(t){L=t,mt()},setTargetOrigin:function(t){ut("Set targetOrigin: "+t),T=t},size:function(t,e){Et("size","parentIFrame.size("+(t||"")+(e?","+e:"")+")",t,e)}},_t(),v=function(){function t(t){var n=t.getBoundingClientRect(),r={x:window.pageXOffset!==e?window.pageXOffset:document.documentElement.scrollLeft,y:window.pageYOffset!==e?window.pageYOffset:document.documentElement.scrollTop};return{x:parseInt(n.left,10)+parseInt(r.x,10),y:parseInt(n.top,10)+parseInt(r.y,10)}}function n(n){var r=n.split("#")[1]||n,i=decodeURIComponent(r),o=document.getElementById(i)||document.getElementsByName(i)[0];e!==o?function(e){var n=t(e);ut("Moving to in page link (#"+r+") at x: "+n.x+" y: "+n.y),Tt(n.y,n.x,"scrollToOffset")}(o):(ut("In page link (#"+r+") not found in iFrame, so sending to parent"),Tt(0,0,"inPageLink","#"+r))}function r(){""!==location.hash&&"#"!==location.hash&&n(location.href)}return v.enable?Array.prototype.forEach&&document.querySelectorAll?(ut("Setting up location.hash handlers"),Array.prototype.forEach.call(document.querySelectorAll('a[href^="#"]'),(function(t){"#"!==t.getAttribute("href")&&it(t,"click",(function(t){t.preventDefault(),n(this.getAttribute("href"))}))})),it(window,"hashchange",r),setTimeout(r,p)):ct("In page linking not fully supported in this browser! (See README.md for IE8 workaround)"):ut("In page linking not enabled"),{findTarget:n}}(),Et("init","Init message from host page"),B()}function lt(t,n){e!==n&&""!==n&&"null"!==n&&(document.body.style[t]=n,ut("Body "+t+' set to "'+n+'"'))}function pt(t){var e={add:function(e){function n(){Et(t.eventName,t.eventType)}V[e]=n,it(window,e,n,{passive:!0})},remove:function(t){var e=V[t];delete V[t],ot(window,t,e)}};t.eventNames&&Array.prototype.map?(t.eventName=t.eventNames[0],t.eventNames.map(e[t.method])):e[t.method](t.eventName),ut(at(t.method)+" event listener: "+t.eventType)}function ht(t){pt({method:t,eventType:"Animation Start",eventNames:["animationstart","webkitAnimationStart"]}),pt({method:t,eventType:"Animation Iteration",eventNames:["animationiteration","webkitAnimationIteration"]}),pt({method:t,eventType:"Animation End",eventNames:["animationend","webkitAnimationEnd"]}),pt({method:t,eventType:"Input",eventName:"input"}),pt({method:t,eventType:"Mouse Up",eventName:"mouseup"}),pt({method:t,eventType:"Mouse Down",eventName:"mousedown"}),pt({method:t,eventType:"Orientation Change",eventName:"orientationchange"}),pt({method:t,eventType:"Print",eventName:["afterprint","beforeprint"]}),pt({method:t,eventType:"Ready State Change",eventName:"readystatechange"}),pt({method:t,eventType:"Touch Start",eventName:"touchstart"}),pt({method:t,eventType:"Touch End",eventName:"touchend"}),pt({method:t,eventType:"Touch Cancel",eventName:"touchcancel"}),pt({method:t,eventType:"Transition Start",eventNames:["transitionstart","webkitTransitionStart","MSTransitionStart","oTransitionStart","otransitionstart"]}),pt({method:t,eventType:"Transition Iteration",eventNames:["transitioniteration","webkitTransitionIteration","MSTransitionIteration","oTransitionIteration","otransitioniteration"]}),pt({method:t,eventType:"Transition End",eventNames:["transitionend","webkitTransitionEnd","MSTransitionEnd","oTransitionEnd","otransitionend"]}),"child"===A&&pt({method:t,eventType:"IFrame Resized",eventName:"resize"})}function ft(t,e,n,r){return e!==t&&(t in n||(ct(t+" is not a valid option for "+r+"CalculationMethod."),t=e),ut(r+' calculation method set to "'+t+'"')),t}function yt(){m=ft(m,y,tt,"height")}function mt(){L=ft(L,z,et,"width")}function _t(){var t;!0===n?(ht("add"),t=0>b,window.MutationObserver||window.WebKitMutationObserver?t?vt():u=function(){function t(t){function e(t){!1===t.complete&&(ut("Attach listeners to "+t.src),t.addEventListener("load",i,!1),t.addEventListener("error",o,!1),s.push(t))}"attributes"===t.type&&"src"===t.attributeName?e(t.target):"childList"===t.type&&Array.prototype.forEach.call(t.target.querySelectorAll("img"),e)}function n(t){ut("Remove listeners from "+t.src),t.removeEventListener("load",i,!1),t.removeEventListener("error",o,!1),function(t){s.splice(s.indexOf(t),1)}(t)}function r(t,r,i){n(t.target),Et(r,i+": "+t.target.src,e,e)}function i(t){r(t,"imageLoad","Image loaded")}function o(t){r(t,"imageLoadFailed","Image load failed")}function a(e){Et("mutationObserver","mutationObserver: "+e[0].target+" "+e[0].type),e.forEach(t)}var s=[],u=window.MutationObserver||window.WebKitMutationObserver,c=function(){var t=document.querySelector("body");return c=new u(a),ut("Create body MutationObserver"),c.observe(t,{attributes:!0,attributeOldValue:!1,characterData:!0,characterDataOldValue:!1,childList:!0,subtree:!0}),c}();return{disconnect:function(){"disconnect"in c&&(ut("Disconnect body MutationObserver"),c.disconnect(),s.forEach(n))}}}():(ut("MutationObserver not supported in this browser!"),vt())):ut("Auto Resize disabled")}function gt(){ht("remove"),null!==u&&u.disconnect(),clearInterval(w)}function vt(){0!==b&&(ut("setInterval: "+b+"ms"),w=setInterval((function(){Et("interval","setInterval: "+b)}),Math.abs(b)))}function bt(t,e){var n=0;return e=e||document.body,n="defaultView"in document&&"getComputedStyle"in document.defaultView?null!==(n=document.defaultView.getComputedStyle(e,null))?n[t]:0:function(t){if(/^\d+(px)?$/i.test(t))return parseInt(t,i);var n=e.style.left,r=e.runtimeStyle.left;return e.runtimeStyle.left=e.currentStyle.left,e.style.left=t||0,t=e.style.pixelLeft,e.style.left=n,e.runtimeStyle.left=r,t}(e.currentStyle[t]),parseInt(n,i)}function wt(t,e){for(var n=e.length,r=0,i=0,o=at(t),a=X(),s=0;si&&(i=r);return a=X()-a,ut("Parsed "+n+" HTML elements"),ut("Element position calculated in "+a+"ms"),function(t){t>N/2&&ut("Event throttle increased to "+(N=2*t)+"ms")}(a),i}function St(t){return[t.bodyOffset(),t.bodyScroll(),t.documentElementOffset(),t.documentElementScroll()]}function Ct(t,e){var n=document.querySelectorAll("["+e+"]");return 0===n.length&&(ct("No tagged elements ("+e+") found on page"),document.querySelectorAll("body *")),wt(t,n)}function It(){return document.querySelectorAll("body *")}function Pt(t,n,r,i){var o,a;!function(){function t(t,e){return!(Math.abs(t-e)<=x)}return o=e!==r?r:tt[m](),a=e!==i?i:et[L](),t(f,o)||d&&t(D,a)}()&&"init"!==t?!(t in{init:1,interval:1,size:1})&&(m in E||d&&L in E)?kt(n):t in{interval:1}||ut("No change in size detected"):(At(),Tt(f=o,D=a,t))}function Et(t,e,n,r){M&&t in l?ut("Trigger event cancelled: "+t):(t in{reset:1,resetPage:1,init:1}||ut("Trigger event: "+e),"init"===t?Pt(t,e,n,r):nt(t,e,n,r))}function At(){M||(M=!0,ut("Trigger event lock on")),clearTimeout(R),R=setTimeout((function(){M=!1,ut("Trigger event lock off"),ut("--")}),p)}function Ot(t){f=tt[m](),D=et[L](),Tt(f,D,t)}function kt(t){var e=m;m=y,ut("Reset trigger event: "+t),At(),Ot("reset"),m=e}function Tt(t,n,r,i,o){var a;!0===O&&(e===o?o=T:ut("Message targetOrigin: "+o),ut("Sending message to host page ("+(a=P+":"+t+":"+n+":"+r+(e!==i?":"+i:""))+")"),k.postMessage(C+a,o))}function xt(e){var n,r={init:function(){g=e.data,k=e.source,dt(),h=!1,setTimeout((function(){_=!1}),p)},reset:function(){_?ut("Page reset ignored by init"):(ut("Page size reset by host page"),Ot("resetPage"))},resize:function(){Et("resizeParent","Parent window requested size check")},moveToAnchor:function(){v.findTarget(o())},inPageLink:function(){this.moveToAnchor()},pageInfo:function(){var t=o();ut("PageInfoFromParent called from parent: "+t),j(JSON.parse(t)),ut(" --")},message:function(){var t=o();ut("MessageCallback called from parent: "+t),U(JSON.parse(t)),ut(" --")}};function i(){return e.data.split("]")[1].split(":")[0]}function o(){return e.data.substr(e.data.indexOf(":")+1)}function a(){return e.data.split(":")[2]in{true:1,false:1}}C===(""+e.data).substr(0,I)&&(!1===h?(n=i())in r?r[n]():!t.exports&&"iFrameResize"in window||"jQuery"in window&&"iFrameResize"in window.jQuery.prototype||a()||ct("Unexpected message ("+e.data+")"):a()?r.init():ut('Ignored message of type "'+i()+'". Received before initialization.'))}function Mt(){"loading"!==document.readyState&&window.parent.postMessage("[iFrameResizerChild]Ready","*")}}()},1310:(t,e,n)=>{function r(t){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},r(t)}t=n.nmd(t),n(93942),n(70472),n(93270),n(51725),n(6550),n(38490),n(64668),n(16516),n(99023),n(40737),n(50633),n(10951),n(34500),n(71806),n(5193),function(e){"use strict";if("undefined"!=typeof window){var n,i=0,o=!1,a=!1,s="message".length,u="[iFrameSizer]",c=u.length,d=null,l=window.requestAnimationFrame,p={max:1,scroll:1,bodyScroll:1,documentElementScroll:1},h={},f=null,y={autoResize:!0,bodyBackground:null,bodyMargin:null,bodyMarginV1:8,bodyPadding:null,checkOrigin:!0,inPageLinks:!1,enablePublicMethods:!0,heightCalculationMethod:"bodyOffset",id:"iFrameResizer",interval:32,log:!1,maxHeight:1/0,maxWidth:1/0,minHeight:0,minWidth:0,resizeFrom:"parent",scrolling:!1,sizeHeight:!0,sizeWidth:!1,warningTimeout:5e3,tolerance:0,widthCalculationMethod:"scroll",closedCallback:function(){},initCallback:function(){},messageCallback:function(){C("MessageCallback function not defined")},resizedCallback:function(){},scrollCallback:function(){return!0}},m={};window.jQuery&&((n=window.jQuery).fn?n.fn.iFrameResize||(n.fn.iFrameResize=function(t){return this.filter("iframe").each((function(e,n){L(n,t)})).end()}):S("","Unable to bind to jQuery, it is not fully loaded.")),"function"==typeof define&&define.amd?define([],q):"object"===r(t)&&"object"===r(t.exports)&&(t.exports=q()),window.iFrameResize=window.iFrameResize||q()}function _(){return window.MutationObserver||window.WebKitMutationObserver||window.MozMutationObserver}function g(t,e,n){"addEventListener"in window?t.addEventListener(e,n,!1):"attachEvent"in window&&t.attachEvent("on"+e,n)}function v(t,e,n){"removeEventListener"in window?t.removeEventListener(e,n,!1):"detachEvent"in window&&t.detachEvent("on"+e,n)}function b(t){return h[t]?h[t].log:o}function w(t,e){I("log",t,e,b(t))}function S(t,e){I("info",t,e,b(t))}function C(t,e){I("warn",t,e,!0)}function I(t,e,n,i){!0===i&&"object"===r(window.console)&&console[t](function(t){return u+"["+function(t){var e="Host page: "+t;return window.top!==window.self&&(e=window.parentIFrame&&window.parentIFrame.getId?window.parentIFrame.getId()+": "+t:"Nested host page: "+t),e}(t)+"]"}(e),n)}function P(t){function e(){n("Height"),n("Width"),N((function(){R(I),T(P),p("resizedCallback",I)}),I,"init")}function n(t){var e=Number(h[P]["max"+t]),n=Number(h[P]["min"+t]),r=t.toLowerCase(),i=Number(I[r]);w(P,"Checking "+r+" is in range "+n+"-"+e),ie&&(i=e,w(P,"Set "+r+" to max value")),I[r]=""+i}function r(t){return b.substr(b.indexOf(":")+s+t)}function i(t,e){var n,r;n=function(){var n,r;D("Send Page Info","pageInfo:"+(n=document.body.getBoundingClientRect(),r=I.iframe.getBoundingClientRect(),JSON.stringify({iframeHeight:r.height,iframeWidth:r.width,clientHeight:Math.max(document.documentElement.clientHeight,window.innerHeight||0),clientWidth:Math.max(document.documentElement.clientWidth,window.innerWidth||0),offsetTop:parseInt(r.top-n.top,10),offsetLeft:parseInt(r.left-n.left,10),scrollTop:window.pageYOffset,scrollLeft:window.pageXOffset})),t,e)},m[r=e]||(m[r]=setTimeout((function(){m[r]=null,n()}),32))}function o(t){var e=t.getBoundingClientRect();return k(P),{x:Math.floor(Number(e.left)+Number(d.x)),y:Math.floor(Number(e.top)+Number(d.y))}}function a(t){var e=t?o(I.iframe):{x:0,y:0},n={x:Number(I.width)+e.x,y:Number(I.height)+e.y};w(P,"Reposition requested from iFrame (offset x:"+e.x+" y:"+e.y+")"),window.top!==window.self?window.parentIFrame?window.parentIFrame["scrollTo"+(t?"Offset":"")](n.x,n.y):C(P,"Unable to scroll to requested position, window.parentIFrame not found"):(d=n,l(),w(P,"--"))}function l(){!1!==p("scrollCallback",d)?T(P):x()}function p(t,e){return E(P,t,e)}var f,y,_,b=t.data,I={},P=null;"[iFrameResizerChild]Ready"===b?function(){for(var t in h)D("iFrame requested init",z(t),document.getElementById(t),t)}():u===(""+b).substr(0,c)&&b.substr(c).split(":")[0]in h?(_=b.substr(c).split(":"),I={iframe:h[_[0]]&&h[_[0]].iframe,id:_[0],height:_[1],width:_[2],type:_[3]},P=I.id,h[P]&&(h[P].loaded=!0),(y=I.type in{true:1,false:1,undefined:1})&&w(P,"Ignoring init message from meta parent page"),!y&&function(t){var e=!0;return h[t]||(e=!1,C(I.type+" No settings for "+t+". Message was: "+b)),e}(P)&&(w(P,"Received: "+b),f=!0,null===I.iframe&&(C(P,"IFrame ("+I.id+") not found"),f=!1),f&&function(){var e,n=t.origin,r=h[P]&&h[P].checkOrigin;if(r&&""+n!="null"&&!(r.constructor===Array?function(){var t=0,e=!1;for(w(P,"Checking connection is from allowed list of origins: "+r);th[u]["max"+t])throw new Error("Value for min"+t+" can not be greater than max"+t)}n("Height"),n("Width"),e("maxHeight"),e("minHeight"),e("maxWidth"),e("minWidth")}(),"number"!=typeof(h[u]&&h[u].bodyMargin)&&"0"!==(h[u]&&h[u].bodyMargin)||(h[u].bodyMarginV1=h[u].bodyMargin,h[u].bodyMargin=h[u].bodyMargin+"px"),a=z(u),(s=_())&&function(e){t.parentNode&&new e((function(e){e.forEach((function(e){Array.prototype.slice.call(e.removedNodes).forEach((function(e){e===t&&O(t)}))}))})).observe(t.parentNode,{childList:!0})}(s),g(t,"load",(function(){var n,r;D("iFrame.onload",a,t,e,!0),n=h[u]&&h[u].firstRun,r=h[u]&&h[u].heightCalculationMethod in p,!n&&r&&M({iframe:t,height:0,width:0,type:"init"})})),D("init",a,t,e,!0),Function.prototype.bind&&h[u]&&(h[u].iframe.iFrameResizer={close:O.bind(null,h[u].iframe),removeListeners:A.bind(null,h[u].iframe),resize:D.bind(null,"Window resize","resize",h[u].iframe),moveToAnchor:function(t){D("Move to anchor","moveToAnchor:"+t,h[u].iframe,u)},sendMessage:function(t){D("Send Message","message:"+(t=JSON.stringify(t)),h[u].iframe,u)}}))}function F(t,e){null===f&&(f=setTimeout((function(){f=null,t()}),e))}function U(t){w("window","Trigger event: "+t),F((function(){j("Window "+t,"resize")}),16)}function B(){"hidden"!==document.visibilityState&&(w("document","Trigger event: Visiblity change"),F((function(){j("Tab Visable","resize")}),16))}function j(t,e){function n(t){return h[t]&&"parent"===h[t].resizeFrom&&h[t].autoResize&&!h[t].firstRun}for(var r in h)n(r)&&D(t,e,document.getElementById(r),r)}function q(){function t(t,e){e&&(function(){if(!e.tagName)throw new TypeError("Object is not a valid DOM element");if("IFRAME"!==e.tagName.toUpperCase())throw new TypeError("Expected